def max_distance(celllist):

    cell_head = celllist[0]
    cell_tail = celllist[len(celllist) - 1]
    [y1, x1] = mfc.get_coordinate(cell_head, ncol)
    [y2, x2] = mfc.get_coordinate(cell_tail, ncol)

    A = y1 - y2
    B = x2 - x1
    C = x1 * y2 - y1 * x2

    coordinates = map(mfc.get_coordinate, celllist,
                      list(np.repeat(ncol, len(celllist))))
    coordinates = np.array(coordinates)
    X = list(coordinates[:, 1])
    Y = list(coordinates[:, 0])

    ds = map(point_to_line_distance, list(np.repeat(A, len(celllist))),
             list(np.repeat(B, len(celllist))),
             list(np.repeat(C, len(celllist))), X, Y)

    max_dis = max(ds)

    mid = ds.index(max_dis)

    return [max_dis, mid]
def surrounding_OneFrame(Input_MoleParentFolder, Output_moleParentFolder, Output_plotParentFolder, GroupNum, FrameNum, backbone_range = 2, close = False):
	GroupNum = int(GroupNum)
	FrameNum = int(FrameNum)
	GroupFolder = mfc.get_grouppath(GroupNum, Input_MoleParentFolder)

	
	grayData_array = fi.get_grayData_frominf(GroupNum, FrameNum)
	display_array = copy.deepcopy(grayData_array)

	molecule_filenames = mfc.get_names_setframe(GroupFolder, FrameNum)
	molecule_amount = len(molecule_filenames)
	start_cells = []
	
	if(molecule_amount):
		for molecule_filename in molecule_filenames:
			mole_start_cell = surrounding_OneMolecule_forframe(display_array, Input_MoleParentFolder, Output_moleParentFolder, Output_plotParentFolder, GroupNum, FrameNum, 0, backbone_range, close, molecule_filename)
			start_cells.append(mole_start_cell)
		print "end of frame!"

		plt.figure(FrameNum, figsize=(16, 12), dpi = 100)
    		mergeplot = plt.imshow(display_array)
	    	mergeplot.set_cmap(colormap)
    		plt.colorbar()
		for ind in range(0, molecule_amount):
			mole_start_position = mfc.get_coordinate(start_cells[ind], ncol)
			text_position = [mole_start_position[0]-15, mole_start_position[1]]
			text = molecule_filenames[ind].split(".")[0].split("e")[2]
			plt.text(text_position[1], text_position[0], text, color = "yellow", size = 'medium',weight = 400)
    		mergeplot.set_clim([np.min(display_array), image_max])
	else:
		plt.figure(1,figsize=(16, 12), dpi = 100)
		mergeplot = plt.imshow(display_array)
	    	mergeplot.set_cmap(colormap)
    		plt.colorbar()
		mergeplot.set_clim([np.min(display_array), image_max])

	GroupName = "group1-" + str(GroupNum) + "-inca34-outputs/"
	FrameName = "frame" + str(FrameNum)
	output_groupfolder = os.path.join(Output_moleParentFolder, GroupName)
	output_framefolder = os.path.join(output_groupfolder, FrameName)
	
	if(not os.path.exists(output_framefolder)):
		os.mkdir(output_framefolder)
	os.chdir(output_framefolder)

	framename_png = "frame" + str(FrameNum) + ".png"
	plt.savefig(framename_png)
	output_groupfolder_plot = os.path.join(Output_plotParentFolder, GroupName)
	output_framefolder_plot = os.path.join(output_groupfolder_plot, FrameName)
	if(not os.path.exists(output_framefolder_plot)):
		os.mkdir(output_framefolder_plot)
	
	framename_png_plot = framename_png
	shutil.copyfile(os.path.join(output_framefolder,framename_png),os.path.join(output_framefolder_plot,framename_png_plot))
	plt.close()
#	plt.show()

	return molecule_amount
