File: itkANTSImageRegistrationOptimizer.cxx

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

  Program:   Advanced Normalization Tools
  Module:    $RCSfile: itkANTSImageRegistrationOptimizer.cxx,v $
  Language:  C++
  Date:      $Date: 2009/04/22 01:00:16 $
  Version:   $Revision: 1.47 $

  Copyright (c) ConsortiumOfANTS. All rights reserved.
  See accompanying COPYING.txt or 
 http://sourceforge.net/projects/advants/files/ANTS/ANTSCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#ifndef _itkANTSImageRegistrationOptimizer_txx_ 
#define _itkANTSImageRegistrationOptimizer_txx_
 
// disable debug warnings in MS compiler
#ifdef _MSC_VER
#pragma warning(disable: 4786)
#endif
#include "itkVectorParameterizedNeighborhoodOperatorImageFilter.h"
#include "itkANTSImageRegistrationOptimizer.h"
#include "itkIdentityTransform.h"
#include "itkLinearInterpolateImageFunction.h"
#include "itkRecursiveGaussianImageFilter.h"
#include "itkVectorGaussianInterpolateImageFunction.h"
#include "itkResampleImageFilter.h"
#include "itkVectorNeighborhoodOperatorImageFilter.h"
#include "vnl/vnl_math.h"
#include "ANTS_affine_registration2.h"
#include "itkWarpImageMultiTransformFilter.h"
#include "itkVectorImageFileWriter.h"

