"""
This python script automate the sensivity analysis on m/n parameter.
It read-write parameter files from a folder where your raster are, you have to adapt the path to this folder.
It then call LSDTT via subprocess (you also have to adapt the path to LSDTT binary).
This script is part of the supplementary material for the paper *insert title and the rest*
B.G. - 2018
"""
import os # os deals with all the directory/path management
import subprocess # Subprocess calls the other codes
import multiprocessing as mp # multiprocess allows to speed-up code execution by running several analysis at the same time

# Global variables to the chi_mapping_tool driver directory
path_to_chi_mapping_tools = "/home/s1675537/PhD/DataStoreBoris/dev_LSD/LSDTT_Development/driver_functions_MuddChi2014/"
# Global read path to the test data
read_path = "/home/s1675537/PhD/LSDTopoData/knickpoint/test_location_paper/Smugglers_SC/"
write_path = "/home/s1675537/PhD/LSDTopoData/knickpoint/test_location_paper/Smugglers_SC/sensitivity_test_movern/"


##### Now defining the functions (main code at the end of the file)

def write_param_file(movern = 0.1): 
    """
    This function generates a parameter file for one or several parameters to adapt.
    Return the path+ name of the parameter file
    B.G. - 2018
    """

    out_directory = "%smovern_%s/" %(write_path,movern)
    if not os.path.isdir(out_directory):
        os.makedirs(out_directory)  

    file_object  = open(out_directory+"%s.param" %(movern), "w")
    file_object.write("""# This is a parameter file for the chi_mapping_tool
# One day there will be documentation. 
# These are parameters for the file i/o
# IMPORTANT: You MUST make the write directory: the code will not work if it doens't exist.
read path: %s
write path: %smovern_%s/
read fname: smugglers
write fname: smugglers
channel heads fname: smugglers_Psources
# Parameter for filling the DEM
min_slope_for_fill: 0.0001
remove_seas: true
raster_is_filled: false
test_drainage_boundaries: true

# Parameters for selecting channels and basins
threshold_contributing_pixels: 0
minimum_elevation: 0
minimum_basin_size_pixels: 20000
maximum_basin_size_pixels: 10000000000
only_take_largest_basin: true
print_basin_raster: true

force_skip_knickpoint_analysis: 1
force_n_iteration_knickpoint_analysis: 50
ksn_knickpoint_analysis: true
MZS_threshold: 0.01
kp_node_combining: 25
window_stepped_kp_detection: 150
std_dev_coeff_stepped_kp: 6.5

sigma: 5
maximum_segment_length: 100000
n_nodes_to_visit: 20
target_nodes: 50

# Parameters for chi analysis
A_0: 1
m_over_n: %s
threshold_pixels_for_chi: 0

write_hillshade: true


#end of file"""%(read_path,write_path,movern,movern))
    file_object.close()
    return out_directory, "%s.param" %(movern)

def run_analysis(movern):
    """
    This function run the analysis  and call the file writing
    B.G. - 2018
    """
    direc,param_file = write_param_file(movern = movern)
    subprocess.call(path_to_chi_mapping_tools + "chi_mapping_tool.exe %s %s"%(direc, param_file), shell = True)

if(__name__ == "__main__"):

    # Main code:

    processes = []# Ignore that
    n_cores = 4 # Number of cpu core to use (ie how many analyses do you wish to run at the same time)
    pool = mp.Pool(processes = 4) # prepare the multiprocessing queue
    
    # Looping through all the different value of theta
    for theta in range(1,20):
        movern = format(theta*0.05, '.2f') # getting the value and formatting it (we don't want the folder to be named 0.050000000 as it can happen sometimes)
        processes.append(pool.apply_async(run_analysis, args=(movern,))) # Call the function in the multiprocess queue

    # Clean way to wait and finish the multiprocessing (it makes sure that no ghost or hidden processes remains)
    pool.close()
    pool.join()

    print("I am done with the analysis.")