def target_pixel(origin_cellnum, vertical_dis = 0, horizontal_dis = 0):
	origin_position = mfc.get_coordinate(origin_cellnum, ncol)
	inframe = 1
	target_position = [origin_position[0] + vertical_dis, origin_position[1] + horizontal_dis]
	target_cellnum = target_position[0]*ncol + target_position[1]
	
	if (target_position[0] < 0) or (target_position[0] >= nrow) or (target_position[1] < 0) or (target_position[1] >= ncol):
		inframe = 0
	return [target_cellnum, inframe]
def surrounding_intensity_circle(CellNumList, grayData_array, grayData_surround, backbone_range = 2, surround_range = 1, close = False):
	
	surrounding_intensity_circle = []
	surrounding_circles = surrounding_circle(CellNumList, backbone_range, surround_range, close)
	
	for pixel in surrounding_circles:
		target_position = list(mfc.get_coordinate(pixel, ncol))
		surrounding_intensity_circle.append(get_pixel_intensity(pixel, grayData_array))
		grayData_surround[target_position[0], target_position[1]] = mask
		
	return surrounding_intensity_circle #, surrounding_origin
def angle_list(turning_knots_cellnums):

    if len(turning_knots_cellnums) == 2:
        cos_list = [1]
        sin_list = [0]
    else:
        cos_list = []
        sin_list = []
        for i in range(0, len(turning_knots_cellnums) - 2):
            [y1, x1] = mfc.get_coordinate(turning_knots_cellnums[i], ncol)
            [y2, x2] = mfc.get_coordinate(turning_knots_cellnums[i + 1], ncol)
            [y3, x3] = mfc.get_coordinate(turning_knots_cellnums[i + 2], ncol)

            vector1 = [x2 - x1, y2 - y1]
            vector2 = [x3 - x2, y3 - y2]

            cos_list.append(cosine_distance(vector1, vector2))
            sin_list.append(sine_distance(vector1, vector2))
    theta_list = map(measure_angle, sin_list, cos_list)
    return theta_list
def angle_list(turning_knots_cellnums):
	
	if len(turning_knots_cellnums) == 2:
		cos_list = [1]
		sin_list = [0]
	else:
		cos_list = []
		sin_list = []
		for i in range(0, len(turning_knots_cellnums) - 2):
			[y1, x1] = mfc.get_coordinate(turning_knots_cellnums[i], ncol)
			[y2, x2] = mfc.get_coordinate(turning_knots_cellnums[i + 1], ncol)
			[y3, x3] = mfc.get_coordinate(turning_knots_cellnums[i + 2], ncol)
	
			vector1 = [x2-x1, y2-y1]
			vector2 = [x3-x2, y3-y2]
	
			cos_list.append(cosine_distance(vector1, vector2))
			sin_list.append(sine_distance(vector1, vector2))
	theta_list = map(measure_angle, sin_list, cos_list)
	return theta_list
def target_pixel(origin_cellnum, vertical_dis=0, horizontal_dis=0):
    origin_position = mfc.get_coordinate(origin_cellnum, ncol)
    inframe = 1
    target_position = [
        origin_position[0] + vertical_dis, origin_position[1] + horizontal_dis
    ]
    target_cellnum = target_position[0] * ncol + target_position[1]

    if (target_position[0] < 0) or (target_position[0] >= nrow) or (
            target_position[1] < 0) or (target_position[1] >= ncol):
        inframe = 0
    return [target_cellnum, inframe]
def max_distance(celllist):

	cell_head = celllist[0]
	cell_tail = celllist[len(celllist) - 1]
	[y1, x1] = mfc.get_coordinate(cell_head, ncol)
	[y2, x2] = mfc.get_coordinate(cell_tail, ncol)

	A = y1-y2
	B = x2-x1
	C = x1*y2 - y1*x2

	coordinates = map(mfc.get_coordinate, celllist, list(np.repeat(ncol,len(celllist))))
	coordinates = np.array(coordinates)
	X = list(coordinates[:,1])
	Y = list(coordinates[:,0])
	
	ds = map(point_to_line_distance, list(np.repeat(A,len(celllist))),list(np.repeat(B,len(celllist))), list(np.repeat(C,len(celllist))), X, Y)

	max_dis = max(ds)
	
	mid = ds.index(max_dis)

	return [max_dis, mid]	