namespace itk
{


template<unsigned int TDimension, class TReal>
ANTSImageRegistrationOptimizer<TDimension, TReal>
::ANTSImageRegistrationOptimizer()
{
    this->m_DeformationField=NULL;
    this->m_InverseDeformationField=NULL;
    this->m_AffineTransform=NULL;
    itk::TransformFactory<TransformType>::RegisterTransform();    
    itk::TransformFactory<itk::ANTSAffine3DTransform<double> >::RegisterTransform();
    itk::TransformFactory<itk::ANTSCenteredAffine2DTransform<double> >::RegisterTransform();
    this->m_FixedPointSet=NULL;
    this->m_MovingPointSet=NULL;

    this->m_UseMulti=true;
    this->m_UseROI=false;
    this->m_MaskImage=NULL;
    this->m_ScaleFactor=1.0;
    this->m_Debug=false;

    this->m_SyNF=NULL;
    this->m_SyNFInv=NULL;
    this->m_SyNM=NULL;
    this->m_SyNMInv=NULL;
    this->m_Parser=NULL;
    this->m_GaussianTruncation=256;
    this->m_TimeVaryingVelocity=NULL;
    this->m_LastTimeVaryingVelocity=NULL;
    this->m_LastTimeVaryingUpdate=NULL;
    this->m_DeltaTime=0.1;
    this->m_SyNType=0;
    this->m_UseNN=false;
    this->m_UseBSplineInterpolation=false;    
    this->m_VelocityFieldInterpolator=VelocityFieldInterpolatorType::New();
    this->m_HitImage=NULL;
    this->m_ThickImage=NULL;
    this->m_SyNFullTime=0;
}



template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::ImagePointer 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::SubsampleImage( ImagePointer image, RealType scalingFactor , typename ImageType::PointType outputOrigin,  typename ImageType::DirectionType outputDirection , AffineTransformPointer aff )
{
    typename ImageType::SpacingType inputSpacing = image->GetSpacing();
    typename ImageType::RegionType::SizeType inputSize = image->GetRequestedRegion().GetSize();

    typename ImageType::SpacingType outputSpacing=this->m_CurrentDomainSpacing;
    typename ImageType::RegionType::SizeType outputSize=this->m_CurrentDomainSize;

//    RealType minimumSpacing = inputSpacing.GetVnlVector().min_value();  
//    RealType maximumSpacing = inputSpacing.GetVnlVector().max_value();  

    typedef ResampleImageFilter<ImageType, ImageType> ResamplerType;
    typename ResamplerType::Pointer resampler = ResamplerType::New();
    typedef LinearInterpolateImageFunction<ImageType, double> InterpolatorType;
    typename InterpolatorType::Pointer interpolator = InterpolatorType::New();
    interpolator->SetInputImage( image );
    resampler->SetInterpolator( interpolator ); 
    typedef itk::IdentityTransform< double, TDimension >  TransformType; 
    typename TransformType::Pointer transform = TransformType::New();
    transform->SetIdentity();
    resampler->SetTransform( transform );
    if ( aff ) 
      {
//      std::cout << " Setting Aff to " << this->m_AffineTransform << std::endl;
      resampler->SetTransform( aff );
      }
    resampler->SetInput( image );
    resampler->SetOutputSpacing( outputSpacing );
    resampler->SetOutputOrigin( outputOrigin );
    resampler->SetOutputDirection( outputDirection );
    resampler->SetSize( outputSize );
    resampler->Update();

    ImagePointer outimage = resampler->GetOutput();

    if (this->m_UseROI ) 
      {
       outimage=this->MakeSubImage(outimage);
//       WriteImage<ImageType>(outimage,"temps.hdr");
    // warp with affine & deformable 
      }

    return outimage;
}

template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::DeformationFieldPointer 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::CopyDeformationField(
  DeformationFieldPointer input
)
{
        DeformationFieldPointer output=DeformationFieldType::New();
        output->SetSpacing( input->GetSpacing() );
        output->SetOrigin( input->GetOrigin() );
        output->SetDirection( input->GetDirection() );
        output->SetLargestPossibleRegion(input->GetLargestPossibleRegion() );
        output->SetRequestedRegion(input->GetLargestPossibleRegion() );
        output->SetBufferedRegion( input->GetLargestPossibleRegion() );
        output->Allocate();

    typedef ImageRegionIterator<DeformationFieldType> Iterator;
    Iterator inIter( input, input->GetBufferedRegion() );
    Iterator outIter( output, output->GetBufferedRegion() );
    inIter.GoToBegin();
    outIter.GoToBegin();
    for( ; !inIter.IsAtEnd(); ++inIter, ++outIter )
    {
        outIter.Set( inIter.Get() );
    }

    output->SetSpacing( input->GetSpacing());
    output->SetOrigin(input->GetOrigin());

    return output;
}




template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::SmoothDeformationFieldGauss(DeformationFieldPointer field, float sig, bool useparamimage, unsigned int lodim)
{
  if (this->m_Debug ) std::cout << " enter gauss smooth " <<  sig  << std::endl;
  if (sig <= 0) return;
  if (!field) { std::cout << " No Field in gauss Smoother " << std::endl; return; }
    DeformationFieldPointer tempField=DeformationFieldType::New();
    tempField->SetSpacing( field->GetSpacing() );
    tempField->SetOrigin( field->GetOrigin() );
    tempField->SetDirection( field->GetDirection() );
    tempField->SetLargestPossibleRegion( 
            field->GetLargestPossibleRegion() );
    tempField->SetRequestedRegion(
            field->GetRequestedRegion() );
    tempField->SetBufferedRegion( field->GetBufferedRegion() );
    tempField->Allocate();

    typedef typename DeformationFieldType::PixelType VectorType;
    typedef typename VectorType::ValueType           ScalarType;
    typedef GaussianOperator<ScalarType,ImageDimension> OperatorType;
    // typedef VectorNeighborhoodOperatorImageFilter< DeformationFieldType,    DeformationFieldType> SmootherType;
    typedef VectorParameterizedNeighborhoodOperatorImageFilter<
    DeformationFieldType,
    DeformationFieldType, ImageType> SmootherType;
  
    OperatorType * oper = new OperatorType;
    typename SmootherType::Pointer smoother = SmootherType::New();

    typedef typename DeformationFieldType::PixelContainerPointer 
    PixelContainerPointer;
    PixelContainerPointer swapPtr;

    // graft the output field onto the mini-pipeline
    smoother->GraftOutput( tempField );

    typename ImageType::SpacingType spacing=field->GetSpacing();
    for( unsigned int j = 0; j < lodim; j++ )
    {
        // smooth along this dimension
        oper->SetDirection( j );
        float sigt=sig;
        oper->SetVariance( sigt );
        oper->SetMaximumError(0.001 );
        oper->SetMaximumKernelWidth( (unsigned int) this->m_GaussianTruncation );
        oper->CreateDirectional();

        // todo: make sure we only smooth within the buffered region
        smoother->SetOperator( *oper );
        smoother->SetInput( field );
        smoother->Update();

        if ( j < lodim - 1 )
        {
            // swap the containers
            swapPtr = smoother->GetOutput()->GetPixelContainer();
            smoother->GraftOutput( field );
            field->SetPixelContainer( swapPtr );
            smoother->Modified();
        }

    }

    // graft the output back to this filter
    tempField->SetPixelContainer( field->GetPixelContainer() );




    //make sure boundary does not move
    float weight=1.0;
    if (sig < 0.5) weight=1.0-1.0*(sig/0.5);
    float weight2=1.0-weight;
    typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;  
    typename DeformationFieldType::SizeType size = field->GetLargestPossibleRegion().GetSize();
    Iterator outIter( field, field->GetLargestPossibleRegion() );
    for( outIter.GoToBegin(); !outIter.IsAtEnd(); ++outIter )
    {
        bool onboundary=false;
        typename DeformationFieldType::IndexType index= outIter.GetIndex();
        for (int i=0;i<ImageDimension;i++) 
        {
            if (index[i] < 1 || index[i] >= static_cast<int>( size[i] )-1 ) onboundary=true;
        }
        if (onboundary) 
        {
            VectorType vec;
            vec.Fill(0.0);
            outIter.Set(vec);
        } else {
	//field=this->CopyDeformationField( 
	VectorType svec=smoother->GetOutput()->GetPixel(index);
	outIter.Set( svec*weight+outIter.Get()*weight2);
	}
    }

  if (this->m_Debug ) std::cout << " done gauss smooth " << std::endl;

    delete oper;

}



template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::SmoothVelocityGauss(TimeVaryingVelocityFieldPointer field, float sig , unsigned int lodim)
{
  if (sig <= 0) return;
  if (!field) { std::cout << " No Field in gauss Smoother " << std::endl; return; }
    TimeVaryingVelocityFieldPointer tempField=TimeVaryingVelocityFieldType::New();
    tempField->SetSpacing( field->GetSpacing() );
    tempField->SetOrigin( field->GetOrigin() );
    tempField->SetDirection( field->GetDirection() );
    tempField->SetLargestPossibleRegion( 
            field->GetLargestPossibleRegion() );
    tempField->SetRequestedRegion(
            field->GetRequestedRegion() );
    tempField->SetBufferedRegion( field->GetBufferedRegion() );
    tempField->Allocate();

    typedef typename TimeVaryingVelocityFieldType::PixelType VectorType;
    typedef typename VectorType::ValueType           ScalarType;
    typedef GaussianOperator<ScalarType,ImageDimension+1> OperatorType;
    typedef VectorNeighborhoodOperatorImageFilter<TimeVaryingVelocityFieldType,
      TimeVaryingVelocityFieldType> SmootherType;
  
    OperatorType * oper = new OperatorType;
    typename SmootherType::Pointer smoother = SmootherType::New();

    typedef typename TimeVaryingVelocityFieldType::PixelContainerPointer 
    PixelContainerPointer;
    PixelContainerPointer swapPtr;

    // graft the output field onto the mini-pipeline
    smoother->GraftOutput( tempField );

    for( unsigned int j = 0; j < lodim; j++ )
    {
        // smooth along this dimension
        oper->SetDirection( j );
        oper->SetVariance( sig );
        oper->SetMaximumError(0.001 );
        oper->SetMaximumKernelWidth( (unsigned int) this->m_GaussianTruncation );
        oper->CreateDirectional();

        // todo: make sure we only smooth within the buffered region
        smoother->SetOperator( *oper );
        smoother->SetInput( field );
        smoother->Update();

        if ( j < lodim - 1 )
        {
            // swap the containers
            swapPtr = smoother->GetOutput()->GetPixelContainer();
            smoother->GraftOutput( field );
            field->SetPixelContainer( swapPtr );
            smoother->Modified();
        }

    }

    // graft the output back to this filter
    tempField->SetPixelContainer( field->GetPixelContainer() );

    //make sure boundary does not move
    float weight=1.0;
    if (sig < 0.5) weight=1.0-1.0*(sig/0.5);
    float weight2=1.0-weight;
    typedef itk::ImageRegionIteratorWithIndex<TimeVaryingVelocityFieldType> Iterator;  
    typename TimeVaryingVelocityFieldType::SizeType size = field->GetLargestPossibleRegion().GetSize();
    Iterator outIter( field, field->GetLargestPossibleRegion() );
    for( outIter.GoToBegin(); !outIter.IsAtEnd(); ++outIter )
    {
        bool onboundary=false;
        typename TimeVaryingVelocityFieldType::IndexType index= outIter.GetIndex();
        for (int i=0;i<ImageDimension;i++) 
        {
            if (index[i] < 1 || index[i] >= static_cast<int>( size[i] )-1 ) onboundary=true;
        }
        if (onboundary) 
        {
            VectorType vec;
            vec.Fill(0.0);
            outIter.Set(vec);
        } else {
	//field=this->CopyDeformationField( 
	VectorType svec=smoother->GetOutput()->GetPixel(index);
	outIter.Set( svec*weight+outIter.Get()*weight2);
	}
    }

  if (this->m_Debug ) std::cout << " done gauss smooth " << std::endl;

    delete oper;

}

template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::SmoothDeformationFieldBSpline( DeformationFieldPointer field, ArrayType meshsize, 
      unsigned int splineorder, unsigned int numberoflevels )
{
  if (this->m_Debug ) std::cout << " enter bspline smooth " << std::endl;
  if (!field) { std::cout << " No Field in bspline Smoother " << std::endl; return; }

  if ( splineorder <= 0 )
    {
    return;     
    }

  typename BSplineFilterType::ArrayType numberofcontrolpoints;
  for ( unsigned int d = 0; d < ImageDimension; d++ )
    {
    if ( meshsize[d] <= 0 )
      {
      return; 
      } 
     
    numberofcontrolpoints[d] = static_cast<unsigned int>( meshsize[d] ) + splineorder;
    }  
  VectorType zeroVector;
  zeroVector.Fill( 0.0 );
  
//  typedef VectorImageFileWriter<DeformationFieldType, ImageType> 
//    DeformationFieldWriterType;
//  typename DeformationFieldWriterType::Pointer writer = DeformationFieldWriterType::New();
//  writer->SetInput( field );
//  writer->SetFileName( "field.nii.gz" ); 
//  writer->Update();
//  exit( 0 ); 

  typename ImageType::DirectionType originalDirection = field->GetDirection();
  typename ImageType::DirectionType identityDirection;
  identityDirection.SetIdentity();
  field->SetDirection( identityDirection );
  
  typename BSplineFilterType::Pointer bspliner = BSplineFilterType::New();
  bspliner->SetInput( field );
  bspliner->SetNumberOfLevels( numberoflevels );
  bspliner->SetSplineOrder( splineorder );
  bspliner->SetNumberOfControlPoints( numberofcontrolpoints );
  bspliner->SetIgnorePixelValue( zeroVector ); 
  bspliner->Update();
  
  field->SetDirection( originalDirection );
  
    //make sure boundary does not move
  typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;  
  typename DeformationFieldType::SizeType size = field->GetLargestPossibleRegion().GetSize();
  Iterator bIter( bspliner->GetOutput(), bspliner->GetOutput()->GetLargestPossibleRegion() );
  Iterator outIter( field, field->GetLargestPossibleRegion() );
  for( outIter.GoToBegin(), bIter.GoToBegin(); 
     !outIter.IsAtEnd(); ++outIter, ++bIter )
    {
//    bool onboundary=false;
//    typename DeformationFieldType::IndexType index = outIter.GetIndex();
//    for( int i = 0; i < ImageDimension; i++ ) 
//      {
//      if ( index[i] < 1 || index[i] >= static_cast<int>( size[i] )-1 ) 
//        onboundary = true;
//      }
//    if (onboundary) 
//      {
//      VectorType vec;
//      vec.Fill(0.0);
//      outIter.Set(vec);
//      }
//    else
//      {
      outIter.Set( bIter.Get() ); 
//      }
    }

  if (this->m_Debug ) std::cout << " done bspline smooth " << std::endl;

}

template<unsigned int TDimension, class TReal>
void 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::ComposeDiffs(DeformationFieldPointer fieldtowarpby, DeformationFieldPointer field, DeformationFieldPointer fieldout, float timesign)
{

  typedef Point<float,itkGetStaticConstMacro(ImageDimension)> VPointType;
  
//  field->SetSpacing( fieldtowarpby->GetSpacing() );
//  field->SetOrigin( fieldtowarpby->GetOrigin() );
//  field->SetDirection( fieldtowarpby->GetDirection() );
  
  if (!fieldout)
    {
    fieldout=DeformationFieldType::New();
    fieldout->SetSpacing( fieldtowarpby->GetSpacing() );
    fieldout->SetOrigin( fieldtowarpby->GetOrigin() );
    fieldout->SetDirection( fieldtowarpby->GetDirection() );
    fieldout->SetLargestPossibleRegion(fieldtowarpby->GetLargestPossibleRegion()  );
    fieldout->SetRequestedRegion( fieldtowarpby->GetLargestPossibleRegion()   );
    fieldout->SetBufferedRegion( fieldtowarpby->GetLargestPossibleRegion()  );
    fieldout->Allocate();
    VectorType zero;  zero.Fill(0);
    fieldout->FillBuffer(zero);
    }
    typedef typename DeformationFieldType::PixelType VectorType;
    
    typedef itk::WarpImageFilter<ImageType,ImageType, DeformationFieldType> WarperType;
    typedef DeformationFieldType FieldType;  
    enum { ImageDimension = FieldType::ImageDimension };
    typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType>         FieldIterator; 
    typedef ImageType FloatImageType;
    
    typedef itk::ImageFileWriter<ImageType> writertype;

    typename ImageType::SpacingType oldspace = field->GetSpacing();
    typename ImageType::SpacingType newspace = fieldtowarpby->GetSpacing();
    
    
    typedef typename DeformationFieldType::IndexType IndexType;
    typedef typename DeformationFieldType::PointType PointType;
    

    typedef itk::VectorLinearInterpolateImageFunction<DeformationFieldType,float> DefaultInterpolatorType;
    typedef itk::VectorGaussianInterpolateImageFunction<DeformationFieldType,float> DefaultInterpolatorType2;
    typename DefaultInterpolatorType::Pointer vinterp =  DefaultInterpolatorType::New();
    vinterp->SetInputImage(field);
    //    vinterp->SetParameters(NULL,1);
    
    
    VPointType pointIn1;
    VPointType pointIn2;
    typename DefaultInterpolatorType::ContinuousIndexType  contind; // married to pointIn2
    VPointType pointIn3;
    unsigned int ct=0;
    // iterate through fieldtowarpby finding the points that it maps to via field.  
    // then take the difference from the original point and put it in the output field.
    //      std::cout << " begin iteration " << std::endl;
    FieldIterator m_FieldIter( fieldtowarpby, fieldtowarpby->GetLargestPossibleRegion());
    for(  m_FieldIter.GoToBegin(); !m_FieldIter.IsAtEnd(); ++m_FieldIter )
      {
      IndexType index = m_FieldIter.GetIndex();
      bool dosample = true;
      //	  if (sub && m_FloatImage->GetPixel(index) < 0.5) dosample=false;
      if (dosample)
        {
	
	fieldtowarpby->TransformIndexToPhysicalPoint( index, pointIn1 );
	VectorType disp=m_FieldIter.Get();
	for (int jj=0; jj<ImageDimension; jj++)
	  {
	  pointIn2[jj]=disp[jj]+pointIn1[jj];
	  }
	typename DefaultInterpolatorType::OutputType disp2;
	if (vinterp->IsInsideBuffer(pointIn2)) disp2 = vinterp->Evaluate( pointIn2 );
	else disp2.Fill(0);
	for (int jj=0; jj<ImageDimension; jj++) pointIn3[jj]=disp2[jj]*timesign+pointIn2[jj];
	
	VectorType out;
	for (int jj=0; jj<ImageDimension; jj++) out[jj]=pointIn3[jj]-pointIn1[jj];
	
	fieldout->SetPixel(m_FieldIter.GetIndex(),out);
	ct++;
	
        }//endif
      }//end iteration
}


template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::DeformationFieldPointer 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::IntegrateConstantVelocity(DeformationFieldPointer totalField, unsigned int ntimesteps, float timestep)
{
    VectorType zero;
    zero.Fill(0);
    DeformationFieldPointer diffmap=DeformationFieldType::New();
    diffmap->SetSpacing( totalField->GetSpacing() );
    diffmap->SetOrigin( totalField->GetOrigin() );
    diffmap->SetDirection( totalField->GetDirection() );
    diffmap->SetLargestPossibleRegion(totalField->GetLargestPossibleRegion()  );
    diffmap->SetRequestedRegion( totalField->GetLargestPossibleRegion()   );
    diffmap->SetBufferedRegion( totalField->GetLargestPossibleRegion()  );
    diffmap->Allocate();
    diffmap->FillBuffer(zero);

    for (unsigned int nts=0; nts<ntimesteps; nts++)
    {
        this->ComposeDiffs(diffmap,totalField,diffmap, timestep);	  
    }
    return diffmap;

}


template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::DeformationFieldPointer 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::ComputeUpdateField(DeformationFieldPointer fixedwarp, DeformationFieldPointer movingwarp ,   PointSetPointer fpoints, PointSetPointer wpoints, DeformationFieldPointer totalUpdateInvField, bool updateenergy)
{
  
  ImagePointer mask=NULL;
  if ( movingwarp && this->m_MaskImage && !this->m_ComputeThickness )
    mask= this->WarpMultiTransform( this->m_MaskImage, this->m_MaskImage, NULL, movingwarp, false , this->m_FixedImageAffineTransform );
  else if (this->m_MaskImage && !this->m_ComputeThickness  ) mask=this->SubsampleImage( this->m_MaskImage, this->m_ScaleFactor , this->m_MaskImage->GetOrigin() , this->m_MaskImage->GetDirection() ,  NULL);
  
  if ( !fixedwarp) {std::cout<< " NO F WARP " << std::endl;  fixedwarp=this->m_DeformationField; }
  //if ( !movingwarp) std::cout<< " NO M WARP " << std::endl;

    ///     std::cout << " get upd field " << std::endl;
    typename ImageType::SpacingType spacing=fixedwarp->GetSpacing(); 
    VectorType zero;
    zero.Fill(0);
    DeformationFieldPointer updateField=NULL,totalUpdateField=NULL,updateFieldInv=NULL;
    totalUpdateField=DeformationFieldType::New();
    totalUpdateField->SetSpacing( fixedwarp->GetSpacing() );
    totalUpdateField->SetOrigin( fixedwarp->GetOrigin() );
    totalUpdateField->SetDirection( fixedwarp->GetDirection() );
    totalUpdateField->SetLargestPossibleRegion(fixedwarp->GetLargestPossibleRegion()  );
    totalUpdateField->SetRequestedRegion( fixedwarp->GetLargestPossibleRegion()   );
    totalUpdateField->SetBufferedRegion( fixedwarp->GetLargestPossibleRegion()  );
    totalUpdateField->Allocate();
    totalUpdateField->FillBuffer(zero);
//    bool hadpointsetmetric=false;

    RealType sumWeights = 0.0;
    for( unsigned int n = 0; n < this->m_SimilarityMetrics.size(); n++ ) 
      { 
      sumWeights += this->m_SimilarityMetrics[n]->GetWeightScalar();
      }
    sumWeights=1;

    for ( unsigned int metricCount = 0; metricCount < this->m_SimilarityMetrics.size(); metricCount++ ) 
    { 
         bool ispointsetmetric=false;

        /** build an update field */
       if (  this->m_SimilarityMetrics.size() == 1 ) 
        {
          updateField=totalUpdateField;
          if (totalUpdateInvField) updateFieldInv=totalUpdateInvField;
        }
        else {
          updateField=DeformationFieldType::New();
          updateField->SetSpacing( fixedwarp->GetSpacing() );
          updateField->SetOrigin( fixedwarp->GetOrigin() );
          updateField->SetDirection( fixedwarp->GetDirection() );
          updateField->SetLargestPossibleRegion(fixedwarp->GetLargestPossibleRegion()  );
          updateField->SetRequestedRegion( fixedwarp->GetLargestPossibleRegion()   );
          updateField->SetBufferedRegion( fixedwarp->GetLargestPossibleRegion()  );
          updateField->Allocate();
          updateField->FillBuffer(zero);
          if (totalUpdateInvField){
            updateFieldInv=DeformationFieldType::New();
            updateFieldInv->SetSpacing( fixedwarp->GetSpacing() );
            updateFieldInv->SetOrigin( fixedwarp->GetOrigin() );
            updateFieldInv->SetDirection( fixedwarp->GetDirection() );
            updateFieldInv->SetLargestPossibleRegion(fixedwarp->GetLargestPossibleRegion()  );
            updateFieldInv->SetRequestedRegion( fixedwarp->GetLargestPossibleRegion()   );
            updateFieldInv->SetBufferedRegion( fixedwarp->GetLargestPossibleRegion()  );
            updateFieldInv->Allocate();
            updateFieldInv->FillBuffer(zero);
           }
         }

        /** get the update */
        typedef DeformationFieldType DeformationFieldType;
        typedef typename FiniteDifferenceFunctionType::NeighborhoodType
        NeighborhoodIteratorType;
        typedef ImageRegionIterator<DeformationFieldType> UpdateIteratorType;
 
//        TimeStepType timeStep;
        void *globalData;
//	std::cout << " B " << std::endl;

    AffineTransformPointer faffinverse=NULL;
    if (this->m_FixedImageAffineTransform ){
    faffinverse=AffineTransformType::New();
    this->m_FixedImageAffineTransform->GetInverse(faffinverse);
    }
    AffineTransformPointer affinverse=NULL;
    if (this->m_AffineTransform ){
    affinverse=AffineTransformType::New();
    this->m_AffineTransform->GetInverse(affinverse);
    }

// for each metric, warp the assoc. Images 
/** We loop Over This To Do MultiVariate */
   /** FIXME really should pass an image list and then warp each one in
         turn  then expand the update field to fit size of total
         deformation */
        ImagePointer wmimage=NULL;
	        if ( fixedwarp)
	 wmimage= this->WarpMultiTransform(  this->m_SmoothFixedImages[metricCount],this->m_SmoothMovingImages[metricCount], this->m_AffineTransform, fixedwarp, false , NULL );
        else wmimage=this->SubsampleImage( this->m_SmoothMovingImages[metricCount] , this->m_ScaleFactor , this->m_SmoothMovingImages[metricCount]->GetOrigin() , this->m_SmoothMovingImages[metricCount]->GetDirection() ,  NULL);
   
//	std::cout << " C " << std::endl;
        ImagePointer wfimage=NULL;
        if ( movingwarp)
	          wfimage= this->WarpMultiTransform( this->m_SmoothFixedImages[metricCount], this->m_SmoothFixedImages[metricCount], NULL, movingwarp, false , this->m_FixedImageAffineTransform );
        else wfimage=this->SubsampleImage( this->m_SmoothFixedImages[metricCount] , this->m_ScaleFactor , this->m_SmoothFixedImages[metricCount]->GetOrigin() , this->m_SmoothFixedImages[metricCount]->GetDirection() ,  NULL);
	/*
	if (this->m_TimeVaryingVelocity && ! this->m_MaskImage ) {
	  std::string outname=this->localANTSGetFilePrefix(this->m_OutputNamingConvention.c_str())+std::string("thick.nii.gz");
	  ///	  WriteImage<ImageType>(wmimage,outname.c_str());
	  outname=this->localANTSGetFilePrefix(this->m_OutputNamingConvention.c_str())+std::string("thick2.nii.gz");
	  WriteImage<ImageType>(wfimage,outname.c_str());
	}
	*/
	//	  std::string outname=this->localANTSGetFilePrefix(this->m_OutputNamingConvention.c_str())+std::string("temp.nii.gz");
	//	  WriteImage<ImageType>(wmimage,outname.c_str());
	//	  std::string outname2=this->localANTSGetFilePrefix(this->m_OutputNamingConvention.c_str())+std::string("temp2.nii.gz");
	//	  WriteImage<ImageType>(wfimage,outname2.c_str());

/** MV Loop END -- Would have to collect update fields then add them
* together somehow -- Would also have to eliminate the similarity
* metric loop within ComputeUpdateField */

        // Get the FiniteDifferenceFunction to use in calculations.
        MetricBaseTypePointer df = this->m_SimilarityMetrics[metricCount]->GetMetric();
        df->SetFixedImage(wfimage);
        df->SetMovingImage(wmimage);
        if (df->ThisIsAPointSetMetric()) ispointsetmetric=true; 
        if (fpoints && ispointsetmetric )  df->SetFixedPointSet(fpoints); else if (ispointsetmetric ) std::cout << "NO POINTS!! " << std::endl;
        if (wpoints && ispointsetmetric ) df->SetMovingPointSet(wpoints); else if (ispointsetmetric ) std::cout << "NO POINTS!! " << std::endl;
        typename ImageType::SizeType  radius = df->GetRadius();
        df->InitializeIteration();
        typename DeformationFieldType::Pointer output = updateField;
        typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<DeformationFieldType>
        FaceCalculatorType;
        typedef typename FaceCalculatorType::FaceListType FaceListType;
        FaceCalculatorType faceCalculator;
        FaceListType faceList = faceCalculator(updateField, updateField->GetLargestPossibleRegion(), radius);
        typename FaceListType::iterator fIt = faceList.begin();
        globalData = df->GetGlobalDataPointer();

        // Process the non-boundary region.
        NeighborhoodIteratorType nD(radius, updateField, *fIt);
        UpdateIteratorType       nU(updateField,  *fIt);
        nD.GoToBegin();
	nU.GoToBegin();
        while( !nD.IsAtEnd() )
        {
            bool oktosample=true;	       
            float maskprob=1.0;
            if (mask)
             {
                maskprob=mask->GetPixel( nD.GetIndex() );
                if (maskprob > 1.0) maskprob=1.0;
                if ( maskprob < 0.1) oktosample=false;
             }
            if ( oktosample ) 
            {
	        VectorType temp=df->ComputeUpdate(nD, globalData)*maskprob;
                nU.Value() += temp;
                if (totalUpdateInvField)
                 {
		   typename ImageType::IndexType index=nD.GetIndex();
		   temp = df->ComputeUpdateInv(nD, globalData)*maskprob+updateFieldInv->GetPixel(index);
		   updateFieldInv->SetPixel(index,temp);
                 }// else nU.Value() -= df->ComputeUpdateInv(nD, globalData)*maskprob;
		
                ++nD;
                ++nU;
            }
            else
            {
                ++nD;
                ++nU;
            }
        }

	// begin restriction of deformation field 
	bool restrict=false;
	for (unsigned int jj=0; jj<this->m_RestrictDeformation.size();  jj++ )
	  {
	    float temp=this->m_RestrictDeformation[jj];
	    if (  fabs( temp - 1 ) > 1.e-5   ) restrict=true;
	  }
	if (restrict && this->m_RestrictDeformation.size() == ImageDimension )
	  {
	    nU.GoToBegin();
	    while( !nU.IsAtEnd() )
	      {
		for (unsigned int jj=0; jj<this->m_RestrictDeformation.size();  jj++ )
		  {
			typename ImageType::IndexType index=nU.GetIndex();
			VectorType temp = updateField->GetPixel(index);
			temp[jj]*=this->m_RestrictDeformation[jj];
			updateField->SetPixel(index,temp);
			if (updateFieldInv )
			  {
			    temp = updateFieldInv->GetPixel(index);
			    temp[jj]*=this->m_RestrictDeformation[jj];
			    updateFieldInv->SetPixel(index,temp);
			  }
		  }
		++nU;
	      }
	  } // end restrict deformation field 

       if (updateenergy){
         this->m_LastEnergy[metricCount]=this->m_Energy[metricCount];
         this->m_Energy[metricCount]=df->GetEnergy();// *this->m_SimilarityMetrics[metricCount]->GetWeightScalar()/sumWeights; 
        }
       
       // smooth the fields 
       //if (!ispointsetmetric || ImageDimension == 2 ){
            this->SmoothDeformationField(updateField,true);
            if (updateFieldInv) this->SmoothDeformationField(updateFieldInv,true);
	    ///}
       /*
       else // use another strategy -- exact lm? / something like Laplacian 
	 {
	   float tmag=0;
	   for (unsigned int ff=0; ff<5; ff++)
	     {
	       tmag=0;
	       this->SmoothDeformationField(updateField,true);
	       if (updateFieldInv) this->SmoothDeformationField(updateFieldInv,true);
	       nD.GoToBegin();
	       nU.GoToBegin();
	       while( !nD.IsAtEnd() )
		 {
		   typename ImageType::IndexType index=nD.GetIndex();
		   bool oktosample=true;	       
		   float maskprob=1.0;
		   if (mask)
		     {
		       maskprob=mask->GetPixel( nD.GetIndex() );
		       if (maskprob > 1.0) maskprob=1.0;
		       if ( maskprob < 0.1) oktosample=false;
		     }
		   VectorType F1;
		   F1.Fill(0);
		   VectorType F2;
		   F2.Fill(0);
		   if ( oktosample ) 
		     {
		       F1 = df->ComputeUpdate(nD, globalData)*maskprob;
		       if (totalUpdateInvField)
			 { 
			   F2 = df->ComputeUpdateInv(nD, globalData)*maskprob;
			 } 
		       ++nD;
		       ++nU;
		     }
		   else
		     {
		       ++nD;
		       ++nU;
		     }

		   // compute mags of F1 and F2 -- if large enough, reset them
		   float f1mag=0,f2mag=0,umag=0;
		   for (unsigned int dim=0; dim<ImageDimension; dim++)
		     {
		       f1mag+=F1[dim]/spacing[dim]*F1[dim]/spacing[dim]; 
		       f2mag+=F2[dim]/spacing[dim]*F2[dim]/spacing[dim];
		       umag+=updateField->GetPixel(index)[dim]/spacing[dim]*updateField->GetPixel(index)[dim]/spacing[dim]; 
		     }
		   f1mag=sqrt(f1mag); f2mag=sqrt(f2mag); umag=sqrt(umag);
		   if ( f1mag > 0.05 ) updateField->SetPixel(index,F1);
		   if ( f2mag > 0.05 ) updateFieldInv->SetPixel(index,F2);
		   tmag+=umag;
		 }
	       //	       std::cout << " total mag " << tmag << std::endl; 
	     }
	   //smooth the total field
	   this->SmoothDeformationField(updateField,true);
	   if (updateFieldInv) this->SmoothDeformationField(updateFieldInv,true);
	 }

       */
 //normalize update field then add to total field 
       typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
        Iterator dIter(totalUpdateField,totalUpdateField->GetLargestPossibleRegion() );
        float mag=0.0;
        float max=0.0;
        unsigned long ct=0;
        float total=0;
        for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
        { 
            typename ImageType::IndexType index=dIter.GetIndex();
            VectorType vec=updateField->GetPixel(index);
            mag=0;
            for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vec[jj]/spacing[jj]*vec[jj]/spacing[jj];
            mag=sqrt(mag);
//            if (mag > 0. ) std::cout << " mag " << mag << " max " << max << " vec " << vec << std::endl;
            if (mag > max) max=mag;
            ct++;
            total+=mag;
	    //    std::cout << " mag " << mag << std::endl;
        }
       if (this->m_Debug) std::cout << "PRE MAX " << max << std::endl;
       float max2=0;
       if (max <= 0) max=1;
       for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
        { 
            typename ImageType::IndexType index=dIter.GetIndex();
            VectorType vec=updateField->GetPixel(index);
            vec=vec/max;
            mag=0;
            for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vec[jj]/spacing[jj]*vec[jj]/spacing[jj];
            mag=sqrt(mag);
            if (mag >  max2 ) max2=mag;
//            if (mag > 0.95) std::cout << " mag " << mag << " max " << max << " vec " << vec << " ind " << index << std::endl;
            /** FIXME need weights between metrics */
            
            RealType normalizedWeight 
              = this->m_SimilarityMetrics[metricCount]->GetWeightScalar() / sumWeights;
//            RealType weight = this->m_SimilarityMetrics[metricCount]->GetWeightImage()->GetPixel( diter.GetIndex() );
	    if (ispointsetmetric ) 
	      {
		VectorType intensityupdate=dIter.Get();
		VectorType lmupdate=vec;
		float lmag=0;
		for (unsigned int li=0; li<ImageDimension; li++) lmag+=(lmupdate[li]/spacing[li])*(lmupdate[li]/spacing[li]);
		lmag=sqrt(lmag);
		float modi=1;
		if (lmag > 1) modi=0;
		else modi=1.0-lmag;
		float iwt=1*modi;
		float lmwt=normalizedWeight;
		VectorType totalv=intensityupdate*iwt+lmupdate*lmwt;
		dIter.Set(totalv);
	      }
            else dIter.Set(dIter.Get()+vec*normalizedWeight);
        }
 
       if (totalUpdateInvField){
        Iterator dIter(totalUpdateInvField,totalUpdateInvField->GetLargestPossibleRegion() );
        float mag=0.0;
        float max=0.0;
        unsigned long ct=0;
        float total=0;
        for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
        { 
            typename ImageType::IndexType index=dIter.GetIndex();
            VectorType vec=updateFieldInv->GetPixel(index);
            mag=0;
            for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vec[jj]/spacing[jj]*vec[jj]/spacing[jj];
            mag=sqrt(mag);
//            if (mag > 0. ) std::cout << " mag " << mag << " max " << max << " vec " << vec << std::endl;
            if (mag > max) max=mag;
            ct++;
            total+=mag;
	    //    std::cout << " mag " << mag << std::endl;
        }
       if (this->m_Debug) std::cout << "PRE MAX " << max << std::endl;
       float max2=0;
       if (max <= 0) max=1;
       for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
        { 
            typename ImageType::IndexType index=dIter.GetIndex();
            VectorType vec=updateFieldInv->GetPixel(index);
            vec=vec/max;
            mag=0;
            for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vec[jj]/spacing[jj]*vec[jj]/spacing[jj];
            mag=sqrt(mag);
            if (mag >  max2 ) max2=mag;
//            if (mag > 0.95) std::cout << " mag " << mag << " max " << max << " vec " << vec << " ind " << index << std::endl;
            /** FIXME need weights between metrics */
            
            RealType normalizedWeight 
              = this->m_SimilarityMetrics[metricCount]->GetWeightScalar() / sumWeights;
//            RealType weight = this->m_SimilarityMetrics[metricCount]->GetWeightImage()->GetPixel( diter.GetIndex() );
            
            if (ispointsetmetric ) 
	      {
		VectorType intensityupdate=dIter.Get();
		VectorType lmupdate=vec;
		float lmag=0;
		for (unsigned int li=0; li<ImageDimension; li++) lmag+=(lmupdate[li]/spacing[li])*(lmupdate[li]/spacing[li]);
		lmag=sqrt(lmag);
		float modi=1;
		if (lmag > 1) modi=0;
		else modi=1.0-lmag;
		float iwt=1*modi;
		float lmwt=normalizedWeight;
		VectorType totalv=intensityupdate*iwt+lmupdate*lmwt;
		dIter.Set(totalv);
	      }
            else dIter.Set(dIter.Get()+vec*normalizedWeight);
        }
        }
       if (this->m_Debug) std::cout << "PO MAX " << max2 << " sz" << totalUpdateField->GetLargestPossibleRegion().GetSize() << std::endl;

    }	

//    this->SmoothDeformationField( totalUpdateField,true);
//    if (totalUpdateInvField) this->SmoothDeformationField( totalUpdateInvField,true);


    return totalUpdateField;
}



template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::DeformationFieldPointer 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::ComputeUpdateFieldAlternatingMin(DeformationFieldPointer fixedwarp, DeformationFieldPointer movingwarp ,   PointSetPointer fpoints, PointSetPointer wpoints, DeformationFieldPointer totalUpdateInvField, bool updateenergy)
{
  
  ImagePointer mask=NULL;
  if ( movingwarp && this->m_MaskImage)
    mask= this->WarpMultiTransform( this->m_MaskImage, this->m_MaskImage, NULL, movingwarp, false , this->m_FixedImageAffineTransform );
  else if (this->m_MaskImage) mask=this->SubsampleImage( this->m_MaskImage, this->m_ScaleFactor , this->m_MaskImage->GetOrigin() , this->m_MaskImage->GetDirection() ,  NULL);
  
  if ( !fixedwarp) {std::cout<< " NO F WARP " << std::endl;  fixedwarp=this->m_DeformationField; }
  //if ( !movingwarp) std::cout<< " NO M WARP " << std::endl;

    ///     std::cout << " get upd field " << std::endl;
    typename ImageType::SpacingType spacing=fixedwarp->GetSpacing(); 
    VectorType zero;
    zero.Fill(0);
    DeformationFieldPointer updateField=NULL,totalUpdateField=NULL,updateFieldInv=NULL;
    totalUpdateField=DeformationFieldType::New();
    totalUpdateField->SetSpacing( fixedwarp->GetSpacing() );
    totalUpdateField->SetOrigin( fixedwarp->GetOrigin() );
    totalUpdateField->SetDirection( fixedwarp->GetDirection() );
    totalUpdateField->SetLargestPossibleRegion(fixedwarp->GetLargestPossibleRegion()  );
    totalUpdateField->SetRequestedRegion( fixedwarp->GetLargestPossibleRegion()   );
    totalUpdateField->SetBufferedRegion( fixedwarp->GetLargestPossibleRegion()  );
    totalUpdateField->Allocate();
    totalUpdateField->FillBuffer(zero);
    //bool hadpointsetmetric=false;

    RealType sumWeights = 0.0;
    for( unsigned int n = 0; n < this->m_SimilarityMetrics.size(); n++ ) 
      { 
      sumWeights += this->m_SimilarityMetrics[n]->GetWeightScalar();
      }
    sumWeights=1;
  
    // for ( unsigned int metricCount = 0; metricCount < this->m_SimilarityMetrics.size(); metricCount++ ) 
    //{
    //MetricBaseTypePointer df = this->m_SimilarityMetrics[metricCount]->GetMetric();
    //  if (df->ThisIsAPointSetMetric()) hadpointsetmetric=true; 
    //}
    
    //for ( unsigned int metricCount = 0; metricCount < this->m_SimilarityMetrics.size(); metricCount++ ) 
    unsigned int metricCount= this->m_CurrentIteration %  this->m_SimilarityMetrics.size();
    { 
         bool ispointsetmetric=false;

        /** build an update field */
	 if ( true )// this->m_SimilarityMetrics.size() == 1 ) 
        {
          updateField=totalUpdateField;
          if (totalUpdateInvField) updateFieldInv=totalUpdateInvField;
        }
        else {
          updateField=DeformationFieldType::New();
          updateField->SetSpacing( fixedwarp->GetSpacing() );
          updateField->SetOrigin( fixedwarp->GetOrigin() );
          updateField->SetDirection( fixedwarp->GetDirection() );
          updateField->SetLargestPossibleRegion(fixedwarp->GetLargestPossibleRegion()  );
          updateField->SetRequestedRegion( fixedwarp->GetLargestPossibleRegion()   );
          updateField->SetBufferedRegion( fixedwarp->GetLargestPossibleRegion()  );
          updateField->Allocate();
          updateField->FillBuffer(zero);
          if (totalUpdateInvField){
            updateFieldInv=DeformationFieldType::New();
            updateFieldInv->SetSpacing( fixedwarp->GetSpacing() );
            updateFieldInv->SetOrigin( fixedwarp->GetOrigin() );
            updateFieldInv->SetDirection( fixedwarp->GetDirection() );
            updateFieldInv->SetLargestPossibleRegion(fixedwarp->GetLargestPossibleRegion()  );
            updateFieldInv->SetRequestedRegion( fixedwarp->GetLargestPossibleRegion()   );
            updateFieldInv->SetBufferedRegion( fixedwarp->GetLargestPossibleRegion()  );
            updateFieldInv->Allocate();
            updateFieldInv->FillBuffer(zero);
           }
         }

        /** get the update */
        typedef DeformationFieldType DeformationFieldType;
        typedef typename FiniteDifferenceFunctionType::NeighborhoodType
        NeighborhoodIteratorType;
        typedef ImageRegionIterator<DeformationFieldType> UpdateIteratorType;
 
//        TimeStepType timeStep;
        void *globalData;
//	std::cout << " B " << std::endl;

// for each metric, warp the assoc. Images 
/** We loop Over This To Do MultiVariate */
   /** FIXME really should pass an image list and then warp each one in
         turn  then expand the update field to fit size of total
         deformation */
        ImagePointer wmimage=NULL;
        if ( fixedwarp)
        wmimage= this->WarpMultiTransform(  this->m_SmoothFixedImages[metricCount],this->m_SmoothMovingImages[metricCount], this->m_AffineTransform, fixedwarp, false , this->m_FixedImageAffineTransform );
        else wmimage=this->SubsampleImage( this->m_SmoothMovingImages[metricCount] , this->m_ScaleFactor , this->m_SmoothMovingImages[metricCount]->GetOrigin() , this->m_SmoothMovingImages[metricCount]->GetDirection() ,  NULL);
   
//	std::cout << " C " << std::endl;
        ImagePointer wfimage=NULL;
        if ( movingwarp)
        wfimage= this->WarpMultiTransform( this->m_SmoothFixedImages[metricCount], this->m_SmoothFixedImages[metricCount], NULL, movingwarp, false , this->m_FixedImageAffineTransform );
        else wfimage=this->SubsampleImage( this->m_SmoothFixedImages[metricCount] , this->m_ScaleFactor , this->m_SmoothFixedImages[metricCount]->GetOrigin() , this->m_SmoothFixedImages[metricCount]->GetDirection() ,  NULL);
   

//	std::cout << " D " << std::endl;

/** MV Loop END -- Would have to collect update fields then add them
* together somehow -- Would also have to eliminate the similarity
* metric loop within ComputeUpdateField */


        // Get the FiniteDifferenceFunction to use in calculations.
        MetricBaseTypePointer df = this->m_SimilarityMetrics[metricCount]->GetMetric();
        df->SetFixedImage(wfimage);
        df->SetMovingImage(wmimage);
        if (df->ThisIsAPointSetMetric()) ispointsetmetric=true; 
        if (fpoints && ispointsetmetric )  df->SetFixedPointSet(fpoints); else if (ispointsetmetric ) std::cout << "NO POINTS!! " << std::endl;
        if (wpoints && ispointsetmetric ) df->SetMovingPointSet(wpoints); else if (ispointsetmetric ) std::cout << "NO POINTS!! " << std::endl;
        typename ImageType::SizeType  radius = df->GetRadius();
        df->InitializeIteration();
        typename DeformationFieldType::Pointer output = updateField;
        typedef NeighborhoodAlgorithm::ImageBoundaryFacesCalculator<DeformationFieldType>
        FaceCalculatorType;
        typedef typename FaceCalculatorType::FaceListType FaceListType;
        FaceCalculatorType faceCalculator;
        FaceListType faceList = faceCalculator(updateField, updateField->GetLargestPossibleRegion(), radius);
        typename FaceListType::iterator fIt = faceList.begin();
        globalData = df->GetGlobalDataPointer();

        // Process the non-boundary region.
        NeighborhoodIteratorType nD(radius, updateField, *fIt);
        UpdateIteratorType       nU(updateField,  *fIt);
        nD.GoToBegin();
	nU.GoToBegin();
        while( !nD.IsAtEnd() )
        {
            bool oktosample=true;	       
            float maskprob=1.0;
            if (mask)
             {
                maskprob=mask->GetPixel( nD.GetIndex() );
                if (maskprob > 1.0) maskprob=1.0;
                if ( maskprob < 0.1) oktosample=false;
             }
            if ( oktosample ) 
            {
                nU.Value() += df->ComputeUpdate(nD, globalData)*maskprob;
                if (totalUpdateInvField)
                 { typename ImageType::IndexType index=nD.GetIndex();
                     VectorType temp = df->ComputeUpdateInv(nD, globalData)*maskprob;
                     updateFieldInv->SetPixel(index,temp);
                 } //else nU.Value() -= df->ComputeUpdateInv(nD, globalData)*maskprob;
                ++nD;
                ++nU;
            }
            else
            {
                ++nD;
                ++nU;
            }
        }
       if (updateenergy){
         this->m_LastEnergy[metricCount]=this->m_Energy[metricCount];
         this->m_Energy[metricCount]=df->GetEnergy();//*this->m_SimilarityMetrics[metricCount]->GetWeightScalar()/sumWeights; 
        }
       
       // smooth the fields 
       //       if (!ispointsetmetric || ImageDimension == 2 ){
            this->SmoothDeformationField(updateField,true);
            if (updateFieldInv) this->SmoothDeformationField(updateFieldInv,true);
	    //  }
       /*
       else // use another strategy -- exact lm? / something like Laplacian 
	 {
	   float tmag=0;
	   for (unsigned int ff=0; ff<5; ff++)
	     {
	       tmag=0;
	       this->SmoothDeformationField(updateField,true);
	       if (updateFieldInv) this->SmoothDeformationField(updateFieldInv,true);
	       nD.GoToBegin();
	       nU.GoToBegin();
	       while( !nD.IsAtEnd() )
		 {
		   typename ImageType::IndexType index=nD.GetIndex();
		   bool oktosample=true;	       
		   float maskprob=1.0;
		   if (mask)
		     {
		       maskprob=mask->GetPixel( nD.GetIndex() );
		       if (maskprob > 1.0) maskprob=1.0;
		       if ( maskprob < 0.1) oktosample=false;
		     }
		   VectorType F1;
		   F1.Fill(0);
		   VectorType F2;
		   F2.Fill(0);
		   if ( oktosample ) 
		     {
		       F1 = df->ComputeUpdate(nD, globalData)*maskprob;
		       if (totalUpdateInvField)
			 { 
			   F2 = df->ComputeUpdateInv(nD, globalData)*maskprob;
			 } 
		       ++nD;
		       ++nU;
		     }
		   else
		     {
		       ++nD;
		       ++nU;
		     }

		   // compute mags of F1 and F2 -- if large enough, reset them
		   float f1mag=0,f2mag=0,umag=0;
		   for (unsigned int dim=0; dim<ImageDimension; dim++)
		     {
		       f1mag+=F1[dim]/spacing[dim]*F1[dim]/spacing[dim]; 
		       f2mag+=F2[dim]/spacing[dim]*F2[dim]/spacing[dim];
		       umag+=updateField->GetPixel(index)[dim]/spacing[dim]*updateField->GetPixel(index)[dim]/spacing[dim]; 
		     }
		   f1mag=sqrt(f1mag); f2mag=sqrt(f2mag); umag=sqrt(umag);
		   if ( f1mag > 0.05 ) updateField->SetPixel(index,F1);
		   if ( f2mag > 0.05 ) updateFieldInv->SetPixel(index,F2);
		   tmag+=umag;
		 }
	       //	       std::cout << " total mag " << tmag << std::endl; 
	     }
	   //smooth the total field
	   this->SmoothDeformationField(updateField,true);
	   if (updateFieldInv) this->SmoothDeformationField(updateFieldInv,true);
	 }

       */
 //normalize update field then add to total field 
       typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
        Iterator dIter(totalUpdateField,totalUpdateField->GetLargestPossibleRegion() );
        float mag=0.0;
        float max=0.0;
        unsigned long ct=0;
        float total=0;
        for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
        { 
            typename ImageType::IndexType index=dIter.GetIndex();
            VectorType vec=updateField->GetPixel(index);
            mag=0;
            for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vec[jj]/spacing[jj]*vec[jj]/spacing[jj];
            mag=sqrt(mag);
//            if (mag > 0. ) std::cout << " mag " << mag << " max " << max << " vec " << vec << std::endl;
            if (mag > max) max=mag;
            ct++;
            total+=mag;
	    //    std::cout << " mag " << mag << std::endl;
        }
       if (this->m_Debug) std::cout << "PRE MAX " << max << std::endl;
       float max2=0;
       if (max <= 0) max=1;
       for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
        { 
            typename ImageType::IndexType index=dIter.GetIndex();
            VectorType vec=updateField->GetPixel(index);
            vec=vec/max;
            mag=0;
            for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vec[jj]/spacing[jj]*vec[jj]/spacing[jj];
            mag=sqrt(mag);
            if (mag >  max2 ) max2=mag;
//            if (mag > 0.95) std::cout << " mag " << mag << " max " << max << " vec " << vec << " ind " << index << std::endl;
            /** FIXME need weights between metrics */
            
            RealType normalizedWeight 
              = this->m_SimilarityMetrics[metricCount]->GetWeightScalar() / sumWeights;
	    /*            RealType weight = this->m_SimilarityMetrics[metricCount]->GetWeightImage()->GetPixel( diter.GetIndex() );
	    if (ispointsetmetric ) 
	      {
		VectorType intensityupdate=dIter.Get();
		VectorType lmupdate=vec;
		float lmag=0;
		for (unsigned int li=0; li<ImageDimension; li++) lmag+=(lmupdate[li]/spacing[li])*(lmupdate[li]/spacing[li]);
		lmag=sqrt(lmag);
		float modi=1;
		if (lmag > 1) modi=0;
		else modi=1.0-lmag;
		float iwt=1*modi;
		float lmwt=normalizedWeight;
		VectorType totalv=intensityupdate*iwt+lmupdate*lmwt;
		dIter.Set(totalv);
	      }
	      else */
	    dIter.Set(dIter.Get()+vec*normalizedWeight);
        }
 
       if (totalUpdateInvField){
        Iterator dIter(totalUpdateInvField,totalUpdateInvField->GetLargestPossibleRegion() );
        float mag=0.0;
        float max=0.0;
        unsigned long ct=0;
        float total=0;
        for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
        { 
            typename ImageType::IndexType index=dIter.GetIndex();
            VectorType vec=updateFieldInv->GetPixel(index);
            mag=0;
            for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vec[jj]/spacing[jj]*vec[jj]/spacing[jj];
            mag=sqrt(mag);
//            if (mag > 0. ) std::cout << " mag " << mag << " max " << max << " vec " << vec << std::endl;
            if (mag > max) max=mag;
            ct++;
            total+=mag;
	    //    std::cout << " mag " << mag << std::endl;
        }
       if (this->m_Debug) std::cout << "PRE MAX " << max << std::endl;
       float max2=0;
       if (max <= 0) max=1;
       for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
        { 
            typename ImageType::IndexType index=dIter.GetIndex();
            VectorType vec=updateFieldInv->GetPixel(index);
            vec=vec/max;
            mag=0;
            for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vec[jj]/spacing[jj]*vec[jj]/spacing[jj];
            mag=sqrt(mag);
            if (mag >  max2 ) max2=mag;
//            if (mag > 0.95) std::cout << " mag " << mag << " max " << max << " vec " << vec << " ind " << index << std::endl;
            /** FIXME need weights between metrics */
            
            RealType normalizedWeight 
              = this->m_SimilarityMetrics[metricCount]->GetWeightScalar() / sumWeights;
//            RealType weight = this->m_SimilarityMetrics[metricCount]->GetWeightImage()->GetPixel( diter.GetIndex() );
            /*
            if (ispointsetmetric ) 
	      {
		VectorType intensityupdate=dIter.Get();
		VectorType lmupdate=vec;
		float lmag=0;
		for (unsigned int li=0; li<ImageDimension; li++) lmag+=(lmupdate[li]/spacing[li])*(lmupdate[li]/spacing[li]);
		lmag=sqrt(lmag);
		float modi=1;
		if (lmag > 1) modi=0;
		else modi=1.0-lmag;
		float iwt=1*modi;
		float lmwt=normalizedWeight;
		VectorType totalv=intensityupdate*iwt+lmupdate*lmwt;
		dIter.Set(totalv);
	      }
	      else */
	    dIter.Set(dIter.Get()+vec*normalizedWeight);
        }
       }
       if (this->m_Debug) std::cout << "PO MAX " << max2 << " sz" << totalUpdateField->GetLargestPossibleRegion().GetSize() << std::endl;

    }

//    this->SmoothDeformationField( totalUpdateField,true);
//    if (totalUpdateInvField) this->SmoothDeformationField( totalUpdateInvField,true);


    return totalUpdateField;
}




template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::DiffeomorphicExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints, PointSetPointer mpoints)
{

  //  this function computes a velocity field that --- when composed with itself --- optimizes the registration solution.  
  // it's very different than the Exp approach used by DiffeomorphicDemons which just composes small deformation over time. 
  //  DiffDem cannot reconstruct the path between images without recomputing the registration.
  // DiffDem also cannot create an inverse mapping. 
    /** FIXME really should pass an image list and then warp each one in
	  turn  then expand the update field to fit size of total
	  deformation */
    typename ImageType::SpacingType spacing=fixedImage->GetSpacing(); 
    VectorType zero;  
    zero.Fill(0);
    DeformationFieldPointer totalUpdateField=NULL;
    DeformationFieldPointer totalField=this->m_DeformationField;
    /** generate phi and phi gradient */
    DeformationFieldPointer diffmap=DeformationFieldType::New();
    diffmap->SetSpacing( totalField->GetSpacing() );
    diffmap->SetOrigin( totalField->GetOrigin() );
    diffmap->SetDirection( totalField->GetDirection() );
    diffmap->SetLargestPossibleRegion(totalField->GetLargestPossibleRegion()  );
    diffmap->SetRequestedRegion( totalField->GetLargestPossibleRegion()   );
    diffmap->SetBufferedRegion( totalField->GetLargestPossibleRegion()  );
    diffmap->Allocate();
    DeformationFieldPointer invdiffmap=DeformationFieldType::New();
    invdiffmap->SetSpacing( totalField->GetSpacing() );
    invdiffmap->SetOrigin( totalField->GetOrigin() );
    invdiffmap->SetDirection( totalField->GetDirection() );
    invdiffmap->SetLargestPossibleRegion(totalField->GetLargestPossibleRegion()  );
    invdiffmap->SetRequestedRegion( totalField->GetLargestPossibleRegion()   );
    invdiffmap->SetBufferedRegion( totalField->GetLargestPossibleRegion()  );
    invdiffmap->Allocate();

    //    float timestep=1.0/(float)this->m_NTimeSteps;
    //    for (unsigned int nts=0; nts<=this->m_NTimeSteps; nts+=this->m_NTimeSteps)
   unsigned int nts=(unsigned int)this->m_NTimeSteps;
    {

        diffmap->FillBuffer(zero);
        invdiffmap->FillBuffer(zero);	
        DeformationFieldPointer diffmap = this->IntegrateConstantVelocity(totalField, nts, 1);
	//DeformationFieldPointer invdiffmap = this->IntegrateConstantVelocity(totalField,(unsigned int)( this->m_NTimeSteps)-nts, (-1.));

        ImagePointer wfimage,wmimage;
        PointSetPointer wfpoints=NULL,wmpoints=NULL;
        AffineTransformPointer aff =this->m_AffineTransform;
        if ( mpoints ) 
             {// need full inverse map
                DeformationFieldPointer tinvdiffmap = this->IntegrateConstantVelocity(totalField, nts, (-1.));
                wmpoints = this->WarpMultiTransform(fixedImage,movingImage,  mpoints ,  aff , tinvdiffmap , true ,   this->m_FixedImageAffineTransform );
        } 
 
        DeformationFieldPointer updateField=this->ComputeUpdateField( diffmap, NULL, fpoints, wmpoints);
	//	updateField = this->IntegrateConstantVelocity( updateField, nts, timestep);
    float maxl= this->MeasureDeformation(updateField);
    if (maxl <= 0) maxl=1;
    typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
    Iterator dIter(updateField,updateField->GetLargestPossibleRegion() );
    for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )  dIter.Set( dIter.Get()*this->m_GradstepAltered/maxl);
    this->ComposeDiffs(updateField,totalField,totalField,1);
    /*	float maxl= this->MeasureDeformation(updateField);
	if (maxl <= 0) maxl=1;
	typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
	Iterator dIter(updateField,updateField->GetLargestPossibleRegion() );
	for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter ) {
	  dIter.Set( dIter.Get()*this->m_GradstepAltered/this->m_NTimeSteps );
	  totalField->SetPixel(dIter.GetIndex(), dIter.Get() +  totalField->GetPixel(dIter.GetIndex()) ); 
    	} */
    }
    this->SmoothDeformationField(totalField,false);

    return;

}

