#!/usr/bin/python
# -*- coding: utf-8 -*-

# 2018-05-25 MW
# 2 - contact detection
#     local thresholding for the refinement of the list
#     contact orientation

import tifffile, numpy

import spam.label.contacts as con

folder = "monotonic/images/"
folderOutput = "monotonic/results/"

# input
filenames    = ["triax.-1.eps=0.spheres_image_gaussian=08_noise=03",
                #"triax.0.eps=-0.0025.spheres_image_gaussian=08_noise=03",
                #"triax.1.eps=-0.005.spheres_image_gaussian=08_noise=03",
                #"triax.2.eps=-0.01.spheres_image_gaussian=08_noise=03",
                #"triax.3.eps=-0.02.spheres_image_gaussian=08_noise=03",
                #"triax.4.eps=-0.03.spheres_image_gaussian=08_noise=03",
                #"triax.5.eps=-0.04.spheres_image_gaussian=08_noise=03",
                #"triax.6.eps=-0.05.spheres_image_gaussian=08_noise=03",
                #"triax.7.eps=-0.06.spheres_image_gaussian=08_noise=03",
                #"triax.8.eps=-0.07.spheres_image_gaussian=08_noise=03",
                #"triax.9.eps=-0.08.spheres_image_gaussian=08_noise=03",
                #"triax.10.eps=-0.09.spheres_image_gaussian=08_noise=03",
                #"triax.11.eps=-0.1.spheres_image_gaussian=08_noise=03",
                #"triax.12.eps=-50124.6.spheres_image_gaussian=08_noise=03",
                ]


NumOfThreads = 2
# choose a local threshold for dealing with the over-detection of contacts
localThreshold = 180

pixelSizeMicrons = 15. #mum
radiusThreshMicrons = 50 #mum
radiusThresh = radiusThreshMicrons/pixelSizeMicrons

for filename in filenames:
    ##############

    volLab  = tifffile.imread(folder+filename+"-lab.tif")
    volGrey = tifffile.imread(folder+filename+".tif")

    ##############

    # 1 - contact List
    print "\tCreating the contact list\n"
    contactVolume, Z, contactsTable, contactingLabels = con.labelledContacts(volLab)

    numpy.savetxt(folderOutput+filename + "-contact_table.txt", contactsTable)
    numpy.savetxt(folderOutput+filename + "-contact_list.txt", contactingLabels)

    # 2 - refine contact list
    print "\tRefining the contact list with a threshold of ", localThreshold, "\n"
    contactListRefined = con.localDetectionAssembly(volLab, volGrey, contactingLabels, localThreshold, radiusThresh=radiusThresh, NumberOfThreads=NumOfThreads)
    numpy.savetxt(folderOutput+filename + "-contact_list_local=%03i.txt"%(localThreshold), contactListRefined,fmt='%i')

    # 3 - contact orientations
    print "\tDetermining contact orientations with the random walker\n"
    contactOrientations = con.contactOrientationsAssembly(volLab, volGrey, contactListRefined, NumberOfThreads=NumOfThreads)
    numpy.savetxt(folderOutput+filename + "-local=%03i_orientations_rw.txt"%(localThreshold), contactOrientations,fmt=('%i %i %f %f %f %i'))