def surrounding_intensity_circle(CellNumList,
                                 grayData_array,
                                 grayData_surround,
                                 backbone_range=2,
                                 surround_range=1,
                                 close=False):

    surrounding_intensity_circle = []
    surrounding_circles = surrounding_circle(CellNumList, backbone_range,
                                             surround_range, close)

    for pixel in surrounding_circles:
        target_position = list(mfc.get_coordinate(pixel, ncol))
        surrounding_intensity_circle.append(
            get_pixel_intensity(pixel, grayData_array))
        grayData_surround[target_position[0], target_position[1]] = mask

    return surrounding_intensity_circle  #, surrounding_origin
def get_pixel_intensity(target_cellnum, grayData_array):
	target_position = list(mfc.get_coordinate(target_cellnum, ncol))
	target_intensity = grayData_array[target_position[0], target_position[1]]
	return target_intensity
def surrounding_OneMolecule(Input_MoleParentFolder, Output_moleParentFolder, Output_plotParentFolder, GroupNum, FrameNum, MoleculeNum, select_region = [-1,-1], backbone_range = 2, close = False):

	GroupNum = int(GroupNum)
	FrameNum = int(FrameNum) 
	MoleculeNum = int(MoleculeNum)
	
	### data input
	grayData_array = fi.get_grayData_frominf(GroupNum, FrameNum)
	display_array1 = copy.deepcopy(grayData_array)
	display_array2 = copy.deepcopy(grayData_array)
	display_array3 = copy.deepcopy(grayData_array)

	fileContents = mfc.read_molecule_files_frominf(Input_MoleParentFolder, GroupNum, MoleculeNum)
	inframe = mfc.find_mole_setframe(fileContents, FrameNum)
	if(not(inframe)):
		print "the molecule is not in this frame! "
		exit(1)
	
	molecule_contents_setframe = mfc.get_content_setframe(fileContents, FrameNum)

	CellNumList_setframe = mfc.get_CellNumbers(molecule_contents_setframe)
	
	heads, tails = mfc.boundary_x(ncol, CellNumList_setframe)
	x_min = mfc.get_coordinate(heads[0],ncol)[1]
	x_max = mfc.get_coordinate(tails[0],ncol)[1]

	if(select_region[0] == -1): select_region[0] = x_min
	if(select_region[1] == -1): select_region[1] = x_max 
	

	CellNumList_setframe_region = []
	for cellnum in CellNumList_setframe:
		inregion = mfc.find_cell_inregion_x(cellnum, select_region, ncol)
		if(inregion):
			CellNumList_setframe_region.append(cellnum)
	
	if(len(CellNumList_setframe) != 0):
		### surrounding intensity acquisition
		surrounding_intensity_circle_1 = surrounding_intensity_circle(CellNumList_setframe_region, grayData_array, display_array1, 2, 1, close)
		surrounding_intensity_circle_2 = surrounding_intensity_circle(CellNumList_setframe_region, grayData_array, display_array2, 2, 2, close)
		surrounding_intensity_circle_3 = surrounding_intensity_circle(CellNumList_setframe_region, grayData_array, display_array3, 2, 3, close)
		
		surrounding_coordinate_1 = surrounding_circle(CellNumList_setframe_region, 2, 1, close)
		surrounding_coordinate_2 = surrounding_circle(CellNumList_setframe_region, 2, 2, close)
		surrounding_coordinate_3 = surrounding_circle(CellNumList_setframe_region, 2, 3, close)

		length = len(surrounding_intensity_circle_3)
		surrounding = np.zeros((length, 6), dtype = int)
		surrounding[0:(len(surrounding_intensity_circle_1)),0] = surrounding_intensity_circle_1
		surrounding[0:(len(surrounding_intensity_circle_2)),1] = surrounding_intensity_circle_2
		surrounding[0:(len(surrounding_intensity_circle_3)),2] = surrounding_intensity_circle_3
		surrounding[0:(len(surrounding_coordinate_1)),3] = surrounding_coordinate_1
		surrounding[0:(len(surrounding_coordinate_2)),4] = surrounding_coordinate_2
		surrounding[0:(len(surrounding_coordinate_3)),5] = surrounding_coordinate_3
	
		### data output
		GroupName = "group1-" + str(GroupNum) + "-inca34-outputs/"
		FrameName = "frame" + str(FrameNum)
		output_groupfolder = os.path.join(Output_moleParentFolder, GroupName)

		## for storing data
		if(not(os.path.exists(output_groupfolder))):
			os.makedirs(output_groupfolder)
		os.chdir(output_groupfolder)
	
		filename = "molecule" + str(MoleculeNum) + "_frame" + str(FrameNum) + ".txt"
		fileid = open(filename, "w")
		fileid.write(" ".join(["intensity1", "intensity2", "intensity3", "coordinate1", "coordinate2", "coordinate3", "\n"]))
		for line in range(0, length):
			line_str = map(str, surrounding[line, :])
			line_str.append("\n")
			fileid.write(" ".join(line_str))
		fileid.close()
		
		print "group", GroupNum, "_frame", FrameNum, "_molecule", MoleculeNum, ": surrounding file created!"
	
		## plotting the frame
		mole_start_position = mfc.get_coordinate(CellNumList_setframe[0],ncol)
		text_position = [mole_start_position[0]-15, mole_start_position[1]]
		text = "mole_" + str(MoleculeNum)
		
		plt.figure(FrameNum, figsize=(16, 12), dpi = 100)
    		mergeplot = plt.imshow(display_array1)
    		mergeplot.set_cmap(colormap)
		plt.text(text_position[1], text_position[0], text, color = "yellow", size = 'medium', weight = 400)
    		plt.colorbar()
    		mergeplot.set_clim([np.min(display_array3), image_max])
	
		framename_pdf = "molecule" + str(MoleculeNum) + "_frame" + str(FrameNum) + ".pdf"
		framename_png = "molecule" + str(MoleculeNum) + "_frame" + str(FrameNum) + ".png"
		plt.savefig(framename_pdf)
		plt.savefig(framename_png)