template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::GreedyExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints, PointSetPointer mpoints)
{

  //  similar approach to christensen 96 and diffeomorphic demons 
    typename ImageType::SpacingType spacing=fixedImage->GetSpacing(); 
    VectorType zero;  
    zero.Fill(0);
    DeformationFieldPointer totalUpdateField=NULL;

    // we compose the update with this field.  
    DeformationFieldPointer totalField=this->m_DeformationField;

    float timestep=1.0/(float)this->m_NTimeSteps;
    unsigned int nts=(unsigned int)this->m_NTimeSteps;
    
    ImagePointer wfimage,wmimage;
    PointSetPointer wfpoints=NULL,wmpoints=NULL;
    AffineTransformPointer aff =this->m_AffineTransform;
    DeformationFieldPointer updateField=this->ComputeUpdateField( totalField, NULL, fpoints, wmpoints);
    updateField = this->IntegrateConstantVelocity( updateField, nts, timestep);
    float maxl= this->MeasureDeformation(updateField);
    if (maxl <= 0) maxl=1;
    typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
    Iterator dIter(updateField,updateField->GetLargestPossibleRegion() );
    for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )  dIter.Set( dIter.Get()*this->m_GradstepAltered/maxl );
    this->ComposeDiffs(updateField,totalField,totalField,1);
    //    maxl= this->MeasureDeformation(totalField);
    //    std::cout << " maxl " << maxl << " gsa " << this->m_GradstepAltered   << std::endl;
    //	totalField=this->CopyDeformationField(totalUpdateField);
    this->SmoothDeformationField(totalField,false);

    return;

}


