explore_data14.py 113 KB
Newer Older
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
#!/usr/bin/env python3
#from numpy import float64
#from tensorflow.contrib.image.ops.gen_distort_image_ops import adjust_hsv_in_yiq

__copyright__ = "Copyright 2018, Elphel, Inc."
__license__   = "GPL-3.0+"
__email__     = "andrey@elphel.com"

import os
import sys
import glob
import imagej_tiff as ijt
import numpy as np
import resource
import re
#import timeit
import matplotlib.pyplot as plt
from scipy.ndimage.filters import gaussian_filter
import time
import tensorflow as tf

#http://stackoverflow.com/questions/287871/print-in-terminal-with-colors-using-python
class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[38;5;214m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    BOLDWHITE = '\033[1;37m'
    UNDERLINE = '\033[4m'
TIME_START = time.time()
TIME_LAST  = TIME_START
    
def print_time(txt="",end="\n"):
    global TIME_LAST
    t = time.time()
    if txt:
        txt +=" "
    print(("%s"+bcolors.BOLDWHITE+"at %.4fs (+%.4fs)"+bcolors.ENDC)%(txt,t-TIME_START,t-TIME_LAST), end = end)
    TIME_LAST = t

def _dtype_feature(ndarray):
    """match appropriate tf.train.Feature class with dtype of ndarray. """
    assert isinstance(ndarray, np.ndarray)
    dtype_ = ndarray.dtype
    if dtype_ == np.float64 or dtype_ == np.float32:
        return lambda array: tf.train.Feature(float_list=tf.train.FloatList(value=array))
    elif dtype_ == np.int64:
        return lambda array: tf.train.Feature(int64_list=tf.train.Int64List(value=array))
    else:  
        raise ValueError("The input should be numpy ndarray. \
                           Instead got {}".format(ndarray.dtype))
def readTFRewcordsEpoch(train_filename):
#    filenames = [train_filename]
#    dataset = tf.data.TFRecordDataset(filenames)
    if not  '.tfrecords' in train_filename:
        train_filename += '.tfrecords'
    record_iterator = tf.python_io.tf_record_iterator(path=train_filename)
    corr2d_list=[]
    target_disparity_list=[]
    gt_ds_list = []
    for string_record in record_iterator:
        example = tf.train.Example()
        example.ParseFromString(string_record)
        corr2d_list.append(np.array(example.features.feature['corr2d'] .float_list .value))
        target_disparity_list.append(np.array(example.features.feature['target_disparity'] .float_list .value[0]))
        gt_ds_list.append(np.array(example.features.feature['gt_ds'] .float_list .value))
    corr2d=            np.array(corr2d_list)
    target_disparity = np.array(target_disparity_list)
    gt_ds =            np.array(gt_ds_list)
    return corr2d, target_disparity, gt_ds   
#"/data_ssd/lwir_sets/lwir_test1/1562390086_121105/v01/ml32"
#1562390086_121105-ML_DATA-32B-AOT-FZ0.03-D00.00000.tiff
#    PATTERN_CORRD = "-D*.tiff"
#1562390086_121105-DSI_GT-AUX.tiff
def writeTFRecordsFromImageSet(
        model_ml_path,    # model/version/ml_dir
        export_mode,      # 0 - GT average, 1 - GT FG, 2 - GT BG, 3 - AUX disparity, 4 - use FG/BG closest to AUX
        random_offset,    # for modes 0..2 - add random offset of -random_offset to +random_offset, in mode 3 add random to  GT average if no AUX data
        pathTFR,          #TFR directory
        rms_ratio_split = None# Fixing Java export that splits near horizontal surface in bg/fg
        ):
    debug = 1
    scene = os.path.basename(os.path.dirname(os.path.dirname(model_ml_path))) #'1562390086_121105'
    scene_version = os.path.basename(os.path.dirname(model_ml_path)) #'v01
    fname = scene+'-'+scene_version+ ('-M%d-R%1.3f_EXTRA'%(export_mode,random_offset)).replace('.','_')
    img_filenameTFR = os.path.join(pathTFR,'img',fname)
    dsi_list = glob.glob(os.path.join(model_ml_path, ExploreData.PATTERN_CORRD))
    if not dsi_list:
        print ("DSI list is empty, nothing to do ...")
        return
    dsi_list.sort()
    gt_aux=glob.glob(os.path.join(os.path.dirname(model_ml_path), ExploreData.PATTERN_GTAUX))[0]
    corr_layers =  ['hor-aux', 'vert-aux','diagm-aux', 'diago-aux']
    #Get tiles data from the GT_AUX file
    img_gt_aux = ijt.imagej_tiff(gt_aux,ijt.IJFGBG.DSI_NAMES) #["disparity","strength","rms","rms-split","fg-disp","fg-str","bg-disp","bg-str","aux-disp","aux-str"]
    num_tiles = img_gt_aux.image.shape[0]*img_gt_aux.image.shape[1]
    all_image_tiles = np.array(range(num_tiles))
    #now read in all scanned files 
    indx = 0
    dsis = np.empty((0))
    dsis_other = np.empty((0))
    for img_path in dsi_list: # all correlation files
        tiff = ijt.imagej_tiff(img_path, corr_layers,all_image_tiles)
        corr2d =   tiff.corr2d.reshape((num_tiles,-1)) # [300][4*81]
        payloads = tiff.payload # [300][11]
        if not indx: # Create array when dimensions are known
            dsis =       np.empty((len(dsi_list), corr2d.shape[0], corr2d.shape[1]), corr2d.dtype)
            dsis_other = np.empty((len(dsi_list), payloads.shape[0], payloads.shape[1]), payloads.dtype)
        dsis[indx] =        corr2d
        dsis_other[indx] =  payloads
        indx += 1
    pass
    '''
    Prepare target disparity from the gt_aux file, filling the gaps in GT data 
    '''
    '''
    Fix bug in the exported data - merge FG/BG back if rms/rms_split < rms_ratio_split
    '''
    if not rms_ratio_split is None: # should be 3.0 < rms_ratio_split < 5.8)
#        merge = img_gt_aux.image[...,ijt.IJFGBG.RMS]/(img_gt_aux.image[...,ijt.IJFGBG.RMS_SPLIT]+1e-6) <  rms_ratio_split
        dmin = 0.5
        merge = (img_gt_aux.image[...,ijt.IJFGBG.RMS] < 
                (np.minimum(np.nan_to_num(img_gt_aux.image[...,ijt.IJFGBG.DISPARITY]), dmin) * img_gt_aux.image[...,ijt.IJFGBG.RMS_SPLIT] * rms_ratio_split))

        keep_split = np.logical_not(merge)
        img_gt_aux.image[...,ijt.IJFGBG.FG_DISP] = np.select(
            [merge,keep_split],
            [img_gt_aux.image[...,ijt.IJFGBG.DISPARITY],img_gt_aux.image[...,ijt.IJFGBG.FG_DISP]])
        img_gt_aux.image[...,ijt.IJFGBG.FG_STR] = np.select(
            [merge,keep_split],
            [img_gt_aux.image[...,ijt.IJFGBG.STRENGTH],img_gt_aux.image[...,ijt.IJFGBG.FG_STR]])
        img_gt_aux.image[...,ijt.IJFGBG.BG_DISP] = np.select(
            [merge,keep_split],
            [img_gt_aux.image[...,ijt.IJFGBG.DISPARITY],img_gt_aux.image[...,ijt.IJFGBG.BG_DISP]])
        img_gt_aux.image[...,ijt.IJFGBG.BG_STR] = np.select(
            [merge,keep_split],
            [img_gt_aux.image[...,ijt.IJFGBG.STRENGTH],img_gt_aux.image[...,ijt.IJFGBG.BG_STR]])
        img_gt_aux.image[...,ijt.IJFGBG.RMS_SPLIT] = np.select(
            [merge,keep_split],
            [img_gt_aux.image[...,ijt.IJFGBG.RMS],img_gt_aux.image[...,ijt.IJFGBG.RMS_SPLIT]])
#    nn_disparity =     np.nan_to_num(rslt[...,0], copy = False)

    # if export_mode == 0 (default):
    disparity =        img_gt_aux.image[...,ijt.IJFGBG.DISPARITY]
    strength =         img_gt_aux.image[...,ijt.IJFGBG.STRENGTH]
    if export_mode == 1:
        disparity =    img_gt_aux.image[...,ijt.IJFGBG.FG_DISP]
        strength =     img_gt_aux.image[...,ijt.IJFGBG.FG_STR]
    elif export_mode == 2:
        disparity =    img_gt_aux.image[...,ijt.IJFGBG.BG_DISP]
        strength =     img_gt_aux.image[...,ijt.IJFGBG.BG_STR]
        
    if (export_mode == 4) or (export_mode == 3):
        #1) replace nan in aux with average gt
        strength =     img_gt_aux.image[...,ijt.IJFGBG.AUX_STR]
        
        aux_nan = np.isnan(img_gt_aux.image[...,ijt.IJFGBG.AUX_DISP])
        disparity =    np.select(
            [aux_nan,                                    np.logical_not(aux_nan)],
            [img_gt_aux.image[...,ijt.IJFGBG.DISPARITY], img_gt_aux.image[...,ijt.IJFGBG.AUX_DISP]])
        
        use_fg = np.abs(img_gt_aux.image[...,ijt.IJFGBG.FG_DISP] - disparity) < np.abs(img_gt_aux.image[...,ijt.IJFGBG.BG_DISP] - disparity)
        d_gt =    np.select(
            [use_fg, np.logical_not(use_fg)],
            [img_gt_aux.image[...,ijt.IJFGBG.FG_DISP], img_gt_aux.image[...,ijt.IJFGBG.BG_DISP]]
            )
        s_gt =     np.select(
            [use_fg, np.logical_not(use_fg)],
            [img_gt_aux.image[...,ijt.IJFGBG.FG_STR], img_gt_aux.image[...,ijt.IJFGBG.BG_STR]]
            )
        if (export_mode == 4):
            disparity = d_gt
            strength =  s_gt
    else:
        d_gt = disparity
        s_gt =  strength

    extra = np.concatenate((
        img_gt_aux.image[...,ijt.IJFGBG.AUX_DISP].reshape(-1,1),
Andrey Filippov's avatar
Andrey Filippov committed
183
        img_gt_aux.image[...,ijt.IJFGBG.FG_DISP].reshape(-1,1),
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
        img_gt_aux.image[...,ijt.IJFGBG.BG_DISP].reshape(-1,1),
        img_gt_aux.image[...,ijt.IJFGBG.RMS].reshape(-1,1),
        img_gt_aux.image[...,ijt.IJFGBG.RMS_SPLIT].reshape(-1,1)
        ),1)
    
    if debug > 1:
        mytitle = "Disparity with gaps"
        fig = plt.figure()
        fig.canvas.set_window_title(scene+mytitle)
        fig.suptitle(mytitle)
        plt.imshow(d_gt)# d_gt.flatten)
        plt.colorbar()
        
        mytitle = "Strength with gaps"
        fig = plt.figure()
        fig.canvas.set_window_title(scene+mytitle)
        fig.suptitle(mytitle)
        plt.imshow(s_gt) # s_gt.flatten)
        plt.colorbar()
        
        d_gt = np.copy(d_gt)    
        s_gt = np.copy(s_gt)
    #next values may be modified to fill gaps, so copy them before
    '''
    fill gaps on ground truth slices only
     
    '''
    fillGapsByLaplacian(
            d_gt, # val, # will be modified in place
            s_gt, # wght, # will be modified in place
            w_diag = 0.7,
            w_reduce = 0.7,
            num_pass = 50,
            eps = 1E-6)
                    
    if debug > 1:
        mytitle = "Disparity w/o gaps"
        fig = plt.figure()
        fig.canvas.set_window_title(scene+mytitle)
        fig.suptitle(mytitle)
        plt.imshow(d_gt)
        plt.colorbar()
        
        mytitle = "Strength w/o gaps"
        fig = plt.figure()
        fig.canvas.set_window_title(scene+mytitle)
        fig.suptitle(mytitle)
        plt.imshow(s_gt)
        plt.colorbar()
    disparity = disparity.flatten()
    strength =  strength.flatten()
    d_gt = d_gt.flatten()
    s_gt = s_gt.flatten()
    '''
    Assemble synthetic image, selecting each tile from the nearest available disparity sweep file
    Currently even in mode s (aux) only sweep files are used (rounded to the nearest step). Consider
    using real GT_AUX measured (not available currently as imageJ output, need to modify+rerun
    '''
    corr2d =           np.zeros((dsis.shape[1],dsis.shape[2]),dsis.dtype)
    target_disparity = np.zeros((dsis.shape[1],            1),dsis.dtype)
    gt_ds =            np.zeros((dsis.shape[1],            2),dsis.dtype)
    for nt in range(num_tiles):
        d = disparity[nt]
        add_random = (export_mode != 3)
        if strength[nt] <= 0.0:
            d = d_gt[nt]
            add_random = True
        best_indx = 0
        dmn = d
        dmx = d
        if add_random:
            dmn -= random_offset
            dmx += random_offset
            
        fit_list = []
        for indx in range (dsis_other.shape[0]):
            dsi_d = dsis_other[indx][nt][ijt.IJML.TARGET]
            if abs (dsi_d - d) < abs (dsis_other[best_indx][nt][ijt.IJML.TARGET] - d):
                best_indx = indx
            if (dsi_d >= dmn) and (dsi_d <= dmx):
                fit_list.append(indx)
        if not len(fit_list):
            fit_list.append(best_indx)
        #select random index from the list - even if no random (it will just be a 1-element list then)
        indx = np.random.choice(fit_list) # possible to add weights
        target_disparity[nt][0] = dsis_other[indx][nt][ijt.IJML.TARGET]
        gt_ds[nt][0] = d_gt[nt]
        gt_ds[nt][1] = s_gt[nt]
        corr2d[nt] = dsis[indx][nt]

    if debug > 1:
        tilesX = img_gt_aux.image.shape[1]
        tilesY = img_gt_aux.image.shape[0]
        tileH =  tiff.tileH
        tileW =  tiff.tileW
        ncorr2_layers = corr2d.shape[1]//(tileH * tileW)
        
        mytitle = "Target Disparity"
        fig = plt.figure()
        fig.canvas.set_window_title(scene+": "+mytitle)
        fig.suptitle(mytitle)
        plt.imshow(target_disparity.reshape((tilesY, tilesX)))
        plt.colorbar()
        
        dbg_corr2d = np.zeros((tilesY * tileH, tilesX*tileW, ncorr2_layers), corr2d.dtype)
        for tileY in range(tilesY):
            for tileX in range(tilesX):
                for nl in range(ncorr2_layers):
                    dbg_corr2d[tileY * tileH : (tileY + 1) * tileH, tileX * tileW : (tileX + 1) * tileW, nl] = (
                    corr2d[tileY * tilesX + tileX].reshape((ncorr2_layers, tileH * tileW))[nl].reshape((tileH, tileW)))
                    pass
        for nl in range(ncorr2_layers):
            corr2d_layer =dbg_corr2d[:,:,nl]
            mytitle = "Corr2D-"+str(nl)
            fig = plt.figure()
            fig.canvas.set_window_title(scene+": "+mytitle)
            fig.suptitle(mytitle)
            plt.imshow(corr2d_layer)
            plt.colorbar()
    #end of debug output
    if not  '.tfrecords' in img_filenameTFR:
        img_filenameTFR += '.tfrecords'

    tfr_filename=img_filenameTFR.replace(' ','_')
    print_time("Saving test image %s as tiles..."%(img_filenameTFR),end = " ")
    try:
        os.makedirs(os.path.dirname(tfr_filename))
    except:
        pass     
          
###    writer = tf.python_io.TFRecordWriter(tfr_filename)
    writer = tf.io.TFRecordWriter(tfr_filename)
    dtype_feature_corr2d =   _dtype_feature(corr2d)
    dtype_target_disparity = _dtype_feature(target_disparity)
    dtype_feature_gt_ds =    _dtype_feature(gt_ds)
    dtype_feature_extra =    _dtype_feature(extra)
    for i in range(num_tiles):
        x = corr2d[i].astype(np.float32)
        y = target_disparity[i].astype(np.float32)
        z = gt_ds[i].astype(np.float32)
        e = extra[i].astype(np.float32)
        d_feature = {'corr2d':          dtype_feature_corr2d(x),
                     'target_disparity':dtype_target_disparity(y),
                     'gt_ds':           dtype_feature_gt_ds(z),
                     'extra':           dtype_feature_extra(e)}
        example = tf.train.Example(features=tf.train.Features(feature=d_feature))
        writer.write(example.SerializeToString())
        pass
    writer.close()
    print()
    sys.stdout.flush()        

def fillGapsByLaplacian(
        val, # will be modified in place
        wght, # will be modified in place
        w_diag = 0.7,
        w_reduce = 0.7,
        num_pass = 10,
        eps = 1E-6,
        debug_level = 0):
    dirs  = ((-1,0), (-1,1), (0,1), (1,1), (1,0), (1,-1), (0,-1), (-1,-1))
    wneib = (  1.0,  w_diag,  1.0,  w_diag,  1.0,  w_diag,  1.0,  w_diag)
    gap_tiles =   []
    gap_neibs =   []
    rows = val.shape[0]
    cols = wght.shape[1]
    for row in range(rows):
        for col in range (cols):
            if wght[row][col] <= 0.0:
                neibs =   []
                for dr, neib in enumerate(dirs): 
                    nrow = row + neib[0]
                    ncol = col + neib[1]
                    if (nrow >= 0) and (ncol >= 0) and (nrow < rows) and (ncol < cols):
                        neibs.append((nrow,ncol,dr))
                gap_tiles.append((row,col))
                gap_neibs.append(neibs)
    if not len(gap_tiles):
        return # no gaps to fill
    valn =  np.copy(val)         
    wghtn = np.copy(wght)
    achange = eps * np.max(wght)
    for npass in range (num_pass):
        num_new = 1
        max_diff = 0.0;
        for tile, neibs in zip (gap_tiles, gap_neibs):
            swn = 0.0
            sw =  0.0
            swd = 0.0;
            for neib in neibs: # (row,col,direction)
                w = wght[neib[0]][neib[1]] * wneib[neib[2]]
                sw += w
                if w > 0:
                    swd += w * val[neib[0]][neib[1]]
                swn += wneib[neib[2]]
            if (sw > 0):    
                valn [tile[0]][tile[1]] = swd/sw    
            wghtn[tile[0]][tile[1]] = w_reduce * sw/swn
            if (wght[tile[0]][tile[1]]) <= 0:
                num_new += 1
            wdiff = abs(wghtn[tile[0]][tile[1]] - wght[tile[0]][tile[1]])
            max_diff = max(max_diff, wdiff)
        np.copyto(val,  valn)         
        np.copyto(wght, wghtn)
        if (debug_level > 3):
            print("Pass %d, max_diff = %f"%(npass, max_diff))
        if (num_new == 0) and (max_diff < achange):
            break

    
def writeTFRewcordsImageTiles(img_path, tfr_filename): # test_set=False):
    num_tiles = 242*324 # fixme
    all_image_tiles = np.array(range(num_tiles))
    corr_layers =  ['hor-pairs', 'vert-pairs','diagm-pair', 'diago-pair']
    img =          ijt.imagej_tiff(img_path, corr_layers, all_image_tiles)
    """
    Values read from correlation file, it now may differ from the COMBO-DSI:
    1) The target disparities used for correlations are replaced if they are too far from the rig (GT) values and
    replaced by interpolation from available neighbors. If there are no suitable neighbors, target disparity is
    derived from the rig data by adding a random offset (specified in ImageJ plugin configuration ML section)
    2) correlation is performed around the defined tiles extrapolating disparity. rig data may be 0 disparity,
    0 strength if there is no rig data for those tiles. That means that such tiles can only be used as peripherals
    i (now 5x5) clusters, not for the cluster centers where GT is needed. 
    """
    corr2d =           img.corr2d.reshape((num_tiles,-1))
    target_disparity = img.target_disparity.reshape((num_tiles,-1))
    gt_ds =            img.gt_ds.reshape((num_tiles,-1))
      
    """
    Replace GT data with zero strength with nan, zero strength
    nan2 = np.array((np.nan,0), dtype=np.float32)            
    gt_ds[np.where(gt_ds[:,1]==0)] = nan2            
    """

    if not  '.tfrecords' in tfr_filename:
        tfr_filename += '.tfrecords'

    tfr_filename=tfr_filename.replace(' ','_')
    try:
        os.makedirs(os.path.dirname(tfr_filename))
    except:
        pass     
          
    writer = tf.io.TFRecordWriter(tfr_filename)
    dtype_feature_corr2d =   _dtype_feature(corr2d)
    dtype_target_disparity = _dtype_feature(target_disparity)
    dtype_feature_gt_ds =    _dtype_feature(gt_ds)
    for i in range(num_tiles):
        x = corr2d[i].astype(np.float32)
        y = target_disparity[i].astype(np.float32)
        z = gt_ds[i].astype(np.float32)
        d_feature = {'corr2d':          dtype_feature_corr2d(x),
                     'target_disparity':dtype_target_disparity(y),
                     'gt_ds':           dtype_feature_gt_ds(z)}
        example = tf.train.Example(features=tf.train.Features(feature=d_feature))
        writer.write(example.SerializeToString())
        pass
    writer.close()
    sys.stdout.flush()        



class ExploreData:
    """
    TODO: add to constructor parameters
    """
    
    PATTERN = "*-DSI_COMBO.tiff"
    PATTERN_GTAUX = "*-DSI_GT-AUX.tiff"
    PATTERN_CORRD = "*-D*.tiff"
#    ML_DIR = "ml"
#    ML_PATTERN = "*-ML_DATA*OFFS*.tiff"
#    ML_PATTERN = "*-ML_DATA*MAIN*.tiff"
#    ML_PATTERN = "*-ML_DATA*MAIN.tiff"
#    ML_PATTERN = "*-ML_DATA*MAIN_RND*.tiff"
##   ML_PATTERN = "*-ML_DATA*RIG_RND*.tiff"
#    ML_PATTERN = "*-ML_DATA*OFFS-0.20000_0.20000.tiff"
    """
1527182801_296892-ML_DATARND-32B-O-FZ0.05-OFFS-0.20000_0.20000.tiff
1527182805_696892-ML_DATA-32B-O-FZ0.05-RIG_RND2.00000.tiff
    """
#1562390086_121105-DSI_GT-AUX.tiff    
    def getComboList(self, top_dir, latest_version_only):
        if not top_dir:
            return []
        tlist = []
        for i in range(5):
            pp = top_dir#) ,'**', patt) # works
            for _ in range (i):
                pp = os.path.join(pp,'*')
            pp = os.path.join(pp, ExploreData.PATTERN)
            tlist += glob.glob(pp)
            if (self.debug_level > 0):    
                print (pp+" "+str(len(tlist)))
        if (self.debug_level > 0):    
            print("Found "+str(len(tlist))+" combo DSI files in "+top_dir+" :")
            if (self.debug_level > 1):    
                print("\n".join(tlist))
        if latest_version_only:
            models = {}
            for p in tlist:
                model = os.path.dirname(os.path.dirname(p))
                if (not model in models) or ( models[model]< p):
                    models[model] = p
            tlist = [v for v in models.values()]
            if (self.debug_level > 0):    
                print("After filtering the latest versions only, left "+str(len(tlist))+" combo DSI files in "+top_dir+" :")
                if (self.debug_level > 1):    
                    print("\n".join(tlist))
        tlist.sort()
        return tlist
    
    def loadComboFiles(self, tlist):
        indx = 0
        images = []
        if (self.debug_level>2):
            print(str(resource.getrusage(resource.RUSAGE_SELF)))
        layers =  ['disparity_rig','strength_rig','disparity_main']
        for combo_file in tlist:
            tiff = ijt.imagej_tiff(combo_file,layers)
            if not indx:
                images = np.empty((len(tlist), tiff.image.shape[0],tiff.image.shape[1],tiff.image.shape[2]), tiff.image.dtype)
            images[indx] = tiff.image
            if (self.debug_level>2):
                print(str(indx)+": "+str(resource.getrusage(resource.RUSAGE_SELF)))
            indx += 1
        return images
    
    def getGtAuxList(self, top_dir, latest_version_only):
        if not top_dir:
            return []
        tlist = []
        for i in range(5):
            pp = top_dir#) ,'**', patt) # works
            for _ in range (i):
                pp = os.path.join(pp,'*')
            pp = os.path.join(pp, ExploreData.PATTERN_GTAUX)
            tlist += glob.glob(pp)
            if (self.debug_level > 0):    
                print (pp+" "+str(len(tlist)))
        if (self.debug_level > 0):    
            print("Found "+str(len(tlist))+" combo DSI files in "+top_dir+" :")
            if (self.debug_level > 1):    
                print("\n".join(tlist))
        if latest_version_only:
            models = {}
            for p in tlist:
                model = os.path.dirname(os.path.dirname(p))
                if (not model in models) or ( models[model]< p):
                    models[model] = p
            tlist = [v for v in models.values()]
            if (self.debug_level > 0):    
                print("After filtering the latest versions only, left "+str(len(tlist))+" GT/AUX DSI files in "+top_dir+" :")
                if (self.debug_level > 1):    
                    print("\n".join(tlist))
        tlist.sort()
        return tlist

    def getMLSweepFiles(self,
                        gtaux_list,
                        ml_name = "ml32"):
        files_list = []
        target_disparities = []
        for gtaux in gtaux_list:
#            files_list.append([])
            ml_path =  os.path.join(os.path.dirname(gtaux),ml_name)
            sweep_list = glob.glob(os.path.join(ml_path, ExploreData.PATTERN_CORRD))
            sweep_list.sort()
            disparities = np.zeros((len(sweep_list)),dtype=float)
            for i,f in enumerate(sweep_list):
                disparities[i] = float(re.search(".*-D([0-9.]*)\.tiff",f).groups()[0])
            files_list.append(sweep_list)
            target_disparities.append(disparities) 
        return  files_list,  target_disparities  
            
        


    def loadGtAuxFiles(self, tlist):
        indx = 0
        images = []
        if (self.debug_level>2):
            print(str(resource.getrusage(resource.RUSAGE_SELF)))
#  IJFGBG.DSI_NAMES = ["disparity","strength","rms","rms-split","fg-disp","fg-str","bg-disp","bg-str","aux-disp","aux-str"]

        layers = ijt.IJFGBG.DSI_NAMES
        for gtaux_file in tlist:
            tiff = ijt.imagej_tiff(gtaux_file,layers)
            if not indx:
                images = np.empty((len(tlist), tiff.image.shape[0],tiff.image.shape[1],tiff.image.shape[2]), tiff.image.dtype)
            images[indx] = tiff.image
            if (self.debug_level>2):
                print(str(indx)+": "+str(resource.getrusage(resource.RUSAGE_SELF)))
            indx += 1
        return images
  
    def selectDSPairFromGtaux(
            self,
            gtaux,
            mode,  #0 - average, 1 - FG, 2 - BG, 3 - AUX, 4 select FG/BG closest to aux
            rms_ratio_split = None): # fixing bug in exported data - use rms_ratio_split = 4.0
        if not rms_ratio_split is None:
##            merge = gtaux[...,ijt.IJFGBG.RMS]/(gtaux[...,ijt.IJFGBG.RMS_SPLIT]+1e-6) <  rms_ratio_split
            dmin = 0.5
            merge = (gtaux[...,ijt.IJFGBG.RMS] < 
                (np.minimum(np.nan_to_num(gtaux[...,ijt.IJFGBG.DISPARITY]), dmin) *
                  gtaux[...,ijt.IJFGBG.RMS_SPLIT] * 
                  rms_ratio_split))
            keep_split = np.logical_not(merge)
            gtaux[...,ijt.IJFGBG.FG_DISP] = np.select(
                [merge, keep_split],
                [gtaux[...,ijt.IJFGBG.DISPARITY], gtaux[...,ijt.IJFGBG.FG_DISP]])
            gtaux[..., ijt.IJFGBG.FG_STR] = np.select(
                [merge, keep_split],
                [gtaux[...,ijt.IJFGBG.STRENGTH], gtaux[...,ijt.IJFGBG.FG_STR]])
            gtaux[..., ijt.IJFGBG.BG_DISP] = np.select(
                [merge, keep_split],
                [gtaux[...,ijt.IJFGBG.DISPARITY], gtaux[...,ijt.IJFGBG.BG_DISP]])
            gtaux[...,ijt.IJFGBG.BG_STR] = np.select(
                [merge, keep_split],
                [gtaux[...,ijt.IJFGBG.STRENGTH], gtaux[...,ijt.IJFGBG.BG_STR]])
            gtaux[...,ijt.IJFGBG.RMS_SPLIT] = np.select(
                [merge, keep_split],
                [gtaux[...,ijt.IJFGBG.RMS], gtaux[...,ijt.IJFGBG.RMS_SPLIT]])
            
        ds_pair = np.empty((gtaux.shape[0],gtaux.shape[1],gtaux.shape[2], 3), dtype=gtaux.dtype)
        if mode == 0:
            ds_pair[:,:,:,0] = gtaux[:,:,:,ijt.IJFGBG.DISPARITY] # 0
            ds_pair[:,:,:,1] = gtaux[:,:,:,ijt.IJFGBG.STRENGTH]  # 1
        elif mode == 1:
            ds_pair[:,:,:,0] = gtaux[:,:,:,ijt.IJFGBG.FG_DISP]   # 4
            ds_pair[:,:,:,1] = gtaux[:,:,:,ijt.IJFGBG.FG_STR]    # 5
        elif mode == 2:
            ds_pair[:,:,:,0] = gtaux[:,:,:,ijt.IJFGBG.BG_DISP]   # 6
            ds_pair[:,:,:,1] = gtaux[:,:,:,ijt.IJFGBG.BG_STR]    # 7
        elif mode == 3:
            ds_pair[:,:,:,0] = gtaux[:,:,:,ijt.IJFGBG.AUX_DISP]  # 8 
            ds_pair[:,:,:,1] = gtaux[:,:,:,ijt.IJFGBG.AUX_DISP]  # 9
        elif mode == 4:
#        strength =     img_gt_aux.image[...,ijt.IJFGBG.AUX_STR]
        #1) replace nan in aux with average gt
            aux_nan = np.isnan(gtaux[:,:,:,ijt.IJFGBG.AUX_DISP])
            disparity =    np.select(
                [aux_nan,                         np.logical_not(aux_nan)],
                [gtaux[...,ijt.IJFGBG.DISPARITY], gtaux[...,ijt.IJFGBG.AUX_DISP]])
        #select FG/BG that is closest to AUX disparity (or DISPARITY if AUX undefined)    
            use_fg = np.abs(gtaux[...,ijt.IJFGBG.FG_DISP] - disparity) < np.abs(gtaux[...,ijt.IJFGBG.BG_DISP] - disparity)
            ds_pair[:,:,:,0] =    np.select(
                [use_fg, np.logical_not(use_fg)],
                [gtaux[:,:,:,ijt.IJFGBG.FG_DISP], gtaux[:,:,:,ijt.IJFGBG.BG_DISP]]
                )
            ds_pair[:,:,:,1] =    np.select(
                [use_fg, np.logical_not(use_fg)],
                [gtaux[:,:,:,ijt.IJFGBG.FG_STR], gtaux[:,:,:,ijt.IJFGBG.BG_STR]]
                )
            
        ds_pair[:,:,:,2] = gtaux[:,:,:, ijt.IJFGBG.AUX_DISP]     # 8
        
        for nf in range (ds_pair.shape[0]):
            if (self.debug_level > 3):
                print ("---- nf=%d"%(nf,))
            fillGapsByLaplacian(
                    ds_pair[nf,:,:,0], # val, # will be modified in place
                    ds_pair[nf,:,:,1], # wght, # will be modified in place
                    w_diag = 0.7,
                    w_reduce = 0.7,
                    num_pass = 20,
                    eps = 1E-6,
                    debug_level = self.debug_level)
            if (self.debug_level > 0):
                print ("---- nf=%d min = %f mean = %f max = %f"%(
                    nf,
                    ds_pair[nf,:,:,0].min(),
                    ds_pair[nf,:,:,0].mean(),
                    ds_pair[nf,:,:,0].max()))
                print("zero strength",np.nonzero(ds_pair[nf,:,:,1]==0.0))
        
        return ds_pair 

    
    def getHistogramDSI(
            self, 
            list_rds,
            disparity_bins =    1000,
            strength_bins =      100,
            disparity_min_drop =  -0.1,
            disparity_min_clip =  -0.1,
            disparity_max_drop = 100.0,
            disparity_max_clip = 100.0,
            strength_min_drop =    0.1,
            strength_min_clip =    0.1,
            strength_max_drop =    1.0,
            strength_max_clip =    0.9,
            max_main_offset =      0.0,
            normalize =           True,
#            no_histogram =        False            
            ):
        good_tiles_list=[]
        for combo_rds in list_rds:
            good_tiles = np.empty((combo_rds.shape[0], combo_rds.shape[1],combo_rds.shape[2]), dtype=bool)
            for ids in range (combo_rds.shape[0]): #iterate over all scenes ds[2][rows][cols]
                ds = combo_rds[ids]
                disparity = ds[...,0]
                strength =  ds[...,1]
                good_tiles[ids] =  disparity >= disparity_min_drop
                good_tiles[ids] &= disparity <= disparity_max_drop
                good_tiles[ids] &= strength >=  strength_min_drop
                good_tiles[ids] &= strength <=  strength_max_drop
                if max_main_offset > 0.0: #2.0
                    disparity_main = ds[...,2] #measured disparity (here aux_disp)?
                    good_tiles[ids] &= disparity_main <= (disparity + max_main_offset)
                    good_tiles[ids] &= disparity_main >= (disparity - max_main_offset)
                disparity = np.nan_to_num(disparity, copy = False) # to be able to multiply by 0.0 in mask | copy=False, then out=disparity all done in-place
                strength =  np.nan_to_num(strength, copy = False)  # likely should never happen
                np.clip(disparity, disparity_min_clip, disparity_max_clip, out = disparity)
                np.clip(strength, strength_min_clip, strength_max_clip, out = strength)
            good_tiles_list.append(good_tiles)
        combo_rds = np.concatenate(list_rds)
        hist, xedges, yedges = np.histogram2d( # xedges, yedges - just for debugging
            x =      combo_rds[...,1].flatten(), # average disparity from main
            y =      combo_rds[...,0].flatten(), # average strength from main
            bins=    (strength_bins, disparity_bins),
            range=   ((strength_min_clip,strength_max_clip),(disparity_min_clip,disparity_max_clip)),
            normed=  normalize,
            weights= np.concatenate(good_tiles_list).flatten())
        for i, combo_rds in enumerate(list_rds):
            for ids in range (combo_rds.shape[0]): #iterate over all scenes ds[2][rows][cols]
                combo_rds[ids][...,1]*= good_tiles_list[i][ids]
        return hist, xedges, yedges
    
    
    def __init__(self,
               topdir_train,
               topdir_test,
               ml_subdir,          #'ml32'
               ml_pattern,
               latest_version_only,
               max_main_offset =      2.0, # > 0.0 - do not use main camera tiles with offset more than this  
               debug_level =          0,
               disparity_bins =    1000,
               strength_bins =      100,
               disparity_min_drop =  -0.1,
               disparity_min_clip =  -0.1,
               disparity_max_drop = 100.0,
               disparity_max_clip = 100.0,
               strength_min_drop =    0.1,
               strength_min_clip =    0.1,
               strength_max_drop =    1.0,
               strength_max_clip =    0.9,
               
               hist_sigma =           2.0,  # Blur log histogram
               hist_cutoff=           0.001, #  of maximal
               #new in LWIR mode
               fgbg_mode =            0,  #  average, 1 - FG, 2 - BG (3 - AUX - not used here)
               rms_merge_ratio =     14.0, 
               rnd_tile =             0.5, #  use corr2d rendered with target disparity this far shuffled from the GT - individual tile
               rnd_plate =            0.5, #  use corr2d rendered with target disparity this far shuffled from the GT common for (5x5) plate
               radius =               2):
    # file name
        self.debug_level =        debug_level
        self.ml_pattern =         ml_pattern
        self.ml_subdir =          ml_subdir          
        #self.testImageTiles()    
        self.max_main_offset =    max_main_offset
        self.disparity_bins =     disparity_bins
        self.strength_bins =      strength_bins
        self.disparity_min_drop = disparity_min_drop
        self.disparity_min_clip = disparity_min_clip
        self.disparity_max_drop = disparity_max_drop
        self.disparity_max_clip = disparity_max_clip
        self.strength_min_drop =  strength_min_drop
        self.strength_min_clip =  strength_min_clip
        self.strength_max_drop =  strength_max_drop
        self.strength_max_clip =  strength_max_clip
        self.hist_sigma =         hist_sigma  # Blur log histogram
        self.hist_cutoff=         hist_cutoff #  of maximal 
        self.fgbg_mode =          fgbg_mode   #0,  #  average, 1 - FG, 2 - BG (3 - AUX - not used here)
        self.rms_merge_ratio =    rms_merge_ratio # fixing exported data bug
        self.rnd_tile =           rnd_tile    #  1.0 #  use corr2d rendered with target disparity this far shuffled from the GT
        self.rnd_plate =          rnd_plate   #  1.0 #  use corr2d rendered with target disparity this far shuffled from the GT
        self.radius =             radius 
        self.pre_log_offs =       0.001 # of histogram maximum
        self.good_tiles =         None
###     self.files_train =        self.getComboList(topdir_train, latest_version_only)
###     self.files_test =         self.getComboList(topdir_test, latest_version_only)
        self.files_train =        self.getGtAuxList(topdir_train, latest_version_only)
        self.files_test =         self.getGtAuxList(topdir_test, latest_version_only)


        
#        self.train_ds =           self.loadGtAuxFiles(self.files_train)
#        self.test_ds =            self.loadGtAuxFiles(self.files_test)
# new in LWIR - all laysrs, including AG, FG, BG and AUX D/S pairs, RMS and RMS_SPLIT 
        self.train_gtaux =           self.loadGtAuxFiles(self.files_train)
        self.test_gtaux =            self.loadGtAuxFiles(self.files_test)
        
        self.train_ds =              self.selectDSPairFromGtaux(self.train_gtaux, self.fgbg_mode, self.rms_merge_ratio)        
        self.test_ds =               self.selectDSPairFromGtaux(self.test_gtaux,  self.fgbg_mode, self.rms_merge_ratio)
        
        
        
        
        
        self.train_sweep_files, self.train_sweep_disparities = self.getMLSweepFiles(self.files_train, self.ml_subdir)
        self.test_sweep_files,  self.test_sweep_disparities =  self.getMLSweepFiles(self.files_test, self.ml_subdir)
        
        self.num_tiles = self.train_ds.shape[1]*self.train_ds.shape[2] 

        self.hist, _, _ = self.getHistogramDSI(
                list_rds =           [self.train_ds,self.test_ds], # combo_rds,
                disparity_bins =     self.disparity_bins,
                strength_bins =      self.strength_bins,
                disparity_min_drop = self.disparity_min_drop,
                disparity_min_clip = self.disparity_min_clip,
                disparity_max_drop = self.disparity_max_drop,
                disparity_max_clip = self.disparity_max_clip,
                strength_min_drop =  self.strength_min_drop,
                strength_min_clip =  self.strength_min_clip,
                strength_max_drop =  self.strength_max_drop,
                strength_max_clip =  self.strength_max_clip,
                max_main_offset =    self.max_main_offset,
                normalize =          True
#                no_histogram =       False
           )
        log_offset = self.pre_log_offs * self.hist.max()
        h_cutoff =   hist_cutoff * self.hist.max()
        lhist =         np.log(self.hist + log_offset)
        blurred_lhist = gaussian_filter(lhist, sigma = self.hist_sigma)
        self.blurred_hist  = np.exp(blurred_lhist) - log_offset
        self.good_tiles =  self.blurred_hist >= h_cutoff
        self.blurred_hist *= self.good_tiles # set bad ones to zero 

    def exploreNeibs(self,
                     data_ds, # disparity/strength data for all files (train or test)
                     radius,  # how far to look from center each side ( 1- 3x3, 2 - 5x5)
                     disp_thesh = 5.0): # reduce effective variance for higher disparities
        """
        For each tile calculate difference between max and min among neighbors and number of qualifying neighbors (bad center is not removed)
        data_ds may mismatch with the correlation files - correlation files have data in extrapolated areas and replaced for large difference with GT
        
        """
        disp_min =   np.empty_like(data_ds[...,0], dtype = np.float)
        disp_max =   np.empty_like(disp_min, dtype = np.float)
        tile_neibs = np.zeros_like(disp_min, dtype = np.int)
        dmin = data_ds[...,0].min()
        dmax = data_ds[...,0].max()
        good_tiles = self.getBB(data_ds) >= 0 # histogram index or -1 for bad tiles
        side = 2 * radius + 1
        for nf, ds in enumerate(data_ds):
            disp = ds[...,0] 
            height = disp.shape[0]
            width = disp.shape[1]
            bad_max = np.ones((height+side, width+side),  dtype=float) * dmax
            bad_min = np.ones((height+side, width+side),  dtype=float) * dmin
            good =    np.zeros((height+side, width+side), dtype=int)
            #Assign centers of the array, replace bad tiles with max/min (so they will not change min/max) 
            bad_max[radius:height+radius,radius:width+radius] = np.select([good_tiles[nf]],[disp],default = dmax)
            bad_min[radius:height+radius,radius:width+radius] = np.select([good_tiles[nf]],[disp],default = dmin)
            good   [radius:height+radius,radius:width+radius] = good_tiles[nf]
            disp_min  [nf,...] = disp 
            disp_max  [nf,...] = disp
            tile_neibs[nf,...] = good_tiles[nf]
            for offset_y in range(-radius, radius+1):
                oy = offset_y+radius
                for offset_x in range(-radius, radius+1):
                    ox = offset_x+radius
                    if offset_y or offset_x: # Skip center - already copied
                        np.minimum(disp_min[nf], bad_max[oy:oy+height, ox:ox+width], out=disp_min[nf])
                        np.maximum(disp_max[nf], bad_min[oy:oy+height, ox:ox+width], out=disp_max[nf])
                        tile_neibs[nf] +=  good[oy:oy+height, ox:ox+width]
                        pass
                    pass
                pass
            pass
        
        #disp_thesh
        disp_avar = disp_max - disp_min
        disp_rvar = disp_avar * disp_thesh / np.maximum(disp_max, 0.001) # removing division by 0 error - those tiles will be anyway discarded 
        disp_var = np.select([disp_max >= disp_thesh, disp_max < disp_thesh],[disp_rvar,disp_avar])
        return disp_var, tile_neibs # per file/tile: (max - min among 5x5 neibs),(number of "ggod" neib. tiles) 

    def assignBatchBins(self,
                        disp_bins,
                        str_bins,
                        files_per_scene = 5,   # not used here, will be used when generating batches
                        min_batch_choices=10,  # not used here, will be used when generating batches
                        max_batch_files = 10): # not used here, will be used when generating batches
        """
        for each disparity/strength combination (self.disparity_bins * self.strength_bins = 1000*100) provide number of "large"
        variable-size disparity/strength bin, or -1 if this disparity/strength combination does not seem right
        """
        self.files_per_scene = files_per_scene
        self.min_batch_choices=min_batch_choices
        self.max_batch_files = max_batch_files
        
        hist_to_batch =       np.zeros((self.blurred_hist.shape[0],self.blurred_hist.shape[1]),dtype=int) #zeros_like?
##        hist_to_batch_multi = np.ones((self.blurred_hist.shape[0],self.blurred_hist.shape[1]),dtype=int) #zeros_like?
        scale_hist= (disp_bins * str_bins)/self.blurred_hist.sum()
        norm_b_hist =     self.blurred_hist * scale_hist
##        disp_list = [] # last disparity hist 
#        disp_multi = [] # number of disp rows to fit
        disp_run_tot = 0.0
        disp_batch = 0
        disp=0
        num_batch_bins = disp_bins * str_bins
        disp_hist = np.linspace(0, num_batch_bins, disp_bins+1)
        batch_index = 0
        num_members = np.zeros((num_batch_bins,),int)
        while disp_batch < disp_bins:
            #disp_multi.append(1)
#        while (disp < self.disparity_bins):
#            disp_target_tot =disp_hist[disp_batch+1]
            disp_run_tot_new = disp_run_tot
            disp0 = disp # start disaprity matching disp_run_tot 
            while (disp_run_tot_new < disp_hist[disp_batch+1]) and (disp < self.disparity_bins):
                disp_run_tot_new += norm_b_hist[:,disp].sum()
                disp+=1;
                disp_multi = 1
                while   (disp_batch < (disp_bins - 1)) and (disp_run_tot_new >= disp_hist[disp_batch+2]):
                    disp_batch += 1 # only if large disp_bins and very high hist value
                    disp_multi += 1
            # now  disp_run_tot - before this batch disparity col
            str_bins_corr = str_bins * disp_multi # if too narrow disparity column - multiply number of strength columns
            str_bins_corr_last = str_bins_corr -1
            str_hist = np.linspace(disp_run_tot, disp_run_tot_new, str_bins_corr + 1)
            str_run_tot_new = disp_run_tot
#            str_batch = 0
            str_index=0
#            wide_col = norm_b_hist[:,disp0:disp] #disp0 - first column, disp - last+ 1
            #iterate in linescan along the column
            for si in range(self.strength_bins):
                for di in range(disp0, disp,1):
                    if norm_b_hist[si,di] > 0.0 :
                        str_run_tot_new += norm_b_hist[si,di]
                        # do not increment after last to avoid precision issues 
                        if (batch_index < num_batch_bins) and (num_members[batch_index] > 0) and (str_index < str_bins_corr_last) and (str_run_tot_new > str_hist[str_index+1]):
                            batch_index += 1
                            str_index +=   1
                        if batch_index < num_batch_bins :     
                            hist_to_batch[si,di] = batch_index
                            num_members[batch_index] += 1
                        else:
                            pass
                    else:
                        hist_to_batch[si,di] = -1
                        
            batch_index += 1 # it was not incremented afterthe last in the column to avoid rounding error 
            disp_batch += 1
            disp_run_tot = disp_run_tot_new
            pass
        self.hist_to_batch = hist_to_batch
        return hist_to_batch        

    def getBB(self, data_ds):
        """
        for each file, each tile get histogram index (or -1 for bad tiles)
        """
##        hist_to_batch = self.hist_to_batch
##        files_batch_list = []
        disp_step = ( self.disparity_max_clip - self.disparity_min_clip )/ self.disparity_bins 
        str_step =  ( self.strength_max_clip -  self.strength_min_clip )/ self.strength_bins
        bb = np.empty_like(data_ds[...,0],dtype=int)
        for findx in range(data_ds.shape[0]):
            ds = data_ds[findx]
            gt = ds[...,1] > 0.0 # OK
            db = (((ds[...,0] - self.disparity_min_clip)/disp_step).astype(int))*gt
            sb = (((ds[...,1] - self.strength_min_clip)/ str_step).astype(int))*gt
            np.clip(db, 0, self.disparity_bins-1, out = db)
            np.clip(sb, 0, self.strength_bins-1, out = sb)
            bb[findx] = (self.hist_to_batch[sb.reshape(self.num_tiles),db.reshape(self.num_tiles)])   .reshape(db.shape[0],db.shape[1]) + (gt -1)
        return bb

    def makeBatchLists(self,
            data_ds =      None,  # (disparity,strength) per scene, per tile #(19, 15, 20, 3)
            data_gtaux =   None,  # full set of layers from GT_AUX file ("disparity","strength","rms","rms-split",...) (19, 15, 20, 10)
            disp_var =     None,  # difference between maximal and minimal disparity for each scene, each tile
            disp_neibs =   None,  # number of valid tiles around each center tile (for 3x3 (radius = 1) - maximal is 9  
            min_var =      None,  # Minimal tile variance to include
            max_var =      None,  # Maximal tile variance to include
            min_neibs =    None,  # Minimal number of valid tiles to include
            use_split =    False, # Select y single/multi-plane tiles (center only)
            keep_split =   False, # When sel_split, keep only multi-plane tiles (false - only single-plane)
            rnd_tile =     None,  # disparity random for each tile 
            rnd_plate =    None): # disparity random for each plate (now 25 tiles)
        if not rnd_tile is None:
            self.rnd_tile = rnd_tile
        if not rnd_plate is None:
            self.rnd_plate = rnd_plate
        #for file names:
        self.min_neibs = min_neibs
        self.use_split = use_split
        self.keep_split = keep_split
           
        if data_ds is None:
            data_ds =      self.train_ds
        num_batch_tiles = np.empty((data_ds.shape[0],self.hist_to_batch.max()+1),dtype = int) 
        border_tiles = np.ones((data_ds.shape[1],data_ds.shape[2]), dtype=np.bool)
        border_tiles[self.radius:-self.radius,self.radius:-self.radius] = False
        border_tiles = border_tiles.reshape(self.num_tiles)
        bb = self.getBB(data_ds) # (19, 15, 20)
        use_neibs = not ((disp_var is None) or (disp_neibs is None) or (min_var is None) or (max_var is None) or (min_neibs is None))
        list_of_file_lists=[]
        for findx in range(data_ds.shape[0]):
            foffs = findx * self.num_tiles 
            lst = []
            for i in range (self.hist_to_batch.max()+1):
                lst.append([])
            if use_neibs:    
                disp_var_tiles =   disp_var[findx].reshape(self.num_tiles)   # was [y,x]
                disp_neibs_tiles = disp_neibs[findx].reshape(self.num_tiles) # was [y,x]
            if use_split:
                if keep_split:
                    drop_tiles = (data_gtaux[findx,:,:,ijt.IJFGBG.RMS] <= data_gtaux[findx][...,ijt.IJFGBG.RMS_SPLIT]).reshape(self.num_tiles)
                else:
                    drop_tiles = (data_gtaux[findx,:,:,ijt.IJFGBG.RMS] >  data_gtaux[findx][...,ijt.IJFGBG.RMS_SPLIT]).reshape(self.num_tiles)
#                disp_split_tiles =     
            for n, indx in enumerate(bb[findx].reshape(self.num_tiles)):     # was [y,x]
                if indx >= 0:
                    if border_tiles[n]:
                        continue # do not use border tiles
                    if use_neibs:
                        if disp_neibs_tiles[n] < min_neibs:
                            continue # too few neighbors
                        if not disp_var_tiles[n] >= min_var:
                            continue #too small variance 
                        if not disp_var_tiles[n] <  max_var:
                            continue #too large variance 
                    if use_split:
                        if drop_tiles[n]:
                            continue #failed multi/single plane for DSI      
                    lst[indx].append(foffs + n)
            lst_arr=[]
            for i,l in enumerate(lst):
                lst_arr.append(l)
                num_batch_tiles[findx,i] = len(l)
            list_of_file_lists.append(lst_arr)
        self.list_of_file_lists= list_of_file_lists
        self.num_batch_tiles =   num_batch_tiles
        return list_of_file_lists, num_batch_tiles
    #todo: only use other files if there are no enough choices in the main file!
    
    '''
    Add random files to the list until each (now 40) of the full_num_choices has more
    than minimal (now 10) variants to chose from
    
    '''
    def augmentBatchFileIndices(self,
                                 seed_index,
                                 seed_list = None,
                                 min_choices=None,
                                 max_files = None,
                                 set_ds = None
                                 ):
        if min_choices is None:
            min_choices = self.min_batch_choices 
        if max_files is None:
            max_files =  self.max_batch_files
        if set_ds is None:
            set_ds = self.train_ds
        full_num_choices = self.num_batch_tiles[seed_index].copy()
        flist = [seed_index]
        if seed_list is None:
            seed_list = list(range(self.num_batch_tiles.shape[0]))
        all_choices = list(seed_list) # a copy of seed list
        all_choices.remove(seed_index) # seed_list made unique by the caller
###     list(filter(lambda a: a != seed_index, all_choices)) # remove all instances of seed_index
        for _ in range (max_files-1):
            if full_num_choices.min() >= min_choices:
                break
            if len(all_choices) == 0:
                print ("Nothing left in all_choices!")
                break
            findx = np.random.choice(all_choices)
            flist.append(findx)
            all_choices.remove(findx) # seed_list made unique by the caller
###            list(filter(lambda a: a != findx, all_choices)) # remove all instances of findx
            full_num_choices += self.num_batch_tiles[findx]

        file_tiles_sparse = [[] for _ in set_ds] #list of empty lists for each train scene (will be sparse)
         
        for nt in range(self.num_batch_tiles.shape[1]): #number of tiles per batch (not counting ml file variant) // radius2 - 40
            tl = []
            nchoices = 0
            for findx in flist:
                if (len(self.list_of_file_lists[findx][nt])):
                    tl.append(self.list_of_file_lists[findx][nt])
                nchoices+= self.num_batch_tiles[findx][nt]
                if nchoices >= min_choices: # use minimum of extra files
                    break;
            while len(tl)==0:
##                print("** BUG! could not find a single candidate from files ",flist," for cell ",nt)
##                print("trying to use some other cell")
                nt1 = np.random.randint(0,self.num_batch_tiles.shape[1])
                for findx in flist:
                    if (len(self.list_of_file_lists[findx][nt1])):
                        tl.append(self.list_of_file_lists[findx][nt1])
                    nchoices+= self.num_batch_tiles[findx][nt1]
                    if nchoices >= min_choices: # use minimum of extra files
                        break;
            tile = np.random.choice(np.concatenate(tl))
            """
Traceback (most recent call last):
  File "explore_data2.py", line 1041, in <module>
    ex_data.writeTFRewcordsEpoch(fpath, ml_list = ml_list_train, files_list = ex_data.files_train, set_ds= ex_data.train_ds, radius = RADIUS)
  File "explore_data2.py", line 761, in writeTFRewcordsEpoch
    corr2d_batch, target_disparity_batch, gt_ds_batch = ex_data.prepareBatchData(ml_list, seed_index, min_choices=None, max_files = None, ml_num = None, set_ds = set_ds, radius = radius)
  File "explore_data2.py", line 556, in prepareBatchData
    flist,tiles = self.augmentBatchFileIndices(seed_index, min_choices, max_files, set_ds)
  File "explore_data2.py", line 494, in augmentBatchFileIndices
    tile = np.random.choice(np.concatenate(tl))
ValueError: need at least one array to concatenate
            """
#            print (nt, tile, tile//self.num_tiles, tile % self.num_tiles)
            if not type (tile) is np.int64:
                print("tile=",tile)
            '''
            List 
            '''
            file_tiles_sparse[tile//self.num_tiles].append(tile % self.num_tiles) 
        file_tiles = []
        for findx in flist:
            file_tiles.append(np.sort(np.array(file_tiles_sparse[findx],dtype=int))) 
        return flist, file_tiles # file indices, list if tile indices for each file   
            
            
               
                
    def getMLList(self, ml_subdir, flist):
        ml_list = []
        for fn in flist:
#            ml_patt = os.path.join(os.path.dirname(fn), ml_subdir, ExploreData.ML_PATTERN)
##            if isinstance(ml_subdir,list)    
            ml_patt = os.path.join(os.path.dirname(fn), ml_subdir, self.ml_pattern)
            ml_list.append(glob.glob(ml_patt))
##        self.ml_list = ml_list
        return ml_list
            
    def getBatchData(
            self,
            flist,
##            tiles,
            ml_list,
            ml_num = None ): # 0 - use all ml files for the scene, >0 select random number
        if ml_num is None:
            ml_num = self.files_per_scene
        ml_all_files = []
        for findx in flist:
            mli =  list(range(len(ml_list[findx])))
            if (ml_num > 0) and (ml_num < len(mli)):
                mli_left = mli
                mli = []
                for _ in range(ml_num):
                    ml = np.random.choice(mli_left)
                    mli.append(ml)
                    mli_left.remove(ml)
            ml_files = []
            for ml_index in mli:
                ml_files.append(ml_list[findx][ml_index])
            ml_all_files.append(ml_files)        
                    
        return ml_all_files
    
    def prepareBatchData(self,
                         ml_list,
                         seed_index,
                         seed_list,
                         min_choices=None,
                         max_files = None,
                         ml_num = None,
                         set_ds = None,
                         radius = 0):
        """
        set_ds (from COMBO_DSI) is used to select tile clusters, exported values come from correlation files. 
        target_disparity for correlation files may be different than data_ds - replaced dureing ImageJ plugin
        export if main camera and the rig (GT) converged on different objects fro the same tile
        """
        if min_choices is None:
            min_choices = self.min_batch_choices #10
        if max_files is None:
            max_files = self.max_batch_files #10
        if ml_num is None:
            ml_num = self.files_per_scene #5
        if set_ds is None:
            set_ds = self.train_ds
        tiles_in_sample = (2 * radius + 1) * (2 * radius + 1)
        height = set_ds.shape[1]
        width =  set_ds.shape[2]
        width_m1 = width-1
        height_m1 = height-1
        corr_layers =  ['hor-pairs', 'vert-pairs','diagm-pair', 'diago-pair']
        flist,tiles = self.augmentBatchFileIndices(
            seed_index,
            seed_list,
            min_choices,
            max_files,
            set_ds)
        ml_all_files = self.getBatchData(
            flist,
            ml_list,
            0) # ml_num) # 0 - use all ml files for the scene, >0 select random number
        if self.debug_level > 1:
            print ("==============",seed_index, flist)
            for i, _ in enumerate(flist):
                print(i,"\n".join(ml_all_files[i])) 
                print(tiles[i]) 
        total_tiles = 0
        for i, t in enumerate(tiles):
            total_tiles += len(t) # tiles per scene * offset files per scene
        if self.debug_level > 1:
            print("Tiles in the batch=",total_tiles)
        corr2d_batch = None # np.empty((total_tiles, len(corr_layers),81))
        gt_ds_batch =            np.empty((total_tiles * tiles_in_sample, 2), dtype=float) 
        target_disparity_batch = np.empty((total_tiles * tiles_in_sample, ),  dtype=float) 
        start_tile = 0
        for nscene, scene_files in enumerate(ml_all_files):
            '''
            Create tiles list including neighbors
            '''
            full_tiles = np.empty([len(tiles[nscene]) * tiles_in_sample], dtype = int)
            indx = 0;
            for i, nt in enumerate(tiles[nscene]):
                ty = nt // width
                tx = nt % width
                for dy in range (-radius, radius+1):
                    y = np.clip(ty+dy,0,height_m1)
                    for dx in range (-radius, radius+1):
                        x = np.clip(tx+dx,0,width_m1)
                        full_tiles[indx] = y * width + x
                        indx += 1
            """
            Assign tiles to several correlation files
            """
            file_tiles = []
            file_indices = []
            for _ in scene_files:
                file_tiles.append([])
            num_scene_files = len(scene_files)    
            for t in full_tiles:
                fi = np.random.randint(0, num_scene_files) #error here - probably wrong ml file pattern (no files matched)
                file_tiles[fi].append(t)
                file_indices.append(fi)
            corr2d_list =           []
            target_disparity_list = []
            gt_ds_list =            []
            for fi, path in enumerate (scene_files):
                img = ijt.imagej_tiff(path, corr_layers, tile_list=file_tiles[fi]) #'hor-pairs' is not in list
                corr2d_list.append          (img.corr2d)
                target_disparity_list.append(img.target_disparity)
                gt_ds_list.append           (img.gt_ds)
            img_indices = [0] * len(scene_files)
            for i, fi in enumerate(file_indices):
                ti = img_indices[fi]
                img_indices[fi] += 1
                if corr2d_batch is None:
                    corr2d_batch = np.empty((total_tiles * tiles_in_sample, len(corr_layers), corr2d_list[fi].shape[-1]))
                gt_ds_batch            [start_tile] = gt_ds_list[fi][ti]
                target_disparity_batch [start_tile] = target_disparity_list[fi][ti]
                corr2d_batch           [start_tile] = corr2d_list[fi][ti]
                start_tile +=  1
            """
             Sometimes get bad tile in ML file that was not bad in COMBO-DSI
             Need to recover
             np.argwhere(np.isnan(target_disparity_batch))                 
            """
        bad_tiles = np.argwhere(np.isnan(target_disparity_batch))
        if (len(bad_tiles)>0):
            print ("*** Got %d bad tiles in a batch, no code to replace :-("%(len(bad_tiles)))
        self.corr2d_batch =           corr2d_batch
        self.target_disparity_batch = target_disparity_batch
        self.gt_ds_batch =            gt_ds_batch
        return corr2d_batch, target_disparity_batch, gt_ds_batch

    def writeTFRewcordsEpoch(self, tfr_filename, ml_list, files_list = None, set_ds= None, radius = 0, num_scenes = None): # test_set=False):
        # open the TFRecords file
        if not  '.tfrecords' in tfr_filename:
            tfr_filename += '.tfrecords'

        tfr_filename=tfr_filename.replace(' ','_')
        if files_list is None:
            files_list = self.files_train
            
        if set_ds is None: # (19, 15, 20, 3)
            set_ds = self.train_ds
        try:
            os.makedirs(os.path.dirname(tfr_filename))
            print("Created directory "+os.path.dirname(tfr_filename))
        except:
            print("Directory "+os.path.dirname(tfr_filename)+" already exists, using it")
            pass
        #skip writing if file exists - it will be possible to continue or run several instances
        if os.path.exists(tfr_filename):
            print(tfr_filename+" already exists, skipping generation. Please remove and re-run this program if you want to regenerate the file")
            return     
        writer = tf.io.TFRecordWriter(tfr_filename)
        if num_scenes is None:
            num_scenes = len(files_list)
        '''    
        if len(files_list) <= num_scenes:
            #create and shuffle repetitive list of files of num_scenes.length    
            seed_list = np.arange(num_scenes) % len(files_list)
            np.random.shuffle(seed_list)
        else:
            #shuffle all files and use first num_scenes of them
            seed_list = np.arange(len(files_list))
            np.random.shuffle(seed_list)
            seed_list = seed_list[:num_scenes]
        np.random.shuffle(seed_list)
        '''
        
        augment_list = []    
        for seed_indx in np.arange(len(files_list)):
            if  self.num_batch_tiles[seed_indx].sum() >0:
                augment_list.append(seed_indx)
        seed_list = list(augment_list) # seed list will be modified while augment_list will have unique/full list of suitable files          
        while len(seed_list) <  num_scenes:
            seed_list.append(np.random.choice(seed_list))             
        np.random.shuffle(seed_list)
        if len(seed_list) >=  num_scenes:
            seed_list = seed_list[:num_scenes]
        
        cluster_size = (2 * radius + 1) * (2 * radius + 1)
        for nscene, seed_index in enumerate(seed_list):
            corr2d_batch, target_disparity_batch, gt_ds_batch = ex_data.prepareBatchData( #'hor-pairs' is not in list
                ml_list,
                seed_index,
                augment_list,
                min_choices=None,
                max_files = None,
                ml_num = None,
                set_ds = set_ds, #DS data from all GT_AX files scanned
                radius = radius)
            #shuffles tiles in a batch
            tiles_in_batch =    corr2d_batch.shape[0]
            clusters_in_batch = tiles_in_batch // cluster_size
            permut = np.random.permutation(clusters_in_batch)
            corr2d_clusters =           corr2d_batch.          reshape((clusters_in_batch,-1)) 
            target_disparity_clusters = target_disparity_batch.reshape((clusters_in_batch,-1)) 
            gt_ds_clusters =            gt_ds_batch.           reshape((clusters_in_batch,-1)) 
                
            corr2d_batch_shuffled =           corr2d_clusters[permut].          reshape((tiles_in_batch, -1))
            target_disparity_batch_shuffled = target_disparity_clusters[permut].reshape((tiles_in_batch, -1))
            gt_ds_batch_shuffled =            gt_ds_clusters[permut].           reshape((tiles_in_batch, -1))
            
            if nscene == 0:
                dtype_feature_corr2d =   _dtype_feature(corr2d_batch_shuffled)
                dtype_target_disparity = _dtype_feature(target_disparity_batch_shuffled)
                dtype_feature_gt_ds =    _dtype_feature(gt_ds_batch_shuffled)

            for i in range(tiles_in_batch):
                x = corr2d_batch_shuffled[i].astype(np.float32)
                y = target_disparity_batch_shuffled[i].astype(np.float32)
                z = gt_ds_batch_shuffled[i].astype(np.float32)
                d_feature = {'corr2d':          dtype_feature_corr2d(x),
                             'target_disparity':dtype_target_disparity(y),
                             'gt_ds':           dtype_feature_gt_ds(z)}
                example = tf.train.Example(features=tf.train.Features(feature=d_feature))
                writer.write(example.SerializeToString())
            if (self.debug_level > 0):
                print_time("Scene %d (%d) of %d -> %s"%(nscene, seed_index, len(seed_list), tfr_filename))        
        writer.close()
        sys.stdout.flush()        


    
    def prepareBatchDataLwir(self,
                         ds_gt,      # ground truth disparity/strength
                         sweep_files,
                         sweep_disparities,
                         seed_index,
                         seed_list,
                         min_choices=None,
                         max_files = None,
                         set_ds =    None,
                         radius =    0,
                         rnd_tile =  0.0, ## disparity random for each tile
                         rnd_plate = 0.0):## disparity random for each plate (now 25 tiles)
        """
        set_ds (from COMBO_DSI) is used to select tile clusters, exported values come from correlation files. 
        target_disparity for correlation files may be different than data_ds - replaced dureing ImageJ plugin
        export if main camera and the rig (GT) converged on different objects fro the same tile
        """
        if min_choices is None:
            min_choices = self.min_batch_choices #10
        if max_files is None:
            max_files = self.max_batch_files #10
        if set_ds is None:
            set_ds = self.train_ds
        tiles_in_sample = (2 * radius + 1) * (2 * radius + 1)
        height = set_ds.shape[1]
        width =  set_ds.shape[2]
        width_m1 = width-1
        height_m1 = height-1
        corr_layers =  ['hor-aux', 'vert-aux','diagm-aux', 'diago-aux']
        
        flist0, tiles0 = self.augmentBatchFileIndices(
            seed_index,
            seed_list,
            min_choices,
            max_files,
            set_ds)
        
        flist = []
        tiles = []
        for f,t in zip (flist0,tiles0):
            if len(t):
                flist.append(f)
                tiles.append(t)

        total_tiles = 0
        for i, t in enumerate(tiles):
            total_tiles += len(t) # tiles per scene * offset files per scene
        if self.debug_level > 1:
            print("Tiles in the batch=",total_tiles)
        corr2d_batch =           np.empty((total_tiles * tiles_in_sample, len(corr_layers),81)) # fix 81 t0 correct
        gt_ds_batch =            np.empty((total_tiles * tiles_in_sample, 2), dtype=float) 
        target_disparity_batch = np.empty((total_tiles * tiles_in_sample, ),  dtype=float) 
        start_tile = 0
        for scene, scene_tiles in zip(flist, tiles):            
            '''
            Create tiles list including neighbors
            '''
            full_tiles = np.empty([len(scene_tiles) * tiles_in_sample], dtype = int)
            indx = 0;
            for i, nt in enumerate(scene_tiles):
                ty = nt // width
                tx = nt % width
                for dy in range (-radius, radius+1):
                    y = np.clip(ty+dy,0,height_m1)
                    for dx in range (-radius, radius+1):
                        x = np.clip(tx+dx,0,width_m1)
                        full_tiles[indx] = y * width + x
                        indx += 1

            scene_ds = ds_gt[scene,:,:,0:2].reshape(height * width,-1)
            disparity_tiles = scene_ds[full_tiles,0] # GT DSI for each of the scene tiles
            gtds_tiles =        scene_ds[full_tiles] # DS pairs for each tile
            gt_ds_batch[start_tile:start_tile+gtds_tiles.shape[0]] = gtds_tiles
            if rnd_plate > 0.0:
                for i in range(len(scene_tiles)):
                    disparity_tiles[i*tiles_in_sample : (i+1)*tiles_in_sample] += np.random.random() * 2 * rnd_plate - rnd_plate
            if rnd_tile > 0.0:
                disparity_tiles += np.random.random(disparity_tiles.shape[0]) * 2 * rnd_tile - rnd_tile
            # find target disparity approximations from the available sweep files
            sweep_indices = np.abs(np.add.outer(sweep_disparities[scene], -disparity_tiles)).argmin(0)
            sfs = list(set(sweep_indices))
            sfs.sort # unique sweep indices (files)
            #read required tiles from required files, place results where they belong
            for sf in sfs:
                #find which of the full_tiles belong to this file
                this_file_indices = np.nonzero(sweep_indices == sf)[0] #Returns a tuple of arrays, one for each dimension of a, containing the indices of the non-zero elements in that dimension. 
                tiles_to_read = full_tiles[this_file_indices]
                where_to_put = this_file_indices + start_tile # index in the batch array (1000 tiles)
                path = sweep_files[scene][sf]
                img = ijt.imagej_tiff(path, corr_layers, tile_list=tiles_to_read)
                corr2d_batch[where_to_put] =           img.corr2d
                target_disparity_batch[where_to_put] = img.target_disparity
            
            pass
            start_tile += full_tiles.shape[0]
        pass    
        bad_tiles = np.argwhere(np.isnan(target_disparity_batch))
        if (len(bad_tiles)>0):
            print ("*** Got %d bad tiles in a batch, no code to replace :-("%(len(bad_tiles)))
        self.corr2d_batch =           corr2d_batch
        self.target_disparity_batch = target_disparity_batch
        self.gt_ds_batch =            gt_ds_batch
        return corr2d_batch, target_disparity_batch, gt_ds_batch

    def writeTFRewcordsEpochLwir(self,
                                 tfr_filename,
                                 sweep_files,
                                 sweep_disparities,
                                 files_list = None,
                                 set_ds=      None,
                                 radius =     0,
                                 num_scenes = None,
                                 rnd_tile =   0.0, ## disparity random for each tile
                                 rnd_plate =  0.0):## disparity random for each plate (now 25 tiles)
        
        # open the TFRecords file
        
        fb = ""
        if self.use_split:
            fb = ["-FB1","-FB2"][self.keep_split] # single plane - FB1, split FG/BG planes - FB2
        
        tfr_filename+="-RT%1.2f-RP%1.2f-M%d-NB%d%s"%(rnd_tile,rnd_plate,self.fgbg_mode,self.min_neibs, fb)
        
        if not  '.tfrecords' in tfr_filename:
            tfr_filename += '.tfrecords'

        tfr_filename=tfr_filename.replace(' ','_')
        if files_list is None:
            files_list = self.files_train
            
        if set_ds is None: # (19, 15, 20, 3)
            set_ds = self.train_ds
        try:
            os.makedirs(os.path.dirname(tfr_filename))
            print("Created directory "+os.path.dirname(tfr_filename))
        except:
            print("Directory "+os.path.dirname(tfr_filename)+" already exists, using it")
            pass
        #skip writing if file exists - it will be possible to continue or run several instances
        if os.path.exists(tfr_filename):
            print(tfr_filename+" already exists, skipping generation. Please remove and re-run this program if you want to regenerate the file")
            return # Temporary disable     
        writer = tf.io.TFRecordWriter(tfr_filename)
        if num_scenes is None:
            num_scenes = len(files_list)
        '''    
        if len(files_list) <= num_scenes:
            #create and shuffle repetitive list of files of num_scenes.length    
            seed_list = np.arange(num_scenes) % len(files_list)
            np.random.shuffle(seed_list)
        else:
            #shuffle all files and use first num_scenes of them
            seed_list = np.arange(len(files_list))
            np.random.shuffle(seed_list)
            seed_list = seed_list[:num_scenes]
        '''    
        augment_list = []    
        for seed_indx in np.arange(len(files_list)):
            if  self.num_batch_tiles[seed_indx].sum() >0:
                augment_list.append(seed_indx)
        seed_list = list(augment_list) # seed list will be modified while augment_list will have unique/full list of suitable files          
        while len(seed_list) <  num_scenes:
            seed_list.append(np.random.choice(seed_list))             
        np.random.shuffle(seed_list)
        if len(seed_list) >=  num_scenes:
            seed_list = seed_list[:num_scenes]

        
        cluster_size = (2 * radius + 1) * (2 * radius + 1)
        for nscene, seed_index in enumerate(seed_list):
            corr2d_batch, target_disparity_batch, gt_ds_batch = ex_data.prepareBatchDataLwir( #'hor-pairs' is not in list
                ds_gt =             set_ds,
                sweep_files =       sweep_files,
                sweep_disparities = sweep_disparities,
                seed_index =        seed_index,
                seed_list =         augment_list,
                min_choices =       None,
                max_files =         None,
                set_ds =            set_ds, #DS data from all GT_AX files scanned
                radius =            radius,
                rnd_tile =          rnd_tile, ## disparity random for each tile
                rnd_plate =         rnd_plate)## disparity random for each plate (now 25 tiles)
                
            #shuffles tiles in a batch
            tiles_in_batch =    corr2d_batch.shape[0]
            clusters_in_batch = tiles_in_batch // cluster_size
            permut = np.random.permutation(clusters_in_batch)
            corr2d_clusters =           corr2d_batch.          reshape((clusters_in_batch,-1)) 
            target_disparity_clusters = target_disparity_batch.reshape((clusters_in_batch,-1)) 
            gt_ds_clusters =            gt_ds_batch.           reshape((clusters_in_batch,-1)) 
                
            corr2d_batch_shuffled =           corr2d_clusters[permut].          reshape((tiles_in_batch, -1))
            target_disparity_batch_shuffled = target_disparity_clusters[permut].reshape((tiles_in_batch, -1))
            gt_ds_batch_shuffled =            gt_ds_clusters[permut].           reshape((tiles_in_batch, -1))
            
            if nscene == 0:
                dtype_feature_corr2d =   _dtype_feature(corr2d_batch_shuffled)
                dtype_target_disparity = _dtype_feature(target_disparity_batch_shuffled)
                dtype_feature_gt_ds =    _dtype_feature(gt_ds_batch_shuffled)

            for i in range(tiles_in_batch):
                x = corr2d_batch_shuffled[i].astype(np.float32)
                y = target_disparity_batch_shuffled[i].astype(np.float32)
                z = gt_ds_batch_shuffled[i].astype(np.float32)
                d_feature = {'corr2d':          dtype_feature_corr2d(x),
                             'target_disparity':dtype_target_disparity(y),
                             'gt_ds':           dtype_feature_gt_ds(z)}
                example = tf.train.Example(features=tf.train.Features(feature=d_feature))
                writer.write(example.SerializeToString())
            if (self.debug_level > 0):
                print_time("Scene %d (%d) of %d -> %s"%(nscene, seed_index, len(seed_list), tfr_filename))        
        writer.close()
        sys.stdout.flush()        




    
    def showVariance(self,
            rds_list,           # list of disparity/strength files, suchas training, testing 
            disp_var_list,      # list of disparity variance files. Same shape(but last dim) as rds_list
            num_neibs_list,    # list of number of tile neibs files. Same shape(but last dim) as rds_list
            variance_min =       0.0,
            variance_max =       1.5,
            neibs_min =          9,
            #Same parameters as for the histogram 
#            disparity_bins =    1000,
#            strength_bins =      100,
#            disparity_min_drop =  -0.1,
#            disparity_min_clip =  -0.1,
#            disparity_max_drop = 100.0,
#            disparity_max_clip = 100.0,
#            strength_min_drop =    0.1,
#            strength_min_clip =    0.1,
#            strength_max_drop =    1.0,
#            strength_max_clip =    0.9,
            normalize =           False): # True):
        good_tiles_list=[]
        for nf, combo_rds in enumerate(rds_list):
            disp_var =  disp_var_list[nf]
            num_neibs = num_neibs_list[nf]
            good_tiles = np.empty((combo_rds.shape[0], combo_rds.shape[1],combo_rds.shape[2]), dtype=bool)
            for ids in range (combo_rds.shape[0]): #iterate over all scenes ds[2][rows][cols]
                ds = combo_rds[ids]
                disparity = ds[...,0]
                strength =  ds[...,1]
                variance =  disp_var[ids]
                neibs =     num_neibs[ids]
                good_tiles[ids] =  disparity >= self.disparity_min_drop
                good_tiles[ids] &= disparity <= self.disparity_max_drop
                good_tiles[ids] &= strength >=  self.strength_min_drop
                good_tiles[ids] &= strength <=  self.strength_max_drop
                good_tiles[ids] &= neibs    >=  neibs_min
                good_tiles[ids] &= variance >=  variance_min
                good_tiles[ids] &= variance <   variance_max
                disparity = np.nan_to_num(disparity, copy = False) # to be able to multiply by 0.0 in mask | copy=False, then out=disparity all done in-place
                strength =  np.nan_to_num(strength, copy = False)  # likely should never happen
#                np.clip(disparity, self.disparity_min_clip, self.disparity_max_clip, out = disparity)
#                np.clip(strength, self.strength_min_clip, self.strength_max_clip, out = strength)
            good_tiles_list.append(good_tiles)
        combo_rds = np.concatenate(rds_list)
#        hist, xedges, yedges = np.histogram2d( # xedges, yedges - just for debugging
        hist, _, _ = np.histogram2d( # xedges, yedges - just for debugging
            x =      combo_rds[...,1].flatten(),
            y =      combo_rds[...,0].flatten(),
            bins=    (self.strength_bins, self.disparity_bins),
            range=   ((self.strength_min_clip,self.strength_max_clip),(self.disparity_min_clip,self.disparity_max_clip)),
            normed=  normalize,
            weights= np.concatenate(good_tiles_list).flatten())
        
        mytitle = "Disparity_Strength variance histogram"
        fig = plt.figure()
        fig.canvas.set_window_title(mytitle)
        fig.suptitle("Min variance = %f, max variance = %f, min neibs = %d"%(variance_min, variance_max, neibs_min))
#        plt.imshow(hist, vmin=0, vmax=.1 * hist.max())#,vmin=-6,vmax=-2) # , vmin=0, vmax=.01)
        plt.imshow(hist, vmin=0.0, vmax=300.0)#,vmin=-6,vmax=-2) # , vmin=0, vmax=.01)
        plt.colorbar(orientation='horizontal') # location='bottom')
        
#        for i, combo_rds in enumerate(rds_list):
#            for ids in range (combo_rds.shape[0]): #iterate over all scenes ds[2][rows][cols]
#                combo_rds[ids][...,1]*= good_tiles_list[i][ids]
#        return hist, xedges, yedges

#MAIN
if __name__ == "__main__":
    LATEST_VERSION_ONLY = True
    try:
        topdir_train = sys.argv[1]
    except IndexError:
#        topdir_train = "/mnt/dde6f983-d149-435e-b4a2-88749245cc6c/home/eyesis/x3d_data/data_sets/train"#test" #all/"
##        topdir_train = "/data_ssd/data_sets/train_mlr32_18d"
##        topdir_train = '/data_ssd/data_sets/test_only'# ''
###        topdir_train = '/data_ssd/data_sets/train_set2'# ''
        topdir_train = '/data_ssd/lwir_sets/lwir_train5'# ''
#        tf_data_5x5_main_10_heur
      
    try:
        topdir_test = sys.argv[2]
    except IndexError:
#        topdir_test = "/mnt/dde6f983-d149-435e-b4a2-88749245cc6c/home/eyesis/x3d_data/data_sets/test"#test" #all/"
#        topdir_test =  "/data_ssd/data_sets/test_mlr32_18d"
##        topdir_test = '/data_ssd/data_sets/test_only'
###        topdir_test = '/data_ssd/data_sets/test_set21'
        topdir_test = '/data_ssd/lwir_sets/lwir_test5'
        
      
    try:
        pathTFR =     sys.argv[3]
    except IndexError:
#        pathTFR = "/mnt/dde6f983-d149-435e-b4a2-88749245cc6c/home/eyesis/x3d_data/data_sets/tf_data_3x3b" #no trailing "/"
#        pathTFR = "/home/eyesis/x3d_data/data_sets/tf_data_5x5" #no trailing "/"
###        pathTFR = "/data_ssd/data_sets/tf_data_5x5_main_13_heur"
        pathTFR = '/data_ssd/lwir_sets/tf_data_5x5_9'
##        pathTFR = "/data_ssd/data_sets/tf_data_5x5_main_11_rnd"
##        pathTFR = "/data_ssd/data_sets/tf_data_5x5_main_12_rigrnd"

    try:
        ml_subdir =   sys.argv[4]
    except IndexError:
#      ml_subdir =   "ml"
#      ml_subdir =   "mlr32_18a"
#        ml_subdir =   "mlr32_18d"
#        ml_subdir =   "{ml32,mlr32_18d}"
        ml_subdir =   "ml32b*"
    try:
        ml_pattern =   sys.argv[5]
    except IndexError:
###     ml_pattern =   "*-ML_DATA*MAIN.tiff" ##        pathTFR = "/data_ssd/data_sets/tf_data_5x5_main_10_heur"
        ml_pattern =   "*-ML_DATA*-D*.tiff" ##        pathTFR = "/data_ssd/data_sets/tf_data_5x5_main_10_heur"
#1562390086_121105-ML_DATA-32B-AOT-FZ0.03-D00.00000.tiff        
        
        
##        ml_pattern =   "*-ML_DATA*MAIN_RND*.tiff" ##        pathTFR = "/data_ssd/data_sets/tf_data_5x5_main_11_rnd"
##        ml_pattern =  "*-ML_DATA*RIG_RND*.tiff" ##        pathTFR = "/data_ssd/data_sets/tf_data_5x5_main_12_rigrnd"

##   ML_PATTERN = "*-ML_DATA*RIG_RND*.tiff"
#1527182801_296892-ML_DATA-32B-O-FZ0.05-MAIN_RND2.00000.tiff
      
#  pathTFR = "/mnt/dde6f983-d149-435e-b4a2-88749245cc6c/home/eyesis/x3d_data/data_sets/tf_data_3x3b" #no trailing "/"
#  test_corr = '/home/eyesis/x3d_data/models/var_main/www/html/x3domlet/models/all-clean/overlook/1527257933_150165/v04/mlr32_18a/1527257933_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff' # overlook
#  test_corr = '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527256816_150165/v02/mlr32_18a/1527256816_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff' # State Street
#  test_corr = '/home/eyesis/x3d_data/models/dsi_combo_and_ml_all/state_street/1527256858_150165/v01/mlr32_18a/1527256858_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff'   # State Street
    """
/data_ssd/models/plane_1527182801/1527182805_696892/v02/mlr32_18d/1527182805_696892-ML_DATA-32B-O-FZ0.05-RIG_RND2.00000.tiff
/data_ssd/models/plane_1527182801/1527182805_696892/v02/mlr32_18d/1527182805_696892-ML_DATA-32B-O-FZ0.05-MAIN_RND2.00000.tiff
/data_ssd/models/plane_1527182801/1527182805_696892/v02/mlr32_18d/1527182805_696892-ML_DATA-32B-O-FZ0.05-MAIN.tiff
    
    test_corrs = [
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527257933_150165/v04/mlr32_18a/1527257933_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # overlook
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527256816_150165/v02/mlr32_18a/1527256816_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # State Street
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527256858_150165/v01/mlr32_18a/1527256858_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # State Street
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527182802_096892/v02/mlr32_18a/1527182802_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # near plane"
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527182805_096892/v02/mlr32_18a/1527182805_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # medium plane"
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527182810_096892/v02/mlr32_18a/1527182810_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # far plane
                ]
    test_corrs = [
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527257933_150165/v04/mlr32_18c/1527257933_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # overlook
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527256816_150165/v02/mlr32_18c/1527256816_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # State Street
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527256858_150165/v01/mlr32_18c/1527256858_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # State Street
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527182802_096892/v02/mlr32_18c/1527182802_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # near plane"
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527182805_096892/v02/mlr32_18c/1527182805_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # medium plane"
                '/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527182810_096892/v02/mlr32_18c/1527182810_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # far plane
                ]
    test_corrs = [
                '/data_ssd/data_sets/test_mlr32_18d/1527257933_150165/v04/mlr32_18d/1527257933_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # overlook
                '/data_ssd/data_sets/test_mlr32_18d/1527256816_150165/v02/mlr32_18d/1527256816_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # State Street
                '/data_ssd/data_sets/test_mlr32_18d/1527256858_150165/v01/mlr32_18d/1527256858_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # State Street
                '/data_ssd/data_sets/test_mlr32_18d/1527182802_096892/v02/mlr32_18d/1527182802_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # near plane"
                '/data_ssd/data_sets/test_mlr32_18d/1527182805_096892/v02/mlr32_18d/1527182805_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # medium plane"
                '/data_ssd/data_sets/test_mlr32_18d/1527182810_096892/v02/mlr32_18d/1527182810_096892-ML_DATA-32B-O-FZ0.05-MAIN.tiff', # far plane
                ]
    test_corrs = [
                '/data_ssd/data_sets/test_mlr32_18d/1527257933_150165/v04/mlr32_18d/1527257933_150165-ML_DATA-32B-O-FZ0.05-MAIN_RND2.00000.tiff', # overlook
                '/data_ssd/data_sets/test_mlr32_18d/1527256816_150165/v02/mlr32_18d/1527256816_150165-ML_DATA-32B-O-FZ0.05-MAIN_RND2.00000.tiff', # State Street
                '/data_ssd/data_sets/test_mlr32_18d/1527256858_150165/v01/mlr32_18d/1527256858_150165-ML_DATA-32B-O-FZ0.05-MAIN_RND2.00000.tiff', # State Street
                '/data_ssd/data_sets/test_mlr32_18d/1527182802_096892/v02/mlr32_18d/1527182802_096892-ML_DATA-32B-O-FZ0.05-MAIN_RND2.00000.tiff', # near plane"
                '/data_ssd/data_sets/test_mlr32_18d/1527182805_096892/v02/mlr32_18d/1527182805_096892-ML_DATA-32B-O-FZ0.05-MAIN_RND2.00000.tiff', # medium plane"
                '/data_ssd/data_sets/test_mlr32_18d/1527182810_096892/v02/mlr32_18d/1527182810_096892-ML_DATA-32B-O-FZ0.05-MAIN_RND2.00000.tiff', # far plane
                ]
    test_corrs = [
                '/data_ssd/data_sets/test_mlr32_18d/1527257933_150165/v04/mlr32_18d/1527257933_150165-ML_DATA-32B-O-FZ0.05-RIG_RND2.00000.tiff', # overlook
                '/data_ssd/data_sets/test_mlr32_18d/1527256816_150165/v02/mlr32_18d/1527256816_150165-ML_DATA-32B-O-FZ0.05-RIG_RND2.00000.tiff', # State Street
                '/data_ssd/data_sets/test_mlr32_18d/1527256858_150165/v01/mlr32_18d/1527256858_150165-ML_DATA-32B-O-FZ0.05-RIG_RND2.00000.tiff', # State Street
                '/data_ssd/data_sets/test_mlr32_18d/1527182802_096892/v02/mlr32_18d/1527182802_096892-ML_DATA-32B-O-FZ0.05-RIG_RND2.00000.tiff', # near plane"
                '/data_ssd/data_sets/test_mlr32_18d/1527182805_096892/v02/mlr32_18d/1527182805_096892-ML_DATA-32B-O-FZ0.05-RIG_RND2.00000.tiff', # medium plane"
                '/data_ssd/data_sets/test_mlr32_18d/1527182810_096892/v02/mlr32_18d/1527182810_096892-ML_DATA-32B-O-FZ0.05-RIG_RND2.00000.tiff', # far plane
                ]
    """
    # These images are made with large random offset
    '''
    test_corrs = [
                '/data_ssd/data_sets/test_only/1527258897_071435/v02/ml32/1527258897_071435-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257894_750165/v02/ml32/1527257894_750165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257406_950165/v02/ml32/1527257406_950165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257757_950165/v02/ml32/1527257757_950165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257370_950165/v02/ml32/1527257370_950165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257235_950165/v02/ml32/1527257235_950165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257235_350165/v02/ml32/1527257235_350165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527259003_271435/v02/ml32/1527259003_271435-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257787_950165/v02/ml32/1527257787_950165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257235_150165/v02/ml32/1527257235_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257235_750165/v02/ml32/1527257235_750165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527258936_671435/v02/ml32/1527258936_671435-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257244_350165/v02/ml32/1527257244_350165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                '/data_ssd/data_sets/test_only/1527257235_550165/v02/ml32/1527257235_550165-ML_DATA-32B-O-FZ0.05-MAIN.tiff',
                ]
    '''
    test_corrs = []
#1527257933_150165-ML_DATA-32B-O-FZ0.05-MAIN-RND2.00000.tiff  
#/home/eyesis/x3d_data/data_sets/test_mlr32_18a/1527257933_150165/v04/mlr32_18c/1527257933_150165-ML_DATA-32B-O-FZ0.05-MAIN.tiff

    test_sets = [
    "/data_ssd/lwir_sets/lwir_test2/1562390202_933097/v01/ml32", # andrey /empty
    "/data_ssd/lwir_sets/lwir_test2/1562390225_269784/v01/ml32", # andrey /empty
    "/data_ssd/lwir_sets/lwir_test2/1562390225_839538/v01/ml32", # andrey /empty
    "/data_ssd/lwir_sets/lwir_test2/1562390243_047919/v01/ml32", # 2 trees
    "/data_ssd/lwir_sets/lwir_test2/1562390251_025390/v01/ml32", # empty space
    "/data_ssd/lwir_sets/lwir_test2/1562390257_977146/v01/ml32", # first 3
    "/data_ssd/lwir_sets/lwir_test2/1562390260_370347/v01/ml32", # all 3
    "/data_ssd/lwir_sets/lwir_test2/1562390260_940102/v01/ml32", # all 3
    "/data_ssd/lwir_sets/lwir_test3/1562390402_254007/v01/ml32", # near moving car
    "/data_ssd/lwir_sets/lwir_test3/1562390407_382326/v01/ml32", # near moving car
    "/data_ssd/lwir_sets/lwir_test3/1562390409_661607/v01/ml32", # lena, 2 far moving cars
    "/data_ssd/lwir_sets/lwir_test3/1562390435_873048/v01/ml32", # 2 parked cars, lena
    "/data_ssd/lwir_sets/lwir_test3/1562390456_842237/v01/ml32", # near trees
    "/data_ssd/lwir_sets/lwir_test3/1562390460_261151/v01/ml32"] # near trees, olga

    #Parameters to generate neighbors data. Set radius to 0 to generate single-tile
    TEST_SAME_LENGTH_AS_TRAIN = False # True # make test to have same number of entries as train ones
    FIXED_TEST_LENGTH =  102 # None # put number of test scenes to output (used when making test only from few or single test file     
    FIXED_TRAIN_LENGTH = 409 # None # put number of test scenes to output (used when making test only from few or single test file     
    RADIUS = 2 # 5x5
    FRAC_NEIBS_VALID = 0.55# 8 #LWIR new
    MIN_NEIBS = (2 * RADIUS + 1) * (2 * RADIUS + 1) # All tiles valid == 9
    MIN_NEIBS = round (MIN_NEIBS * FRAC_NEIBS_VALID)
    VARIANCE_THRESHOLD =       1.2 # 0.4 # 1.5
    VARIANCE_SCALE_DISPARITY = 5.0 #Scale variance if average is above this
    NUM_TRAIN_SETS =           32# 16 # 8
    
    FGBGMODE_TESTS =            [4] # 0 - average, 1 - FG, 2 - BG, 3 - AUX
    FGBGMODE_TRAIN =            4 # 1 # 0 - average, 1 - FG, 2 - BG, 4 - FG/BG closest to AUX
    RND_AMPLITUDE_TEST =         0.5 # present corr2d rendered +/- this far from the GT
    RMS_MERGE_RATIO =           4.0 # fixing bug in exported data - merging FG/BG for near horizontal surfaces (3.0 < RMS_MERGE_RATIO <5.8)
    RND_AMPLIUDE_TRAIN_TILE =   0.5 # train with corr2d rendered +/- this far from the GT - independent for each tile component
    RND_AMPLIUDE_TRAIN_PLATE =  0.0 # train with corr2d rendered +/- this far from the GT - common for each (5x5) plate component
    RND_AMPLIUDE_TRAIN_TILEW =  2.0 # train with corr2d rendered +/- this far from the GT - independent for each tile component
    RND_AMPLIUDE_TRAIN_PLATEW = 0.0 # train with corr2d rendered +/- this far from the GT - common for each (5x5) plate component
    MAX_MAIN_OFFSET =           2.5 # do not use tile for training if MAIN camera (AUX for LWIR) differs more from GT
    MODEL_ML_DIR =             "ml32" # subdirectory with the ML disparity sweep files
    USE_SPLIT =                False # True,                # Select y single/multi-plane tiles (center only)
    KEEP_SPLIT =               False # When sel_split, keep only multi-plane tiles (false - only single-plane)

    
    if not topdir_train:
        NUM_TRAIN_SETS = 0
    if RADIUS == 0:
        BATCH_DISP_BINS = 50 # 1000 * 1
        BATCH_STR_BINS =  20 # 10
    elif RADIUS == 1:
        BATCH_DISP_BINS = 15 # 120 * 9
        BATCH_STR_BINS =  8
    else: # RADIUS = 2
        BATCH_DISP_BINS = 10 # 40 * 25
        BATCH_STR_BINS =  4

    train_filenameTFR = pathTFR+"/train"        
    test_filenameTFR =  pathTFR+"/test"
    
    
    ''' Prepare full image for testing '''
    
    for model_ml_path in test_sets:
        for fgbgmode_test in FGBGMODE_TESTS:
            writeTFRecordsFromImageSet(
                model_ml_path,     # model/version/ml_dir
                fgbgmode_test,     # 0, # expot_mode,    # 0 - GT average, 1 - GT FG, 2 - GT BG, 3 - AUX disparity
                RND_AMPLITUDE_TEST, # random_offset, # for modes 0..2 - add random offset of -random_offset to +random_offset, in mode 3 add random to  GT average if no AUX data
                pathTFR,           # TFR directory
                RMS_MERGE_RATIO)   # fixing bug - merging FG+BG for horizontal surfaces
    
    
#        disp_bins = 20,
#      str_bins=10)

#  corr2d, target_disparity, gt_ds = readTFRewcordsEpoch(train_filenameTFR)
#  print_time("Read %d tiles"%(corr2d.shape[0]))
#  exit (0)
    ex_data = ExploreData(
               topdir_train =         topdir_train,
               topdir_test =          topdir_test,
               ml_subdir =            MODEL_ML_DIR,
               ml_pattern =           ml_pattern,
               max_main_offset =      MAX_MAIN_OFFSET,
               latest_version_only =  LATEST_VERSION_ONLY,
               debug_level =          1, #3, #1, #3, ##0, #3,
               disparity_bins =      50, #100 #200, #1000,
               strength_bins =       50, #100
               disparity_min_drop =  -0.1,
               disparity_min_clip =  -0.1,
               disparity_max_drop =   8.0, #100.0,
               disparity_max_clip =   8.0, #100.0,
               strength_min_drop =    0.02, # 0.1,
               strength_min_clip =    0.02, # 0.1,
               strength_max_drop =    0.3,  # 1.0,
               strength_max_clip =    0.27, # 0.9,
               hist_sigma =           2.0,  # Blur log histogram
               hist_cutoff=           0.001, #  of maximal
               fgbg_mode =            FGBGMODE_TRAIN,  #  average, 1 - FG, 2 - BG (3 - AUX - not used here)
               rms_merge_ratio =      RMS_MERGE_RATIO,
               rnd_tile =             RND_AMPLIUDE_TRAIN_TILE, #  use corr2d rendered with target disparity this far shuffled from the GT
               rnd_plate =            RND_AMPLIUDE_TRAIN_PLATE, #  use corr2d rendered with target disparity this far shuffled from the GT
               radius =               RADIUS) 
  
    mytitle = "Disparity_Strength histogram"
    fig = plt.figure()
    fig.canvas.set_window_title(mytitle)
    fig.suptitle(mytitle)
    #  plt.imshow(lhist,vmin=-6,vmax=-2) # , vmin=0, vmax=.01)
    plt.imshow(ex_data.blurred_hist, vmin=0, vmax=.1 * ex_data.blurred_hist.max())#,vmin=-6,vmax=-2) # , vmin=0, vmax=.01)
    plt.colorbar(orientation='horizontal') # location='bottom')
    hist_to_batch = ex_data.assignBatchBins(
        disp_bins = BATCH_DISP_BINS,
        str_bins =  BATCH_STR_BINS)
    bb_display = hist_to_batch.copy()
    bb_display = ( 1+ (bb_display % 2) + 2 * ((bb_display % 20)//10)) * (hist_to_batch > 0) #).astype(float) 
    fig2 = plt.figure()
    fig2.canvas.set_window_title("Batch indices")
    fig2.suptitle("Batch index for each disparity/strength cell")
    plt.imshow(bb_display) #, vmin=0, vmax=.1 * ex_data.blurred_hist.max())#,vmin=-6,vmax=-2) # , vmin=0, vmax=.01)
    
    """ prepare test dataset """
    '''
    for test_corr in test_corrs:
        scene = os.path.basename(test_corr)[:17]
        scene_version= os.path.basename(os.path.dirname(os.path.dirname(test_corr)))
        fname =scene+'-'+scene_version 
        img_filenameTFR = os.path.join(pathTFR,'img',fname)
        print_time("Saving test image %s as tiles..."%(img_filenameTFR),end = " ")        
        writeTFRewcordsImageTiles(test_corr, img_filenameTFR)
        print_time("Done")        
        pass
    '''



    if (RADIUS > 0):
        disp_var_test,  num_neibs_test =  ex_data.exploreNeibs(ex_data.test_ds, RADIUS, VARIANCE_SCALE_DISPARITY)
        disp_var_train, num_neibs_train = ex_data.exploreNeibs(ex_data.train_ds, RADIUS, VARIANCE_SCALE_DISPARITY)
      
        # show varinace histogram
#      for var_thresh in [0.1, 1.0, 1.5, 2.0, 5.0]:
        for var_thresh in [VARIANCE_THRESHOLD]:
            ex_data.showVariance(
                rds_list =       [ex_data.train_ds, ex_data.test_ds],           # list of disparity/strength files, suchas training, testing 
                disp_var_list =  [disp_var_train,  disp_var_test],      # list of disparity variance files. Same shape(but last dim) as rds_list
                num_neibs_list = [num_neibs_train, num_neibs_test],    # list of number of tile neibs files. Same shape(but last dim) as rds_list
                variance_min =       0.0,
                variance_max =       var_thresh,
                neibs_min =          MIN_NEIBS)
            ex_data.showVariance(
                rds_list =       [ex_data.train_ds, ex_data.test_ds],           # list of disparity/strength files, suchas training, testing 
                disp_var_list =  [disp_var_train,  disp_var_test],      # list of disparity variance files. Same shape(but last dim) as rds_list
                num_neibs_list = [num_neibs_train, num_neibs_test],    # list of number of tile neibs files. Same shape(but last dim) as rds_list
                variance_min =       var_thresh,
                variance_max =       1000.0,
                neibs_min =          MIN_NEIBS)
            pass
        pass
      
    else:
        disp_var_test,  num_neibs_test =  None, None    
        disp_var_train, num_neibs_train = None, None    
  
    #Wrong way to get ML lists for LWIR mode - make it an error!
###    ml_list_train=ex_data.getMLList(ml_subdir, ex_data.files_train)
###    ml_list_test= ex_data.getMLList(ml_subdir, ex_data.files_test)
    ml_list_train= []
    ml_list_test=  []
    

    if FIXED_TEST_LENGTH is None:
        num_test_scenes = len([ex_data.files_test, ex_data.files_train][TEST_SAME_LENGTH_AS_TRAIN])    
    else:
        num_test_scenes = FIXED_TEST_LENGTH 
    
    
    if FIXED_TRAIN_LENGTH is None:    
        num_train_scenes = len(ex_data.files_train)
    else:
        num_train_scenes =  FIXED_TRAIN_LENGTH

    if RADIUS == 0 : # not used
        list_of_file_lists_train, num_batch_tiles_train = ex_data.makeBatchLists( # results are also saved to self.*
            data_ds =      ex_data.train_ds,
            data_gtaux =   ex_data.train_gtaux,
            disp_var =     disp_var_train,      # difference between maximal and minimal disparity for each scene, each tile
            disp_neibs =   num_neibs_train,     # number of valid tiles around each center tile (for 3x3 (radius = 1) - macximal is 9  
            min_var =      0.0,                 # Minimal tile variance to include
            max_var =      VARIANCE_THRESHOLD,  # Maximal tile variance to include
            scale_disp =   VARIANCE_SCALE_DISPARITY,
            min_neibs =    MIN_NEIBS,           # Minimal number of valid tiles to include
            use_split =    USE_SPLIT,           # Select y single/multi-plane tiles (center only)
            keep_split =   KEEP_SPLIT)          # When sel_split, keep only multi-plane tiles (false - only single-plane)
        pass

        for train_var in range (NUM_TRAIN_SETS):
            fpath =  train_filenameTFR+("%03d"%(train_var,))
            ex_data.writeTFRewcordsEpochLwir(
                fpath,
                sweep_files =        ex_data.train_sweep_files,
                sweep_disparities =  ex_data.train_sweep_disparities,
                files_list =         ex_data.files_train,
                set_ds =             ex_data.train_ds,
                radius =             ex_data.radius,
                rnd_tile =           ex_data.rnd_tile,
                rnd_plate =          ex_data.rnd_plate)
          
        list_of_file_lists_test, num_batch_tiles_test = ex_data.makeBatchLists( # results are also saved to self.*
            data_ds =      ex_data.test_ds,
            data_gtaux =   ex_data.test_gtaux,
            disp_var =     disp_var_test,      # difference between maximal and minimal disparity for each scene, each tile
            disp_neibs =   num_neibs_test,     # number of valid tiles around each center tile (for 3x3 (radius = 1) - macximal is 9  
            min_var =      0.0,                # Minimal tile variance to include
            max_var =      VARIANCE_THRESHOLD, # Maximal tile variance to include
            min_neibs =    MIN_NEIBS,          # Minimal number of valid tiles to include
            use_split =    USE_SPLIT,           # Select y single/multi-plane tiles (center only)
            keep_split =   KEEP_SPLIT)          # When sel_split, keep only multi-plane tiles (false - only single-plane)
        
        fpath =  test_filenameTFR # +("-%03d"%(train_var,))
        
        ex_data.writeTFRewcordsEpochLwir(
            fpath,
            sweep_files =        ex_data.test_sweep_files,
            sweep_disparities =  ex_data.test_sweep_disparities,
            files_list =         ex_data.files_test,
            set_ds =             ex_data.test_ds,
            radius =             ex_data.radius,
            num_scenes =         num_test_scenes,
            rnd_tile =           ex_data.rnd_tile,
            rnd_plate =          ex_data.rnd_plate)
    else: # RADIUS > 0
    # test
        list_of_file_lists_test, num_batch_tiles_test = ex_data.makeBatchLists( # results are also saved to self.*
            data_ds =      ex_data.test_ds,
            data_gtaux =   ex_data.test_gtaux,
            disp_var =     disp_var_test,       # difference between maximal and minimal disparity for each scene, each tile
            disp_neibs =   num_neibs_test,      # number of valid tiles around each center tile (for 3x3 (radius = 1) - macximal is 9  
            min_var =      0.0,                 # Minimal tile variance to include
            max_var =      1000.0,              # Maximal tile variance to include
            min_neibs =    MIN_NEIBS,           # Minimal number of valid tiles to include
            use_split =    USE_SPLIT,           # Select y single/multi-plane tiles (center only)
            keep_split =   KEEP_SPLIT,          # When sel_split, keep only multi-plane tiles (false - only single-plane)
            rnd_tile =     RND_AMPLIUDE_TRAIN_TILE, ## disparity random for each tile - narrow
            rnd_plate =    RND_AMPLIUDE_TRAIN_PLATE)## disparity random for each plate (now 25 tiles) - narrow
            
        
        num_le_test =  num_batch_tiles_test.sum()
        print("Number of <= %f disparity variance tiles: %d (est)"%(VARIANCE_THRESHOLD, num_le_test))

        fpath =  test_filenameTFR +("TEST_R%d"%(RADIUS))
        # next line: 
        ex_data.writeTFRewcordsEpochLwir(
            fpath,
            sweep_files =        ex_data.test_sweep_files,
            sweep_disparities =  ex_data.test_sweep_disparities,
            files_list =         ex_data.files_test,
            set_ds =             ex_data.test_ds,
            radius =             ex_data.radius,
            num_scenes =         num_test_scenes,
            rnd_tile =           ex_data.rnd_tile,
            rnd_plate =          ex_data.rnd_plate)

        list_of_file_lists_test, num_batch_tiles_test = ex_data.makeBatchLists( # results are also saved to self.*
            data_ds =      ex_data.test_ds,
            data_gtaux =   ex_data.test_gtaux,
            disp_var =     disp_var_test,       # difference between maximal and minimal disparity for each scene, each tile
            disp_neibs =   num_neibs_test,      # number of valid tiles around each center tile (for 3x3 (radius = 1) - macximal is 9  
            min_var =      0.0,                 # Minimal tile variance to include
            max_var =      1000.0,              # Maximal tile variance to include
            min_neibs =    MIN_NEIBS,           # Minimal number of valid tiles to include
            use_split =    USE_SPLIT,           # Select y single/multi-plane tiles (center only)
            keep_split =   KEEP_SPLIT,          # When sel_split, keep only multi-plane tiles (false - only single-plane)
            rnd_tile =     RND_AMPLIUDE_TRAIN_TILEW, ## disparity random for each tile - wide
            rnd_plate =    RND_AMPLIUDE_TRAIN_PLATEW)## disparity random for each plate (now 25 tiles) - wide
        
        num_gt_test =  num_batch_tiles_test.sum()
        high_fract_test = 1.0 * num_gt_test / (num_le_test + num_gt_test)
        print("Number of > %f disparity variance tiles: %d, fraction = %f (test)"%(VARIANCE_THRESHOLD, num_gt_test, high_fract_test))
        fpath =  test_filenameTFR +("TEST_R%d"%(RADIUS,))

        ex_data.writeTFRewcordsEpochLwir(
            fpath,
            sweep_files =        ex_data.test_sweep_files,
            sweep_disparities =  ex_data.test_sweep_disparities,
            files_list =         ex_data.files_test,
            set_ds =             ex_data.test_ds,
            radius =             ex_data.radius,
            num_scenes =         num_test_scenes,
            rnd_tile =           ex_data.rnd_tile,
            rnd_plate =          ex_data.rnd_plate)

        #fake
        if NUM_TRAIN_SETS > 0:
            list_of_file_lists_fake, num_batch_tiles_fake = ex_data.makeBatchLists( # results are also saved to self.*
                data_ds =      ex_data.train_ds,
                data_gtaux =   ex_data.train_gtaux,
                disp_var =     disp_var_train,      # difference between maximal and minimal disparity for each scene, each tile
                disp_neibs =   num_neibs_train,     # number of valid tiles around each center tile (for 3x3 (radius = 1) - macximal is 9  
                min_var =      0.0,                 # Minimal tile variance to include
                max_var =      1000.0,              # Maximal tile variance to include
                min_neibs =    MIN_NEIBS,           # Minimal number of valid tiles to include
                use_split =    USE_SPLIT,           # Select y single/multi-plane tiles (center only)
                keep_split =   KEEP_SPLIT,          # When sel_split, keep only multi-plane tiles (false - only single-plane)
                rnd_tile =     RND_AMPLIUDE_TRAIN_TILE, ## disparity random for each tile - narrow
                rnd_plate =    RND_AMPLIUDE_TRAIN_PLATE)## disparity random for each plate (now 25 tiles) - narrow
            
            num_le_fake = num_batch_tiles_fake.sum()
            print("Number of <= %f disparity variance tiles: %d (test)"%(VARIANCE_THRESHOLD, num_le_fake))
    
            fpath =  test_filenameTFR +("FAKE_R%d"%(RADIUS,))
            
            ex_data.writeTFRewcordsEpochLwir(
                fpath,
                sweep_files =        ex_data.train_sweep_files,
                sweep_disparities =  ex_data.train_sweep_disparities,
                files_list =         ex_data.files_train,
                set_ds =             ex_data.train_ds,
                radius =             ex_data.radius,
                num_scenes =         num_test_scenes,
                rnd_tile =           ex_data.rnd_tile,
                rnd_plate =          ex_data.rnd_plate)
    
            list_of_file_lists_fake, num_batch_tiles_fake = ex_data.makeBatchLists( # results are also saved to self.*
                data_ds =      ex_data.train_ds,
                data_gtaux =   ex_data.train_gtaux,
                disp_var =     disp_var_train,      # difference between maximal and minimal disparity for each scene, each tile
                disp_neibs =   num_neibs_train,     # number of valid tiles around each center tile (for 3x3 (radius = 1) - macximal is 9  
                min_var =      0.0,                 # Minimal tile variance to include
                max_var =      1000.0,              # Maximal tile variance to include
                min_neibs =    MIN_NEIBS,           # Minimal number of valid tiles to include
                use_split =    USE_SPLIT,           # Select y single/multi-plane tiles (center only)
                keep_split =   KEEP_SPLIT,          # When sel_split, keep only multi-plane tiles (false - only single-plane)
                rnd_tile =     RND_AMPLIUDE_TRAIN_TILEW, ## disparity random for each tile - wide
                rnd_plate =    RND_AMPLIUDE_TRAIN_PLATEW)## disparity random for each plate (now 25 tiles) - wide
            
            num_gt_fake =  num_batch_tiles_fake.sum()
            high_fract_fake = 1.0 * num_gt_fake / (num_le_fake + num_gt_fake)
            print("Number of > %f disparity variance tiles: %d, fraction = %f (test)"%(VARIANCE_THRESHOLD, num_gt_fake, high_fract_fake))
            fpath =  test_filenameTFR +("FAKE_R%d"%(RADIUS,))

            ex_data.writeTFRewcordsEpochLwir(
                fpath,
                sweep_files =        ex_data.train_sweep_files,
                sweep_disparities =  ex_data.train_sweep_disparities,
                files_list =         ex_data.files_train,
                set_ds =             ex_data.train_ds,
                radius =             ex_data.radius,
                num_scenes =         num_test_scenes,
                rnd_tile =           ex_data.rnd_tile,
                rnd_plate =          ex_data.rnd_plate)
        
        # train 32  sets
        for train_var in range (NUM_TRAIN_SETS): # Recalculate list for each file - slower, but will alternate lvar/hvar
            
            list_of_file_lists_train, num_batch_tiles_train = ex_data.makeBatchLists( # results are also saved to self.*
                data_ds =      ex_data.train_ds,
                data_gtaux =   ex_data.train_gtaux,
                disp_var =     disp_var_train,      # difference between maximal and minimal disparity for each scene, each tile
                disp_neibs =   num_neibs_train,     # number of valid tiles around each center tile (for 3x3 (radius = 1) - macximal is 9  
                min_var =      0.0,                 # Minimal tile variance to include
                max_var =      1000.0,              # Maximal tile variance to include
                min_neibs =    MIN_NEIBS,           # Minimal number of valid tiles to include
                use_split =    USE_SPLIT,           # Select y single/multi-plane tiles (center only)
                keep_split =   KEEP_SPLIT,          # When sel_split, keep only multi-plane tiles (false - only single-plane)
                rnd_tile =     RND_AMPLIUDE_TRAIN_TILE, ## disparity random for each tile - narrow
                rnd_plate =    RND_AMPLIUDE_TRAIN_PLATE)## disparity random for each plate (now 25 tiles) - narrow
                
            num_le_train = num_batch_tiles_train.sum()
            print("Number of <= %f disparity variance tiles: %d (train)"%(VARIANCE_THRESHOLD, num_le_train))
            fpath =  train_filenameTFR+("%03d_R%d"%(train_var,RADIUS,))

            ex_data.writeTFRewcordsEpochLwir(
                fpath,
                sweep_files =        ex_data.train_sweep_files,
                sweep_disparities =  ex_data.train_sweep_disparities,
                files_list =         ex_data.files_train,
                set_ds =             ex_data.train_ds,
                radius =             ex_data.radius,
                num_scenes =         num_train_scenes, # len(ex_data.files_train),
                rnd_tile =           ex_data.rnd_tile,
                rnd_plate =          ex_data.rnd_plate)

            list_of_file_lists_train, num_batch_tiles_train = ex_data.makeBatchLists( # results are also saved to self.*
                data_ds =      ex_data.train_ds,
                data_gtaux =   ex_data.train_gtaux,
                disp_var =     disp_var_train,      # difference between maximal and minimal disparity for each scene, each tile
                disp_neibs =   num_neibs_train,     # number of valid tiles around each center tile (for 3x3 (radius = 1) - macximal is 9  
                min_var =      0.0,                 # Minimal tile variance to include
                max_var =      1000.0,              # Maximal tile variance to include
                min_neibs =    MIN_NEIBS,           # Minimal number of valid tiles to include
                use_split =    USE_SPLIT,           # Select y single/multi-plane tiles (center only)
                keep_split =   KEEP_SPLIT,          # When sel_split, keep only multi-plane tiles (false - only single-plane)
                rnd_tile =     RND_AMPLIUDE_TRAIN_TILEW, ## disparity random for each tile - wide
                rnd_plate =    RND_AMPLIUDE_TRAIN_PLATEW)## disparity random for each plate (now 25 tiles) - wide

            num_gt_train = num_batch_tiles_train.sum()
            high_fract_train = 1.0 * num_gt_train / (num_le_train + num_gt_train)
            print("Number of > %f disparity variance tiles: %d, fraction = %f (train)"%(VARIANCE_THRESHOLD, num_gt_train, high_fract_train))
            fpath =  (train_filenameTFR+("%03d_R%d"%(train_var,RADIUS)))

            ex_data.writeTFRewcordsEpochLwir(
                fpath,
                sweep_files =        ex_data.train_sweep_files,
                sweep_disparities =  ex_data.train_sweep_disparities,
                files_list =         ex_data.files_train,
                set_ds =             ex_data.train_ds,
                radius =             ex_data.radius,
                num_scenes =         num_train_scenes, # len(ex_data.files_train),
                rnd_tile =           ex_data.rnd_tile,
                rnd_plate =          ex_data.rnd_plate)
            
    plt.show()
    """              
    scene = os.path.basename(test_corr)[:17]
    scene_version= os.path.basename(os.path.dirname(os.path.dirname(test_corr)))
    fname =scene+'-'+scene_version 
    img_filenameTFR = os.path.join(pathTFR,'img',fname)
    print_time("Saving test image %s as tiles..."%(img_filenameTFR),end = " ")        
    writeTFRewcordsImageTiles(test_corr, img_filenameTFR)
    print_time("Done")        
    pass
    """
    pass