#		plt.show()
		plt.close()


		## save plots to another folder
		output_groupfolder_plot = os.path.join(Output_plotParentFolder, GroupName)
		if(not(os.path.exists(output_groupfolder_plot))):
			os.makedirs(output_groupfolder_plot)
		framename_pdf_plot = framename_pdf
		framename_png_plot = framename_png
		shutil.copyfile(os.path.join(output_groupfolder,framename_pdf),os.path.join(output_groupfolder_plot,framename_pdf_plot))
		shutil.copyfile(os.path.join(output_groupfolder,framename_png),os.path.join(output_groupfolder_plot,framename_png_plot))
		os.remove(os.path.join(output_groupfolder,framename_pdf))
		os.remove(os.path.join(output_groupfolder,framename_png))


	else:
		print("selected region wrong! no pixel of the molecule in this region..")
def get_pixel_intensity(target_cellnum, grayData_array):
    target_position = list(mfc.get_coordinate(target_cellnum, ncol))
    target_intensity = grayData_array[target_position[0], target_position[1]]
    return target_intensity
def surrounding_OneFrame(Input_MoleParentFolder,
                         Output_moleParentFolder,
                         Output_plotParentFolder,
                         GroupNum,
                         FrameNum,
                         backbone_range=2,
                         close=False):
    GroupNum = int(GroupNum)
    FrameNum = int(FrameNum)
    GroupFolder = mfc.get_grouppath(GroupNum, Input_MoleParentFolder)

    grayData_array = fi.get_grayData_frominf(GroupNum, FrameNum)
    display_array = copy.deepcopy(grayData_array)

    molecule_filenames = mfc.get_names_setframe(GroupFolder, FrameNum)
    molecule_amount = len(molecule_filenames)
    start_cells = []

    if (molecule_amount):
        for molecule_filename in molecule_filenames:
            mole_start_cell = surrounding_OneMolecule_forframe(
                display_array, Input_MoleParentFolder, Output_moleParentFolder,
                Output_plotParentFolder, GroupNum, FrameNum, 0, backbone_range,
                close, molecule_filename)
            start_cells.append(mole_start_cell)
        print "end of frame!"

        plt.figure(FrameNum, figsize=(16, 12), dpi=100)
        mergeplot = plt.imshow(display_array)
        mergeplot.set_cmap(colormap)
        plt.colorbar()
        for ind in range(0, molecule_amount):
            mole_start_position = mfc.get_coordinate(start_cells[ind], ncol)
            text_position = [
                mole_start_position[0] - 15, mole_start_position[1]
            ]
            text = molecule_filenames[ind].split(".")[0].split("e")[2]
            plt.text(text_position[1],
                     text_position[0],
                     text,
                     color="yellow",
                     size='medium',
                     weight=400)
        mergeplot.set_clim([np.min(display_array), image_max])
    else:
        plt.figure(1, figsize=(16, 12), dpi=100)
        mergeplot = plt.imshow(display_array)
        mergeplot.set_cmap(colormap)
        plt.colorbar()
        mergeplot.set_clim([np.min(display_array), image_max])

    GroupName = "group1-" + str(GroupNum) + "-inca34-outputs/"
    FrameName = "frame" + str(FrameNum)
    output_groupfolder = os.path.join(Output_moleParentFolder, GroupName)
    output_framefolder = os.path.join(output_groupfolder, FrameName)

    if (not os.path.exists(output_framefolder)):
        os.mkdir(output_framefolder)
    os.chdir(output_framefolder)

    framename_png = "frame" + str(FrameNum) + ".png"
    plt.savefig(framename_png)
    output_groupfolder_plot = os.path.join(Output_plotParentFolder, GroupName)
    output_framefolder_plot = os.path.join(output_groupfolder_plot, FrameName)
    if (not os.path.exists(output_framefolder_plot)):
        os.mkdir(output_framefolder_plot)

    framename_png_plot = framename_png
    shutil.copyfile(os.path.join(output_framefolder, framename_png),
                    os.path.join(output_framefolder_plot, framename_png_plot))
    plt.close()
    #	plt.show()

    return molecule_amount