//added by songgang
template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::AffineTransformPointer
ANTSImageRegistrationOptimizer<TDimension, TReal>::AffineOptimization(OptAffineType &affine_opt) {
    //    typedef itk::Image<float, 3> TempImageType;
    //    typename TempImageType::Pointer fixedImage = TempImageType::New();
    //    typename TempImageType::Pointer movingImage = TempImageType::New();

    ImagePointer fixedImage;
    ImagePointer movingImage;
    /** FIXME -- here we assume the metrics all have the same image */
    fixedImage = this->m_SimilarityMetrics[0]->GetFixedImage();
    movingImage = this->m_SimilarityMetrics[0]->GetMovingImage();

    //TODO: get mask image pointer / type for mask image
    if (this->m_MaskImage) affine_opt.mask_fixed = this->m_MaskImage;
    
    
    // AffineTransformPointer &transform_init = affine_opt.transform_initial;
    // ImagePointer &maskImage = affine_opt.mask_fixed;

    AffineTransformPointer transform = AffineTransformType::New();
    
    
    // std::cout << "In AffineOptimization: transform_init.IsNotNull()=" << transform_init.IsNotNull() << std::endl; 
    // compute_single_affine_transform(fixedImage, movingImage, maskImage, transform, transform_init);
    
    // OptAffine<AffineTransformPointer, ImagePointer> opt;
    ComputeSingleAffineTransform(fixedImage, movingImage, affine_opt, transform);
    
    return transform;
}





template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::SyNRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints, PointSetPointer mpoints)
{

  typename ImageType::SpacingType spacing=fixedImage->GetSpacing(); 
  VectorType zero;  
  zero.Fill(0);
  DeformationFieldPointer       totalUpdateField,totalUpdateInvField=DeformationFieldType::New();
  totalUpdateInvField->SetSpacing( this->m_DeformationField->GetSpacing() );
  totalUpdateInvField->SetOrigin( this->m_DeformationField->GetOrigin() );
  totalUpdateInvField->SetDirection( this->m_DeformationField->GetDirection() );
  totalUpdateInvField->SetLargestPossibleRegion(this->m_DeformationField->GetLargestPossibleRegion()  );
  totalUpdateInvField->SetRequestedRegion( this->m_DeformationField->GetLargestPossibleRegion()   );
  totalUpdateInvField->SetBufferedRegion( this->m_DeformationField->GetLargestPossibleRegion()  );
  totalUpdateInvField->Allocate();
  totalUpdateInvField->FillBuffer(zero);
  if (!this->m_SyNF)
    {
    std::cout <<" Allocating " << std::endl;
    this->m_SyNF=this->CopyDeformationField(totalUpdateInvField);
    this->m_SyNFInv=this->CopyDeformationField(this->m_SyNF);
    this->m_SyNM=this->CopyDeformationField(totalUpdateInvField);
    this->m_SyNMInv=this->CopyDeformationField(this->m_SyNF);
    //this->m_Debug=true;
        if (this->m_Debug)     std::cout << " SyNFInv" << this->m_SyNFInv->GetLargestPossibleRegion().GetSize() << std::endl;
        if (this->m_Debug)     std::cout << " t updIf " << totalUpdateInvField->GetLargestPossibleRegion().GetSize() << std::endl;
        if (this->m_Debug)     std::cout << " synf " << this->m_SyNF->GetLargestPossibleRegion().GetSize() << std::endl;
	//this->m_Debug=false;
    std::cout <<" Allocating Done " << std::endl;
    }


  if (!this->m_SyNF) { std::cout<<" F'D UP " << std::endl;}
  
    PointSetPointer wfpoints=NULL,wmpoints=NULL;
    AffineTransformPointer aff =this->m_AffineTransform;   
    AffineTransformPointer affinverse=NULL; 
    if (aff){
    affinverse=AffineTransformType::New();
    aff->GetInverse(affinverse);
    }  
         
    if ( mpoints ) 
      {
	wmpoints = this->WarpMultiTransform(fixedImage,movingImage,  mpoints ,  aff , this->m_SyNM , true ,  this->m_FixedImageAffineTransform );
      }

    if ( fpoints ) 
      {// need full inverse map
      wfpoints = this->WarpMultiTransform(fixedImage,fixedImage, fpoints ,  NULL , this->m_SyNF , false  ,  this->m_FixedImageAffineTransform  );
      }
    //syncom
    totalUpdateField=this->ComputeUpdateField(this->m_SyNMInv, this->m_SyNFInv, wfpoints, wmpoints,totalUpdateInvField);
	
      this->ComposeDiffs(this->m_SyNF,totalUpdateField,this->m_SyNF,this->m_GradstepAltered);
      this->ComposeDiffs(this->m_SyNM,totalUpdateInvField,this->m_SyNM,this->m_GradstepAltered);
      
      if ( this->m_TotalSmoothingparam > 0 || this->m_TotalSmoothingMeshSize[0] > 0 )
	{
	this->SmoothDeformationField( this->m_SyNF,false);
	this->SmoothDeformationField( this->m_SyNM,false);
	}
     
      this->InvertField(this->m_SyNF,this->m_SyNFInv);
      this->InvertField(this->m_SyNM,this->m_SyNMInv);
      this->InvertField(this->m_SyNFInv,this->m_SyNF);
      this->InvertField(this->m_SyNMInv,this->m_SyNM); 

//      std::cout <<  " F " << this->MeasureDeformation(this->m_SyNF) << " F1 " << this->MeasureDeformation(this->m_SyNFInv) << std::endl;
//      std::cout <<  " M " << this->MeasureDeformation(this->m_SyNM) << " M1 " << this->MeasureDeformation(this->m_SyNMInv) << std::endl;
    return;

}



template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::SyNExpRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints, PointSetPointer mpoints)
{
  std::cout << " SyNEX" ;
  typename ImageType::SpacingType spacing=fixedImage->GetSpacing(); 
  VectorType zero;  
  zero.Fill(0);
  DeformationFieldPointer       totalUpdateField,totalUpdateInvField=DeformationFieldType::New();
  totalUpdateInvField->SetSpacing( this->m_DeformationField->GetSpacing() );
  totalUpdateInvField->SetOrigin( this->m_DeformationField->GetOrigin() );
  totalUpdateInvField->SetDirection( this->m_DeformationField->GetDirection() );
  totalUpdateInvField->SetLargestPossibleRegion(this->m_DeformationField->GetLargestPossibleRegion()  );
  totalUpdateInvField->SetRequestedRegion( this->m_DeformationField->GetLargestPossibleRegion()   );
  totalUpdateInvField->SetBufferedRegion( this->m_DeformationField->GetLargestPossibleRegion()  );
  totalUpdateInvField->Allocate();
  totalUpdateInvField->FillBuffer(zero);
  if (!this->m_SyNF)
    {
    std::cout <<" Allocating " << std::endl;
    this->m_SyNF=this->CopyDeformationField(totalUpdateInvField);
    this->m_SyNFInv=this->CopyDeformationField(this->m_SyNF);
    this->m_SyNM=this->CopyDeformationField(totalUpdateInvField);
    this->m_SyNMInv=this->CopyDeformationField(this->m_SyNF);
    std::cout <<" Allocating Done " << std::endl;
    }

  if (!this->m_SyNF) { std::cout<<" F'D UP " << std::endl;}
  
    ImagePointer wfimage,wmimage;
    PointSetPointer wfpoints=NULL,wmpoints=NULL;
    AffineTransformPointer aff =this->m_AffineTransform;   
    AffineTransformPointer affinverse=NULL;

//here, SyNF holds the moving velocity field, SyNM holds the fixed
//velocity field and we integrate both to generate the inv/fwd fields

    float timestep=1.0/(float)this->m_NTimeSteps;
    unsigned int nts=this->m_NTimeSteps;
    DeformationFieldPointer fdiffmap = this->IntegrateConstantVelocity(this->m_SyNF, nts, 1);
    this->m_SyNFInv = this->IntegrateConstantVelocity(this->m_SyNF, nts, (-1.));
    DeformationFieldPointer mdiffmap = this->IntegrateConstantVelocity(this->m_SyNM, nts, 1);
    this->m_SyNMInv = this->IntegrateConstantVelocity(this->m_SyNM, nts, (-1.));


    if (aff){
    affinverse=AffineTransformType::New();
    aff->GetInverse(affinverse);
    }
    if ( mpoints ) 
      {
	wmpoints = this->WarpMultiTransform(fixedImage,movingImage,  mpoints ,  aff , this->m_SyNM , true  ,  this->m_FixedImageAffineTransform );
      }
    if ( fpoints ) 
      {// need full inverse map
      wfpoints = this->WarpMultiTransform(fixedImage,fixedImage, fpoints ,  NULL , this->m_SyNF , false  ,  this->m_FixedImageAffineTransform );
      }

    totalUpdateField=this->ComputeUpdateField( this->m_SyNMInv , this->m_SyNFInv , wfpoints, wmpoints,totalUpdateInvField);
//then addd
    typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
    Iterator dIter(this->m_SyNF,this->m_SyNF->GetLargestPossibleRegion() );
    float max=0,max2=0;
    for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
    { 
    typename ImageType::IndexType index=dIter.GetIndex();
    VectorType vecf=totalUpdateField->GetPixel(index);
    VectorType vecm=totalUpdateInvField->GetPixel(index);
    dIter.Set(dIter.Get()+vecf*this->m_GradstepAltered);
    this->m_SyNM->SetPixel( index, this->m_SyNM->GetPixel( index )+vecm*this->m_GradstepAltered);
// min field difference => geodesic => DV/dt=0 
    float geowt1=0.99;
    float geowt2=1.0-geowt1;
    VectorType synmv=this->m_SyNM->GetPixel( index );
    VectorType synfv   =this->m_SyNF->GetPixel( index );
    this->m_SyNM->SetPixel( index, synmv*geowt1-synfv*geowt2);
    this->m_SyNF->SetPixel( index, synfv*geowt1-synmv*geowt2);
    }

    if (this->m_TotalSmoothingparam > 0 || this->m_TotalSmoothingMeshSize[0] > 0 )
      { 
      this->SmoothDeformationField( this->m_SyNF,false);
      this->SmoothDeformationField( this->m_SyNM,false);
      }
//      std::cout <<  " TUF " << this->MeasureDeformation(this->m_SyNF) << " TUM " << this->MeasureDeformation(this->m_SyNM) << std::endl;

    return;

}

template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::UpdateTimeVaryingVelocityFieldWithSyNFandSyNM( )
{
  typedef float  PixelType;
  typedef itk::Vector<float,TDimension>         VectorType;
  typedef itk::Image<VectorType,TDimension>     DeformationFieldType;
  typedef itk::Image<PixelType,TDimension> ImageType;
  typedef typename  ImageType::IndexType IndexType;
  typedef typename  ImageType::SizeType SizeType;
  typedef typename  ImageType::SpacingType SpacingType;
  typedef TimeVaryingVelocityFieldType tvt;

  bool generatetvfield=false;
  if (!this->m_TimeVaryingVelocity) generatetvfield=true;  
  else 
    {
    for (int jj=0; jj<ImageDimension; jj++)
      if (this->m_CurrentDomainSize[jj] !=  this->m_TimeVaryingVelocity->GetLargestPossibleRegion().GetSize()[jj])   generatetvfield=true;
    }
  VectorType zero;
  zero.Fill(0);
  if (generatetvfield)
    {
    typename tvt::RegionType gregion;
    typename tvt::SizeType gsize;
    typename tvt::SpacingType gspace;
    typename tvt::PointType gorigin;
    gorigin.Fill(0);
    for (unsigned int dim=0; dim<TDimension; dim++) 
      {
      gsize[dim]=this->m_CurrentDomainSize[dim];
      gspace[dim]=this->m_CurrentDomainSpacing[dim];
      gorigin[dim]=this->m_CurrentDomainOrigin[dim];
      }
    gsize[TDimension]=2;//this->m_NTimeSteps;
    gspace[TDimension]=1;
    gregion.SetSize(gsize);

/** The TV Field has the direction of the sub-image -- the time domain
    has identity transform */
    typename tvt::DirectionType iddir;
    iddir.Fill(0);
    iddir[ImageDimension][ImageDimension]=1;
    for (unsigned int i=0; i<ImageDimension+1;i++)
      for (unsigned int j=0; j<ImageDimension+1;j++)
//	if (i == j) iddir[i][j]=1;
	if ( i < ImageDimension && j < ImageDimension)
	  iddir[i][j]=this->GetDeformationField()->GetDirection()[i][j];

    this->m_TimeVaryingVelocity=tvt::New();
    this->m_TimeVaryingVelocity->SetSpacing( gspace );
    this->m_TimeVaryingVelocity->SetOrigin( gorigin );
    this->m_TimeVaryingVelocity->SetDirection( iddir );
    this->m_TimeVaryingVelocity->SetLargestPossibleRegion(gregion);
    this->m_TimeVaryingVelocity->SetRequestedRegion( gregion);
    this->m_TimeVaryingVelocity->SetBufferedRegion( gregion  );
    this->m_TimeVaryingVelocity->Allocate();
    this->m_TimeVaryingVelocity->FillBuffer(zero);
    }

  typedef  tvt TimeVaryingVelocityFieldType;
  typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType>         FieldIterator;
  typedef itk::ImageRegionIteratorWithIndex<tvt>         TVFieldIterator;
  typedef typename DeformationFieldType::IndexType DIndexType;
  typedef typename DeformationFieldType::PointType DPointType;
  typedef typename TimeVaryingVelocityFieldType::IndexType VIndexType;
  typedef typename TimeVaryingVelocityFieldType::PointType VPointType;

  TVFieldIterator m_FieldIter( this->m_TimeVaryingVelocity,this->m_TimeVaryingVelocity->GetLargestPossibleRegion());
  for(  m_FieldIter.GoToBegin(); !m_FieldIter.IsAtEnd(); ++m_FieldIter )
    {
    typename tvt::IndexType velind=m_FieldIter.GetIndex();
    IndexType ind;
    for (unsigned int j=0; j<ImageDimension; j++) ind[j]=velind[j];
    if (velind[ImageDimension]==0) 
      {
      VectorType vel=this->m_SyNF->GetPixel(ind);
      m_FieldIter.Set(vel);
      }
    else if (velind[ImageDimension]==1) 
      {
      VectorType vel=this->m_SyNM->GetPixel(ind)*(-1.0);
      m_FieldIter.Set(vel);
      }
    }

//  std::cout <<" ALlocated TV F "<< std::endl;
}