def surrounding_OneMolecule(Input_MoleParentFolder,
                            Output_moleParentFolder,
                            Output_plotParentFolder,
                            GroupNum,
                            FrameNum,
                            MoleculeNum,
                            select_region=[-1, -1],
                            backbone_range=2,
                            close=False):

    GroupNum = int(GroupNum)
    FrameNum = int(FrameNum)
    MoleculeNum = int(MoleculeNum)

    ### data input
    grayData_array = fi.get_grayData_frominf(GroupNum, FrameNum)
    display_array1 = copy.deepcopy(grayData_array)
    display_array2 = copy.deepcopy(grayData_array)
    display_array3 = copy.deepcopy(grayData_array)

    fileContents = mfc.read_molecule_files_frominf(Input_MoleParentFolder,
                                                   GroupNum, MoleculeNum)
    inframe = mfc.find_mole_setframe(fileContents, FrameNum)
    if (not (inframe)):
        print "the molecule is not in this frame! "
        exit(1)

    molecule_contents_setframe = mfc.get_content_setframe(
        fileContents, FrameNum)

    CellNumList_setframe = mfc.get_CellNumbers(molecule_contents_setframe)

    heads, tails = mfc.boundary_x(ncol, CellNumList_setframe)
    x_min = mfc.get_coordinate(heads[0], ncol)[1]
    x_max = mfc.get_coordinate(tails[0], ncol)[1]

    if (select_region[0] == -1): select_region[0] = x_min
    if (select_region[1] == -1): select_region[1] = x_max

    CellNumList_setframe_region = []
    for cellnum in CellNumList_setframe:
        inregion = mfc.find_cell_inregion_x(cellnum, select_region, ncol)
        if (inregion):
            CellNumList_setframe_region.append(cellnum)

    if (len(CellNumList_setframe) != 0):
        ### surrounding intensity acquisition
        surrounding_intensity_circle_1 = surrounding_intensity_circle(
            CellNumList_setframe_region, grayData_array, display_array1, 2, 1,
            close)
        surrounding_intensity_circle_2 = surrounding_intensity_circle(
            CellNumList_setframe_region, grayData_array, display_array2, 2, 2,
            close)
        surrounding_intensity_circle_3 = surrounding_intensity_circle(
            CellNumList_setframe_region, grayData_array, display_array3, 2, 3,
            close)

        surrounding_coordinate_1 = surrounding_circle(
            CellNumList_setframe_region, 2, 1, close)
        surrounding_coordinate_2 = surrounding_circle(
            CellNumList_setframe_region, 2, 2, close)
        surrounding_coordinate_3 = surrounding_circle(
            CellNumList_setframe_region, 2, 3, close)

        length = len(surrounding_intensity_circle_3)
        surrounding = np.zeros((length, 6), dtype=int)
        surrounding[0:(len(surrounding_intensity_circle_1)),
                    0] = surrounding_intensity_circle_1
        surrounding[0:(len(surrounding_intensity_circle_2)),
                    1] = surrounding_intensity_circle_2
        surrounding[0:(len(surrounding_intensity_circle_3)),
                    2] = surrounding_intensity_circle_3
        surrounding[0:(len(surrounding_coordinate_1)),
                    3] = surrounding_coordinate_1
        surrounding[0:(len(surrounding_coordinate_2)),
                    4] = surrounding_coordinate_2
        surrounding[0:(len(surrounding_coordinate_3)),
                    5] = surrounding_coordinate_3

        ### data output
        GroupName = "group1-" + str(GroupNum) + "-inca34-outputs/"
        FrameName = "frame" + str(FrameNum)
        output_groupfolder = os.path.join(Output_moleParentFolder, GroupName)

        ## for storing data
        if (not (os.path.exists(output_groupfolder))):
            os.makedirs(output_groupfolder)
        os.chdir(output_groupfolder)

        filename = "molecule" + str(MoleculeNum) + "_frame" + str(
            FrameNum) + ".txt"
        fileid = open(filename, "w")
        fileid.write(" ".join([
            "intensity1", "intensity2", "intensity3", "coordinate1",
            "coordinate2", "coordinate3", "\n"
        ]))
        for line in range(0, length):
            line_str = map(str, surrounding[line, :])
            line_str.append("\n")
            fileid.write(" ".join(line_str))
        fileid.close()

        print "group", GroupNum, "_frame", FrameNum, "_molecule", MoleculeNum, ": surrounding file created!"

        ## plotting the frame
        mole_start_position = mfc.get_coordinate(CellNumList_setframe[0], ncol)
        text_position = [mole_start_position[0] - 15, mole_start_position[1]]
        text = "mole_" + str(MoleculeNum)

        plt.figure(FrameNum, figsize=(16, 12), dpi=100)
        mergeplot = plt.imshow(display_array1)
        mergeplot.set_cmap(colormap)
        plt.text(text_position[1],
                 text_position[0],
                 text,
                 color="yellow",
                 size='medium',
                 weight=400)
        plt.colorbar()
        mergeplot.set_clim([np.min(display_array3), image_max])

        framename_pdf = "molecule" + str(MoleculeNum) + "_frame" + str(
            FrameNum) + ".pdf"
        framename_png = "molecule" + str(MoleculeNum) + "_frame" + str(
            FrameNum) + ".png"
        plt.savefig(framename_pdf)
        plt.savefig(framename_png)
        #		plt.show()
        plt.close()

        ## save plots to another folder
        output_groupfolder_plot = os.path.join(Output_plotParentFolder,
                                               GroupName)
        if (not (os.path.exists(output_groupfolder_plot))):
            os.makedirs(output_groupfolder_plot)
        framename_pdf_plot = framename_pdf
        framename_png_plot = framename_png
        shutil.copyfile(
            os.path.join(output_groupfolder, framename_pdf),
            os.path.join(output_groupfolder_plot, framename_pdf_plot))
        shutil.copyfile(
            os.path.join(output_groupfolder, framename_png),
            os.path.join(output_groupfolder_plot, framename_png_plot))
        os.remove(os.path.join(output_groupfolder, framename_pdf))
        os.remove(os.path.join(output_groupfolder, framename_png))

    else:
        print(
            "selected region wrong! no pixel of the molecule in this region..")