template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::CopyOrAddToVelocityField( TimeVaryingVelocityFieldPointer velocity,  DeformationFieldPointer update1, DeformationFieldPointer update2 , float timept)
{
  typedef float  PixelType;
  typedef itk::Vector<float,TDimension>         VectorType;
  typedef itk::Image<VectorType,TDimension>     DeformationFieldType;
  typedef itk::Image<PixelType,TDimension> ImageType;
  typedef typename  ImageType::IndexType IndexType;
  typedef typename  ImageType::SizeType SizeType;
  typedef typename  ImageType::SpacingType SpacingType;
  typedef TimeVaryingVelocityFieldType tvt;

  VectorType zero;
  typedef  tvt TimeVaryingVelocityFieldType;
  typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType>         FieldIterator;
  typedef itk::ImageRegionIteratorWithIndex<tvt>         TVFieldIterator;
  typedef typename DeformationFieldType::IndexType DIndexType;
  typedef typename DeformationFieldType::PointType DPointType;
  typedef typename TimeVaryingVelocityFieldType::IndexType VIndexType;
  typedef typename TimeVaryingVelocityFieldType::PointType VPointType;
  int tpupdate=(unsigned int) (((float)this->m_NTimeSteps-1.0)*timept+0.5);
  //std::cout <<"  add to " << tpupdate << std::endl;
  float tmag=0;
  TVFieldIterator m_FieldIter(velocity, velocity->GetLargestPossibleRegion());
  for(  m_FieldIter.GoToBegin(); !m_FieldIter.IsAtEnd(); ++m_FieldIter )
    {
    typename tvt::IndexType velind=m_FieldIter.GetIndex();
    IndexType ind;
    for (unsigned int j=0; j<ImageDimension; j++) ind[j]=velind[j];
    if (velind[ImageDimension]== tpupdate && update1 ) 
      {
      VectorType vel=update1->GetPixel(ind);
      float mag=0;
      for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vel[jj]*vel[jj];
      tmag+=sqrt(mag);
      m_FieldIter.Set(vel+m_FieldIter.Get() );
      }
    if (velind[ImageDimension]== tpupdate && update2 ) 
      {
 	VectorType vel=update2->GetPixel(ind)*(-1);
        m_FieldIter.Set(vel+m_FieldIter.Get() );
      }
    }
  //  std::cout << " tmag " << tmag << std::endl;
}


template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::SyNTVRegistrationUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints, PointSetPointer mpoints)
{
  typename ImageType::SpacingType spacing=fixedImage->GetSpacing(); 
  VectorType zero;  
  zero.Fill(0);
  DeformationFieldPointer       totalUpdateField,totalUpdateInvField=DeformationFieldType::New();
  totalUpdateInvField->SetSpacing( this->m_DeformationField->GetSpacing() );
  totalUpdateInvField->SetOrigin( this->m_DeformationField->GetOrigin() );
  totalUpdateInvField->SetDirection( this->m_DeformationField->GetDirection() );
  totalUpdateInvField->SetLargestPossibleRegion(this->m_DeformationField->GetLargestPossibleRegion()  );
  totalUpdateInvField->SetRequestedRegion( this->m_DeformationField->GetLargestPossibleRegion()   );
  totalUpdateInvField->SetBufferedRegion( this->m_DeformationField->GetLargestPossibleRegion()  );
  totalUpdateInvField->Allocate();
  totalUpdateInvField->FillBuffer(zero);
  if (!this->m_SyNF)
    {
    std::cout <<" Allocating " << std::endl;
    this->m_SyNF=this->CopyDeformationField(totalUpdateInvField);
    this->m_SyNFInv=this->CopyDeformationField(this->m_SyNF);
    this->m_SyNM=this->CopyDeformationField(totalUpdateInvField);
    this->m_SyNMInv=this->CopyDeformationField(this->m_SyNF);
    std::cout <<" Allocating Done " << std::endl;
    }

  if (!this->m_SyNF) { std::cout<<" F'D UP " << std::endl;}
  
    ImagePointer wfimage,wmimage;
    PointSetPointer wfpoints=NULL,wmpoints=NULL;
    AffineTransformPointer aff =this->m_AffineTransform;   
    AffineTransformPointer affinverse=NULL;

    typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
    Iterator dIter(this->m_SyNF,this->m_SyNF->GetLargestPossibleRegion() );

//here, SyNF holds the moving velocity field, SyNM holds the fixed
//velocity field and we integrate both to generate the inv/fwd fields
  typename JacobianFunctionType::Pointer jfunction = JacobianFunctionType::New();
    float lot=0,hit=0.5;
    float lot2=1.0;
    this->UpdateTimeVaryingVelocityFieldWithSyNFandSyNM( );// sets tvt to SyNF and SyNM -- works only for 2 time points!
    this->m_SyNFInv = this->IntegrateVelocity(hit,lot);
    this->m_SyNMInv = this->IntegrateVelocity(hit,lot2);
    if (aff){
    affinverse=AffineTransformType::New();
    aff->GetInverse(affinverse);
    }
    if ( mpoints ) 
      {
/**FIXME -- NEED INTEGRATION FOR POINTS ONLY  -- warp landmarks for
* tv-field */
//      std::cout <<" aff " << std::endl;
/** NOte, totalUpdateInvField is filled with zeroes! -- we only want
      affine mapping */
      wmpoints = this->WarpMultiTransform(fixedImage,movingImage,  mpoints ,  aff , totalUpdateInvField , true, NULL );
      DeformationFieldPointer mdiffmap = this->IntegrateLandmarkSetVelocity(lot2,hit,wmpoints,movingImage);
      wmpoints = this->WarpMultiTransform(fixedImage,movingImage,  wmpoints ,  NULL , mdiffmap , true , NULL );
      }
    if ( fpoints ) 
      {// need full inverse map
      wfpoints = this->WarpMultiTransform(fixedImage,movingImage,  fpoints , NULL , totalUpdateInvField , true, this->m_FixedImageAffineTransform );
      DeformationFieldPointer fdiffmap = this->IntegrateLandmarkSetVelocity(lot,hit,wfpoints,fixedImage);
      wfpoints = this->WarpMultiTransform(fixedImage,fixedImage, wfpoints ,  NULL , fdiffmap , false , NULL );
      }
    totalUpdateField=this->ComputeUpdateField( this->m_SyNMInv, this->m_SyNFInv , wfpoints, wmpoints,totalUpdateInvField,true);

    for( dIter.GoToBegin(); !dIter.IsAtEnd(); ++dIter )
    { 
    typename ImageType::IndexType index=dIter.GetIndex();
    VectorType vecf=totalUpdateField->GetPixel(index)*1;
    VectorType vecm=totalUpdateInvField->GetPixel(index);
// update time components 1 & 2
    this->m_SyNF->SetPixel( index, this->m_SyNF->GetPixel( index )+vecf*this->m_GradstepAltered);
    this->m_SyNM->SetPixel( index, this->m_SyNM->GetPixel( index )+vecm*this->m_GradstepAltered);
// min field difference => geodesic => DV/dt=0 
    float geowt1=0.95;
    float geowt2=1.0-geowt1;
    VectorType synmv=this->m_SyNM->GetPixel( index );
    VectorType synfv   =this->m_SyNF->GetPixel( index );
    this->m_SyNM->SetPixel( index, synmv*geowt1-synfv*geowt2);
    this->m_SyNF->SetPixel( index, synfv*geowt1-synmv*geowt2);
    }

    if (  this->m_TotalSmoothingparam > 0 
      || this->m_TotalSmoothingMeshSize[0] > 0 )
      {
	//smooth time components separately 
      this->SmoothDeformationField( this->m_SyNF,false);
      this->SmoothDeformationField( this->m_SyNM,false);
      }

    return;

}


template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::DiReCTUpdate(ImagePointer fixedImage, ImagePointer movingImage, PointSetPointer fpoints, PointSetPointer mpoints)
{

  typedef TimeVaryingVelocityFieldType tvt;
  TimeVaryingVelocityFieldPointer velocityUpdate=NULL;  
  typename ImageType::SpacingType spacing=fixedImage->GetSpacing(); 
  VectorType zero;  
  zero.Fill(0);
  DeformationFieldPointer       totalUpdateField,totalUpdateInvField=DeformationFieldType::New();
  totalUpdateInvField->SetSpacing( this->m_DeformationField->GetSpacing() );
  totalUpdateInvField->SetOrigin( this->m_DeformationField->GetOrigin() );
  totalUpdateInvField->SetDirection( this->m_DeformationField->GetDirection() );
  totalUpdateInvField->SetLargestPossibleRegion(this->m_DeformationField->GetLargestPossibleRegion()  );
  totalUpdateInvField->SetRequestedRegion( this->m_DeformationField->GetLargestPossibleRegion()   );
  totalUpdateInvField->SetBufferedRegion( this->m_DeformationField->GetLargestPossibleRegion()  );
  totalUpdateInvField->Allocate();
  totalUpdateInvField->FillBuffer(zero);
  unsigned long numpx=this->m_DeformationField->GetBufferedRegion().GetNumberOfPixels();

  bool generatetvfield=false;
  bool enlargefield=false;
  if (!this->m_TimeVaryingVelocity) generatetvfield=true;  
  else 
    {
    for (int jj=0; jj<ImageDimension; jj++)
      if (this->m_CurrentDomainSize[jj] !=  this->m_TimeVaryingVelocity->GetLargestPossibleRegion().GetSize()[jj])   enlargefield=true;
    }

    velocityUpdate=tvt::New();
    typename tvt::RegionType gregion;
    typename tvt::SizeType gsize;
    typename tvt::SpacingType gspace;
    typename tvt::PointType gorigin;
    gorigin.Fill(0);
    for (unsigned int dim=0; dim<TDimension; dim++) 
      {
      gsize[dim]=this->m_CurrentDomainSize[dim];
      gspace[dim]=this->m_CurrentDomainSpacing[dim];
      gorigin[dim]=this->m_CurrentDomainOrigin[dim];
      }
    if ( this->m_NTimeSteps < 2 ) this->m_NTimeSteps=2;
    gsize[TDimension]=(unsigned long) this->m_NTimeSteps;
    float hitstep=1.0/((float)this->m_NTimeSteps-1);
    gspace[TDimension]=1;
    gregion.SetSize(gsize);
    velocityUpdate->SetSpacing( gspace );
    velocityUpdate->SetOrigin( gorigin );

/** The TV Field has the direction of the sub-image -- the time domain
    has identity transform */
    typename tvt::DirectionType iddir;
    iddir.Fill(0);
    iddir[ImageDimension][ImageDimension]=1;
    for (unsigned int i=0; i<ImageDimension+1;i++)
      for (unsigned int j=0; j<ImageDimension+1;j++)
//	if (i == j) iddir[i][j]=1;
	if ( i < ImageDimension && j < ImageDimension)
	  iddir[i][j]=this->GetDeformationField()->GetDirection()[i][j];

    velocityUpdate->SetDirection( iddir );
    velocityUpdate->SetLargestPossibleRegion(gregion);
    velocityUpdate->SetRequestedRegion( gregion);
    velocityUpdate->SetBufferedRegion( gregion  );
    velocityUpdate->Allocate();
    velocityUpdate->FillBuffer(zero);
   
 if (generatetvfield)
    {
    this->m_TimeVaryingVelocity=tvt::New();
    this->m_TimeVaryingVelocity->SetSpacing( gspace );
    this->m_TimeVaryingVelocity->SetOrigin( gorigin );
    this->m_TimeVaryingVelocity->SetDirection( iddir );
    this->m_TimeVaryingVelocity->SetLargestPossibleRegion(gregion);
    this->m_TimeVaryingVelocity->SetRequestedRegion( gregion);
    this->m_TimeVaryingVelocity->SetBufferedRegion( gregion  );
    this->m_TimeVaryingVelocity->Allocate();
    this->m_TimeVaryingVelocity->FillBuffer(zero);
    /*    this->m_LastTimeVaryingVelocity=tvt::New();
    this->m_LastTimeVaryingVelocity->SetSpacing( gspace );
    this->m_LastTimeVaryingVelocity->SetOrigin( gorigin );
    this->m_LastTimeVaryingVelocity->SetDirection( iddir );
    this->m_LastTimeVaryingVelocity->SetLargestPossibleRegion(gregion);
    this->m_LastTimeVaryingVelocity->SetRequestedRegion( gregion);
    this->m_LastTimeVaryingVelocity->SetBufferedRegion( gregion  );
    this->m_LastTimeVaryingVelocity->Allocate();
    this->m_LastTimeVaryingVelocity->FillBuffer(zero); */
    this->m_LastTimeVaryingUpdate=tvt::New();
    this->m_LastTimeVaryingUpdate->SetSpacing( gspace );
    this->m_LastTimeVaryingUpdate->SetOrigin( gorigin );
    this->m_LastTimeVaryingUpdate->SetDirection( iddir );
    this->m_LastTimeVaryingUpdate->SetLargestPossibleRegion(gregion);
    this->m_LastTimeVaryingUpdate->SetRequestedRegion( gregion);
    this->m_LastTimeVaryingUpdate->SetBufferedRegion( gregion  );
    this->m_LastTimeVaryingUpdate->Allocate();
    this->m_LastTimeVaryingUpdate->FillBuffer(zero);
    }
   else if ( enlargefield ){
        this->m_TimeVaryingVelocity=this->ExpandVelocity();
        this->m_TimeVaryingVelocity->SetSpacing(gspace);
        this->m_TimeVaryingVelocity->SetOrigin(gorigin);
	/*        this->m_LastTimeVaryingVelocity=tvt::New();
	this->m_LastTimeVaryingVelocity->SetSpacing( gspace );
	this->m_LastTimeVaryingVelocity->SetOrigin( gorigin );
	this->m_LastTimeVaryingVelocity->SetDirection( iddir );
	this->m_LastTimeVaryingVelocity->SetLargestPossibleRegion(gregion);
	this->m_LastTimeVaryingVelocity->SetRequestedRegion( gregion);
	this->m_LastTimeVaryingVelocity->SetBufferedRegion( gregion  );
	this->m_LastTimeVaryingVelocity->Allocate();
	this->m_LastTimeVaryingVelocity->FillBuffer(zero);*/
	this->m_LastTimeVaryingUpdate=tvt::New();
	this->m_LastTimeVaryingUpdate->SetSpacing( gspace );
	this->m_LastTimeVaryingUpdate->SetOrigin( gorigin );
	this->m_LastTimeVaryingUpdate->SetDirection( iddir );
	this->m_LastTimeVaryingUpdate->SetLargestPossibleRegion(gregion);
	this->m_LastTimeVaryingUpdate->SetRequestedRegion( gregion);
	this->m_LastTimeVaryingUpdate->SetBufferedRegion( gregion  );
	this->m_LastTimeVaryingUpdate->Allocate();
	this->m_LastTimeVaryingUpdate->FillBuffer(zero);
   }
  if (!this->m_SyNF)
    {
    std::cout <<" Allocating " << std::endl;
    this->m_SyNF=this->CopyDeformationField(totalUpdateInvField);
    this->m_SyNFInv=this->CopyDeformationField(this->m_SyNF);
    this->m_SyNM=this->CopyDeformationField(totalUpdateInvField);
    this->m_SyNMInv=this->CopyDeformationField(this->m_SyNF);
    std::cout <<" Allocating Done " << std::endl;
    }

  if (!this->m_SyNF) { std::cout<<" F'D UP " << std::endl;}
  
    ImagePointer wfimage,wmimage;
    PointSetPointer wfpoints=NULL,wmpoints=NULL;
    AffineTransformPointer aff =this->m_AffineTransform;   
    AffineTransformPointer affinverse=NULL;

    typedef ImageRegionIteratorWithIndex<DeformationFieldType> Iterator;
    Iterator dIter(this->m_SyNF,this->m_SyNF->GetLargestPossibleRegion() );

//here, SyNF holds the moving velocity field, SyNM holds the fixed
//velocity field and we integrate both to generate the inv/fwd fields
  typename JacobianFunctionType::Pointer jfunction = JacobianFunctionType::New();
    float lot=0, lot2=1.0;
    unsigned int fct=100;
    for (float hit=0; hit<=1; hit=hit+hitstep) {
    this->m_SyNFInv = this->IntegrateVelocity(hit,lot);
    this->m_SyNMInv = this->IntegrateVelocity(hit,lot2);

  if ( false && this->m_CurrentIteration == 1 &&  this->m_SyNFInv  ) {
   typedef itk::VectorImageFileWriter<DeformationFieldType, ImageType> 
    DeformationFieldWriterType;
    typename DeformationFieldWriterType::Pointer writer = DeformationFieldWriterType::New();
    std::ostringstream osstream;
    osstream << fct;
    fct++;
    std::string fnm = std::string("field1")+osstream.str()+std::string("warp.nii.gz");
    std::string fnm2 = std::string("field2")+osstream.str()+std::string("warp.nii.gz");
    writer->SetUseAvantsNamingConvention( true );
    writer->SetInput( this->m_SyNFInv );
    writer->SetFileName( fnm.c_str() ); 
    std::cout << " write " << fnm << std::endl;
    writer->Update();
    // writer->SetInput( this->m_SyNMInv );
      // writer->SetFileName( fnm2.c_str() ); 
      //      writer->Update();
       }


    if (aff){
    affinverse=AffineTransformType::New();
    aff->GetInverse(affinverse);
    }
    if ( mpoints ) 
      {
/**FIXME -- NEED INTEGRATION FOR POINTS ONLY  -- warp landmarks for
* tv-field */
//      std::cout <<" aff " << std::endl;
/** NOte, totalUpdateInvField is filled with zeroes! -- we only want
      affine mapping */
      wmpoints = this->WarpMultiTransform(fixedImage,movingImage,  mpoints ,  aff , totalUpdateInvField , true, NULL );
      DeformationFieldPointer mdiffmap = this->IntegrateLandmarkSetVelocity(lot2,hit,wmpoints,movingImage);
      wmpoints = this->WarpMultiTransform(fixedImage,movingImage,  wmpoints ,  NULL , mdiffmap , true , NULL );
      }
    if ( fpoints ) 
      {// need full inverse map
      wfpoints = this->WarpMultiTransform(fixedImage,movingImage,  fpoints , NULL , totalUpdateInvField , true, this->m_FixedImageAffineTransform );
      DeformationFieldPointer fdiffmap = this->IntegrateLandmarkSetVelocity(lot,hit,wfpoints,fixedImage);
      wfpoints = this->WarpMultiTransform(fixedImage,fixedImage, wfpoints ,  NULL , fdiffmap , false , NULL );
      }
    totalUpdateField=this->ComputeUpdateField( this->m_SyNMInv, this->m_SyNFInv , wfpoints, wmpoints,totalUpdateInvField,true);
    if ( this->m_SyNFullTime == 2 ) totalUpdateInvField=NULL;
      this->CopyOrAddToVelocityField( velocityUpdate, totalUpdateField ,  totalUpdateInvField,  hit );
    }
    // http://en.wikipedia.org/wiki/Conjugate_gradient_method
    // below is r_k+1
    this->SmoothVelocityGauss( velocityUpdate ,  this->m_GradSmoothingparam , ImageDimension );
    // update total velocity with v-update 
    float tmag=0;
   typedef itk::ImageRegionIteratorWithIndex<tvt>         TVFieldIterator;
   TVFieldIterator m_FieldIter( this->m_TimeVaryingVelocity,this->m_TimeVaryingVelocity->GetLargestPossibleRegion());
    for(  m_FieldIter.GoToBegin(); !m_FieldIter.IsAtEnd(); ++m_FieldIter )
      { 
	float A=1;
	float alpha=0,alpha1=0,alpha2=0,beta=0,beta1=0,beta2=0;
	VectorType vec1=velocityUpdate->GetPixel(m_FieldIter.GetIndex()); // r_k+1
	VectorType vec2=vec1;//this->m_LastTimeVaryingVelocity->GetPixel(m_FieldIter.GetIndex()); // r_k
	VectorType upd=this->m_LastTimeVaryingUpdate->GetPixel(m_FieldIter.GetIndex()); // p_k 
	for (unsigned int ii=0; ii<ImageDimension; ii++) { 
	  alpha1=vec2[ii]*vec2[ii];
	  alpha2=upd[ii]*upd[ii];
	  beta1=vec1[ii]*vec1[ii];
	  beta2=vec2[ii]*vec2[ii];
	}
	if (alpha2 > 0 ) alpha=alpha1/(A*alpha2+0.001);
	if (beta2 > 0 ) beta=beta1/(beta2+0.001);
	if (beta > 1) beta=1;
	if (alpha > 1) alpha=1;
	//		std::cout <<" beta " << beta << " alpha " << alpha << " it " << this->m_CurrentIteration << std::endl;
	VectorType newupd=(vec1);
	if ( this->m_CurrentIteration  > 2) { newupd=(vec1+upd)*0.5; }
	VectorType newsoln=m_FieldIter.Get()+ this->m_GradstepAltered*newupd;
	m_FieldIter.Set( newsoln );
	//	VectorType vec2u=vec2 - alpha*A*upd;
	//	this->m_LastTimeVaryingVelocity->SetPixel(m_FieldIter.GetIndex(), vec1 );
	this->m_LastTimeVaryingUpdate->SetPixel(m_FieldIter.GetIndex(), newupd);
        float mag=0;
	VectorType vv=m_FieldIter.Get();
        for (unsigned int jj=0; jj<ImageDimension; jj++) mag+=vv[jj]*vv[jj];
        tmag+=sqrt(mag);
      }
    tmag/=((float)this->m_NTimeSteps*(float)numpx);
    std::cout << " DiffLength " << tmag << std::endl;
    if (  this->m_TotalSmoothingparam > 0 
      || this->m_TotalSmoothingMeshSize[0] > 0 )
      {
	this->SmoothVelocityGauss( this->m_TimeVaryingVelocity ,  this->m_TotalSmoothingparam , ImageDimension );
	  //      this->SmoothDeformationField( this->m_SyNF,false);
	  //      this->SmoothDeformationField( this->m_SyNM,false);
      }

    return;

}






template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::DeformationFieldPointer 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::IntegrateVelocity(float starttimein, float finishtimein )
{
  ImagePointer mask=NULL;
  if ( this->m_SyNMInv && this->m_MaskImage)
    mask= this->WarpMultiTransform( this->m_MaskImage, this->m_MaskImage, NULL, this->m_SyNMInv, false , this->m_FixedImageAffineTransform );
  else if (this->m_MaskImage) mask=this->SubsampleImage( this->m_MaskImage, this->m_ScaleFactor , this->m_MaskImage->GetOrigin() , this->m_MaskImage->GetDirection() ,  NULL);

//  std::cout << " st " << starttimein << " ft " << finishtimein << std::endl;
  typedef float  PixelType;
  typedef itk::Vector<float,TDimension>         VectorType;
  typedef itk::Image<VectorType,TDimension>     DeformationFieldType;
  typedef itk::Image<PixelType,TDimension> ImageType;
  typedef typename  ImageType::IndexType IndexType;
  typedef typename  ImageType::SizeType SizeType;
  typedef typename  ImageType::SpacingType SpacingType;
  typedef TimeVaryingVelocityFieldType tvt;

  bool dothick=false;
  if (  finishtimein > starttimein  && this->m_ComputeThickness ) dothick=true;
  if ( dothick && this->m_CurrentIteration  > 2 ) {
    this->m_ThickImage=ImageType::New();
    this->m_ThickImage->SetSpacing( this->m_SyNF->GetSpacing() );
    this->m_ThickImage->SetOrigin( this->m_SyNF->GetOrigin() );
    this->m_ThickImage->SetDirection( this->m_SyNF->GetDirection() );
    this->m_ThickImage->SetLargestPossibleRegion(this->m_SyNF->GetLargestPossibleRegion()  );
    this->m_ThickImage->SetRequestedRegion( this->m_SyNF->GetLargestPossibleRegion()   );
    this->m_ThickImage->SetBufferedRegion( this->m_SyNF->GetLargestPossibleRegion()  );
    this->m_ThickImage->Allocate();
    this->m_ThickImage->FillBuffer(0);
    this->m_HitImage=ImageType::New();
    this->m_HitImage->SetSpacing( this->m_SyNF->GetSpacing() );
    this->m_HitImage->SetOrigin( this->m_SyNF->GetOrigin() );
    this->m_HitImage->SetDirection( this->m_SyNF->GetDirection() );
    this->m_HitImage->SetLargestPossibleRegion(this->m_SyNF->GetLargestPossibleRegion()  );
    this->m_HitImage->SetRequestedRegion( this->m_SyNF->GetLargestPossibleRegion()   );
    this->m_HitImage->SetBufferedRegion( this->m_SyNF->GetLargestPossibleRegion()  );
    this->m_HitImage->Allocate();
    this->m_HitImage->FillBuffer(0);
  }
  else { this->m_HitImage=NULL;  this->m_ThickImage=NULL; }

  DeformationFieldPointer intfield=DeformationFieldType::New();
  intfield->SetSpacing( this->m_CurrentDomainSpacing );
  intfield->SetOrigin(  this->m_DeformationField->GetOrigin() );
  intfield->SetDirection(  this->m_DeformationField->GetDirection() );
  intfield->SetLargestPossibleRegion( this->m_DeformationField->GetLargestPossibleRegion());
  intfield->SetRequestedRegion(   this->m_DeformationField->GetLargestPossibleRegion());
  intfield->SetBufferedRegion(  this->m_DeformationField->GetLargestPossibleRegion() );
  intfield->Allocate();
  VectorType zero;
  zero.Fill(0);
  intfield->FillBuffer(zero);
  if (starttimein == finishtimein) return intfield;
  if (!this->m_TimeVaryingVelocity) { std::cout << " No TV Field " << std::endl;  return intfield; }
  this->m_VelocityFieldInterpolator->SetInputImage(this->m_TimeVaryingVelocity);

  typedef  tvt TimeVaryingVelocityFieldType;
  typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType>         FieldIterator;
  typedef itk::ImageRegionIteratorWithIndex<tvt>         TVFieldIterator;
  typedef typename DeformationFieldType::IndexType DIndexType;
  typedef typename DeformationFieldType::PointType DPointType;
  typedef typename TimeVaryingVelocityFieldType::IndexType VIndexType;
  typedef typename TimeVaryingVelocityFieldType::PointType VPointType;

  if (starttimein < 0) starttimein=0;
  if (starttimein > 1) starttimein=1;
  if (finishtimein < 0) finishtimein=0;
  if (finishtimein > 1) finishtimein=1;

  float timesign=1.0;
  if (starttimein  >  finishtimein ) timesign= -1.0;
  FieldIterator m_FieldIter(this->GetDeformationField(), this->GetDeformationField()->GetLargestPossibleRegion());
//  std::cout << " Start Int " << starttimein <<  std::endl;
  if ( mask  && !this->m_ComputeThickness ) 
    {
  for(  m_FieldIter.GoToBegin(); !m_FieldIter.IsAtEnd(); ++m_FieldIter )
    {
      IndexType velind=m_FieldIter.GetIndex(); 
      VectorType disp;
      if (mask->GetPixel(velind) > 0.05 )
        disp=this->IntegratePointVelocity(starttimein, finishtimein , velind)*mask->GetPixel(velind);
      else disp.Fill(0);
     intfield->SetPixel(velind,disp);
    }
    } else {
  for(  m_FieldIter.GoToBegin(); !m_FieldIter.IsAtEnd(); ++m_FieldIter )
    {
      IndexType velind=m_FieldIter.GetIndex();
      VectorType disp=this->IntegratePointVelocity(starttimein, finishtimein , velind);
      intfield->SetPixel(velind,disp);
    }
  }
  if (this->m_ThickImage && this->m_MaskImage ){
    std::string outname=this->localANTSGetFilePrefix(this->m_OutputNamingConvention.c_str())+std::string("thick.nii.gz");
    std::cout << " write " << outname << std::endl;
    WriteImage<ImageType>(this->m_ThickImage,outname.c_str());
  }

  return intfield;

}


template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::DeformationFieldPointer 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::IntegrateLandmarkSetVelocity(float starttimein, float finishtimein,  typename ANTSImageRegistrationOptimizer<TDimension, TReal>::PointSetPointer mypoints ,  typename ANTSImageRegistrationOptimizer<TDimension, TReal>::ImagePointer refimage )
{

  typedef float  PixelType;
  typedef itk::Vector<float,TDimension>         VectorType;
  typedef itk::Image<VectorType,TDimension>     DeformationFieldType;
  typedef itk::Image<PixelType,TDimension> ImageType;
  typedef typename  ImageType::IndexType IndexType;
  typedef typename  ImageType::SizeType SizeType;
  typedef typename  ImageType::SpacingType SpacingType;
  typedef TimeVaryingVelocityFieldType tvt;


  DeformationFieldPointer intfield=DeformationFieldType::New();
  intfield->SetSpacing( this->m_CurrentDomainSpacing );
  intfield->SetOrigin(  this->m_DeformationField->GetOrigin() );
  intfield->SetDirection(  this->m_DeformationField->GetDirection() );
  intfield->SetLargestPossibleRegion( this->m_DeformationField->GetLargestPossibleRegion());
  intfield->SetRequestedRegion(   this->m_DeformationField->GetLargestPossibleRegion());
  intfield->SetBufferedRegion(  this->m_DeformationField->GetLargestPossibleRegion() );
  intfield->Allocate();
  VectorType zero;
  zero.Fill(0);
  intfield->FillBuffer(zero);
  if (starttimein == finishtimein) return intfield;
  if (!this->m_TimeVaryingVelocity) { std::cout << " No TV Field " << std::endl;  return intfield; }
  this->m_VelocityFieldInterpolator->SetInputImage(this->m_TimeVaryingVelocity);

  typedef  tvt TimeVaryingVelocityFieldType;
  typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType>         FieldIterator;
  typedef itk::ImageRegionIteratorWithIndex<tvt>         TVFieldIterator;
  typedef typename DeformationFieldType::IndexType DIndexType;
  typedef typename DeformationFieldType::PointType DPointType;
  typedef typename TimeVaryingVelocityFieldType::IndexType VIndexType;
  typedef typename TimeVaryingVelocityFieldType::PointType VPointType;

  if (starttimein < 0) starttimein=0;
  if (starttimein > 1) starttimein=1;
  if (finishtimein < 0) finishtimein=0;
  if (finishtimein > 1) finishtimein=1;

  float timesign=1.0;
  if (starttimein  >  finishtimein ) timesign= -1.0;

      unsigned long sz1 = mypoints->GetNumberOfPoints();
      for (unsigned long ii=0; ii<sz1; ii++)
	{ 
	PointType point;
	//std::cout <<" get point " << std::endl;
	mypoints->GetPoint(ii,&point);
	//std::cout <<" get point index " << point << std::endl;

	ImagePointType pt,wpt;
	for (unsigned int jj=0;  jj<ImageDimension; jj++) pt[jj]=point[jj];
	IndexType velind;
	bool bisinside=intfield->TransformPhysicalPointToIndex( pt, velind );
	//std::cout <<" inside? " << bisinside  << std::endl;
	if (bisinside)
	  {
//	  std::cout <<  "integrate " << std::endl;
	  VectorType disp=this->IntegratePointVelocity(starttimein, finishtimein , velind);
//	  std::cout <<  "put inside " << std::endl;
	  intfield->SetPixel(velind,disp);
	  }
	}

  return intfield;
 
}     



template<unsigned int TDimension, class TReal>
typename ANTSImageRegistrationOptimizer<TDimension, TReal>::VectorType 
ANTSImageRegistrationOptimizer<TDimension, TReal>
::IntegratePointVelocity(float starttimein, float finishtimein , IndexType velind) 
{

  typedef Point<float,itkGetStaticConstMacro(ImageDimension+1)> xPointType;
  this->m_Debug=false;
//  std::cout <<"Enter IP "<< std::endl;
  typedef typename VelocityFieldInterpolatorType::OutputType InterpPointType;

  typedef float  PixelType;
  typedef itk::Vector<float,TDimension>         VectorType;
  typedef itk::Image<VectorType,TDimension>     DeformationFieldType;
  typedef itk::Image<PixelType,TDimension> ImageType;
  typedef typename  ImageType::IndexType IndexType;
  typedef typename  ImageType::SizeType SizeType;
  typedef typename  ImageType::SpacingType SpacingType;
  typedef TimeVaryingVelocityFieldType tvt;

  VectorType zero;
  zero.Fill(0);
  if (starttimein == finishtimein) return zero;

  typedef  tvt TimeVaryingVelocityFieldType;
  typedef itk::ImageRegionIteratorWithIndex<DeformationFieldType>         FieldIterator;
  typedef itk::ImageRegionIteratorWithIndex<tvt>         TVFieldIterator;
  typedef typename DeformationFieldType::IndexType DIndexType;
  typedef typename DeformationFieldType::PointType DPointType;
  typedef typename TimeVaryingVelocityFieldType::IndexType VIndexType;
  typedef typename TimeVaryingVelocityFieldType::PointType VPointType;
  this->m_VelocityFieldInterpolator->SetInputImage(this->m_TimeVaryingVelocity);

  double dT=this->m_DeltaTime;
  unsigned int m_NumberOfTimePoints = this->m_TimeVaryingVelocity->GetLargestPossibleRegion().GetSize()[TDimension]; 
  if (starttimein < 0) starttimein=0;
  if (starttimein > 1) starttimein=1;
  if (finishtimein < 0) finishtimein=0;
  if (finishtimein > 1) finishtimein=1;

  float timesign=1.0;
  if (starttimein  >  finishtimein ) timesign= -1.0;
    
  VectorType velo;
  velo.Fill(0);
  xPointType pointIn1;
  xPointType pointIn2;
  xPointType pointIn3;
  typename VelocityFieldInterpolatorType::ContinuousIndexType  vcontind; 

  float itime = starttimein;  
  unsigned long ct = 0;
  float inverr=0; 
  float thislength=0,euclideandist=0;
  bool timedone = false;
  inverr=1110;
  VectorType disp;
  double deltaTime=dT,vecsign=1.0;
  SpacingType spacing= this->m_DeformationField->GetSpacing();
  if (starttimein  > finishtimein ) vecsign=-1.0;
  VIndexType vind;
  vind.Fill(0);
  for (unsigned int jj=0; jj<TDimension; jj++)
    {
    vind[jj]=velind[jj];
    pointIn1[jj]=velind[jj]*spacing[jj];
    }
  this->m_TimeVaryingVelocity->TransformIndexToPhysicalPoint( vind, pointIn1);
// time is in [0,1]
  pointIn1[TDimension]= starttimein*(m_NumberOfTimePoints-1);
  bool isinside=true;
  xPointType Y1x;
  xPointType Y2x;
  xPointType Y3x;
  xPointType Y4x;
  // set up parameters for start of integration 
  disp.Fill(0.0);
  timedone=false;  
  itime = starttimein;  
  ct = 0;
  while ( !timedone )
    {

     double itimetn1 = itime - timesign*deltaTime;
     double itimetn1h = itime - timesign*deltaTime*0.5;
      if (itimetn1h < 0 ) itimetn1h=0;
      if (itimetn1h > 1 ) itimetn1h=1;
      if (itimetn1 < 0 ) itimetn1=0;
      if (itimetn1 > 1 ) itimetn1=1;
      
      float totalmag=0;
      // first get current position of particle 
      typename VelocityFieldInterpolatorType::OutputType f1;  f1.Fill(0);
      typename VelocityFieldInterpolatorType::OutputType f2;  f2.Fill(0);
      typename VelocityFieldInterpolatorType::OutputType f3;  f3.Fill(0);
      typename VelocityFieldInterpolatorType::OutputType f4;  f4.Fill(0);  

      for (unsigned int jj=0; jj<TDimension; jj++)
	{
	  pointIn2[jj]=disp[jj]+pointIn1[jj];
	  Y1x[jj]=pointIn2[jj];  
	  Y2x[jj]=pointIn2[jj];
	  Y3x[jj]=pointIn2[jj];
	  Y4x[jj]=pointIn2[jj];
	}
  if (this->m_Debug)     std::cout << " p2 " << pointIn2<< std::endl;

      Y1x[TDimension]=itimetn1*(float)(m_NumberOfTimePoints-1);
      Y2x[TDimension]=itimetn1h*(float)(m_NumberOfTimePoints-1);
      Y3x[TDimension]=itimetn1h*(float)(m_NumberOfTimePoints-1);
      Y4x[TDimension]=itime*(float)(m_NumberOfTimePoints-1);

if (this->m_Debug)       std::cout << " p2 " << pointIn2<< " y1 " <<  Y1x[TDimension] <<  " y4 " <<   Y4x[TDimension]  << std::endl;

      if ( this->m_VelocityFieldInterpolator->IsInsideBuffer(Y1x) )
	{
	f1 = this->m_VelocityFieldInterpolator->Evaluate( Y1x );
	for (unsigned int jj=0; jj<TDimension; jj++) Y2x[jj]+=f1[jj]*deltaTime*0.5;
	} else isinside=false;
      if ( this->m_VelocityFieldInterpolator->IsInsideBuffer(Y2x) )
	{
	f2 = this->m_VelocityFieldInterpolator->Evaluate( Y2x );
	for (unsigned int jj=0; jj<TDimension; jj++) Y3x[jj]+=f2[jj]*deltaTime*0.5;
	}
      if ( this->m_VelocityFieldInterpolator->IsInsideBuffer(Y3x) )
	{
	f3 = this->m_VelocityFieldInterpolator->Evaluate( Y3x );
	for (unsigned int jj=0; jj<TDimension; jj++) Y4x[jj]+=f3[jj]*deltaTime;
	}
      if ( this->m_VelocityFieldInterpolator->IsInsideBuffer(Y4x) )
	{  f4 = this->m_VelocityFieldInterpolator->Evaluate( Y4x ); }
      
      for (unsigned int jj=0; jj<TDimension; jj++) 
       pointIn3[jj] = pointIn2[jj] + vecsign*deltaTime/6.0 * ( f1[jj] + 2.0*f2[jj] + 2.0*f3[jj] + f4[jj] );
      pointIn3[TDimension]=itime*(float)(m_NumberOfTimePoints-1);

      VectorType out;
      float mag=0, dmag=0;
      for (unsigned int jj=0; jj<TDimension; jj++) 
      { 
      out[jj]=pointIn3[jj]-pointIn1[jj];  
      mag+=(pointIn3[jj] - pointIn2[jj])*(pointIn3[jj] - pointIn2[jj]); 
      dmag+=(pointIn3[jj] - pointIn1[jj])*(pointIn3[jj] - pointIn1[jj]); 
      disp[jj]=out[jj];
      }

//      std::cout << " p3 " << pointIn3 << std::endl;
      dmag=sqrt(dmag);
      totalmag+=sqrt(mag);
      ct++;
      thislength += totalmag;
      euclideandist=dmag;
      itime = itime + deltaTime*timesign;
      if (starttimein > finishtimein) 
	{
	  if (itime <= finishtimein  ) timedone=true;
	}
      else if (thislength ==  0) timedone=true;
      else
	{
	  if (itime >= finishtimein ) timedone=true;
	}

    }

  // now we have the thickness value stored in thislength 
  if ( this->m_ThickImage && this->m_HitImage){

  // set up parameters for start of integration 
  velo.Fill(0);
  itime = starttimein;  
  timedone = false;
  vind.Fill(0);
  for (unsigned int jj=0; jj<TDimension; jj++)
    {
    vind[jj]=velind[jj];
    pointIn1[jj]=velind[jj]*spacing[jj];
    }
  this->m_TimeVaryingVelocity->TransformIndexToPhysicalPoint( vind, pointIn1);
// time is in [0,1]
  pointIn1[TDimension]= starttimein*(m_NumberOfTimePoints-1);
  // set up parameters for start of integration 
  disp.Fill(0.0);
  timedone=false;  
  itime = starttimein;  
  ct = 0;
  while ( !timedone )
    {

     double itimetn1 = itime - timesign*deltaTime;
     double itimetn1h = itime - timesign*deltaTime*0.5;
      if (itimetn1h < 0 ) itimetn1h=0;
      if (itimetn1h > 1 ) itimetn1h=1;
      if (itimetn1 < 0 ) itimetn1=0;
      if (itimetn1 > 1 ) itimetn1=1;
      
      //      float totalmag=0;
      // first get current position of particle 
      typename VelocityFieldInterpolatorType::OutputType f1;  f1.Fill(0);
      typename VelocityFieldInterpolatorType::OutputType f2;  f2.Fill(0);
      typename VelocityFieldInterpolatorType::OutputType f3;  f3.Fill(0);
      typename VelocityFieldInterpolatorType::OutputType f4;  f4.Fill(0);  

      for (unsigned int jj=0; jj<TDimension; jj++)
	{
	  pointIn2[jj]=disp[jj]+pointIn1[jj];
	  Y1x[jj]=pointIn2[jj];  
	  Y2x[jj]=pointIn2[jj];
	  Y3x[jj]=pointIn2[jj];
	  Y4x[jj]=pointIn2[jj];
	}
  if (this->m_Debug)     std::cout << " p2 " << pointIn2<< std::endl;

      Y1x[TDimension]=itimetn1*(float)(m_NumberOfTimePoints-1);
      Y2x[TDimension]=itimetn1h*(float)(m_NumberOfTimePoints-1);
      Y3x[TDimension]=itimetn1h*(float)(m_NumberOfTimePoints-1);
      Y4x[TDimension]=itime*(float)(m_NumberOfTimePoints-1);
      if (this->m_Debug)       std::cout << " p2 " << pointIn2<< " y1 " <<  Y1x[TDimension] <<  " y4 " <<   Y4x[TDimension]  << std::endl;
      
      if ( this->m_VelocityFieldInterpolator->IsInsideBuffer(Y1x) )
	{
	f1 = this->m_VelocityFieldInterpolator->Evaluate( Y1x );
	for (unsigned int jj=0; jj<TDimension; jj++) Y2x[jj]+=f1[jj]*deltaTime*0.5;
	} else isinside=false;
      if ( this->m_VelocityFieldInterpolator->IsInsideBuffer(Y2x) )
	{
	f2 = this->m_VelocityFieldInterpolator->Evaluate( Y2x );
	for (unsigned int jj=0; jj<TDimension; jj++) Y3x[jj]+=f2[jj]*deltaTime*0.5;
	}
      if ( this->m_VelocityFieldInterpolator->IsInsideBuffer(Y3x) )
	{
	f3 = this->m_VelocityFieldInterpolator->Evaluate( Y3x );
	for (unsigned int jj=0; jj<TDimension; jj++) Y4x[jj]+=f3[jj]*deltaTime;
	}
      if ( this->m_VelocityFieldInterpolator->IsInsideBuffer(Y4x) )
	{  f4 = this->m_VelocityFieldInterpolator->Evaluate( Y4x ); }
      
      for (unsigned int jj=0; jj<TDimension; jj++) 
       pointIn3[jj] = pointIn2[jj] + vecsign*deltaTime/6.0 * ( f1[jj] + 2.0*f2[jj] + 2.0*f3[jj] + f4[jj] );
      pointIn3[TDimension]=itime*(float)(m_NumberOfTimePoints-1);


      VectorType out;
      float mag=0, dmag=0;
      for (unsigned int jj=0; jj<TDimension; jj++) 
      { 
      out[jj]=pointIn3[jj]-pointIn1[jj];  
      mag+=(pointIn3[jj] - pointIn2[jj])*(pointIn3[jj] - pointIn2[jj]); 
      dmag+=(pointIn3[jj] - pointIn1[jj])*(pointIn3[jj] - pointIn1[jj]); 
      disp[jj]=out[jj];
      }
      itime = itime + deltaTime*timesign;
      if (starttimein > finishtimein) 
	{
	  if (itime <= finishtimein  ) timedone=true;
	}
      else
	{
	  if (itime >= finishtimein ) timedone=true;
	}
     
      //        bool isingray=true; 
      if ( this->m_MaskImage ) {
	if ( this->m_MaskImage->GetPixel(velind) ) {
	VIndexType thind2;
	IndexType thind;
	bool isin=this->m_TimeVaryingVelocity->TransformPhysicalPointToIndex( pointIn3, thind2 );
	for (unsigned int ij=0; ij<ImageDimension; ij++) thind[ij]=thind2[ij];
        if (isin){
        unsigned long lastct=(unsigned long) this->m_HitImage->GetPixel(thind);
        unsigned long newct=lastct+1;
        float oldthick=this->m_ThickImage->GetPixel(thind); 
        float newthick=(float)lastct/(float)newct*oldthick+1.0/(float)newct*euclideandist;
        this->m_HitImage->SetPixel( thind,  newct );
        this->m_ThickImage->SetPixel(thind, newthick );
	}
	else std::cout << " thind " << thind << " edist " << euclideandist << " p3 " << pointIn3 << " p1 " << pointIn1 << std::endl;
	//        this->m_ThickImage->SetPixel(thind, thislength );
      }
      }
    }


      }


//  if (!isinside) { std::cout << " velind " << velind << " not inside " << Y1 << std::endl;   }

 if (this->m_Debug)   std::cout << " Length " << thislength << std::endl;
  this->m_Debug=false;
    return disp; 

}     




/**
 * Standard "PrintSelf" method
 */
template<unsigned int TDimension, class TReal>
void
ANTSImageRegistrationOptimizer<TDimension, TReal>
::PrintSelf( std::ostream& os, Indent indent) const
{
    Superclass::PrintSelf( os, indent );
}



} // end namespace itk
#endif