def surrounding_circle(CellNumList,backbone_range = 2, surround_range = 1, close = False):

	vertical_range = backbone_range + surround_range
	horizontal_range = vertical_range
	
	surrounding_condition = ventral_dorsal_string(CellNumList, vertical_range)

	if(close):
		head_cells, tail_cells = mfc.boundary_x(ncol, CellNumList)
		for head in head_cells:
			head_box = head_tail_box(head, True, False, vertical_range, horizontal_range)
			for head_pixel in head_box:
				surrounding_condition.append(head_pixel)
		for tail in tail_cells:
			tail_box = head_tail_box(tail, False, True, vertical_range, horizontal_range)
			for tail_pixel in tail_box:
				surrounding_condition.append(tail_pixel)

	surrounding_condition = set(map(tuple, surrounding_condition))
	surrounding_condition = list(map(list, surrounding_condition))
	
	surrounding_condition = np.array(surrounding_condition)
	
	surrounding_inframe = surrounding_condition[:,1]
	surrounding_circle = surrounding_condition.compress(surrounding_inframe, axis = 0)[:,0]

	### origin_backbone = surrounding_condition.compress(surrounding_inframe, axis = 0)[:,[0,2]]
	### ready to output the origin position(cellnums)?

	return list(surrounding_circle)  #list(surrounding_origin)
def surrounding_circle(CellNumList,
                       backbone_range=2,
                       surround_range=1,
                       close=False):

    vertical_range = backbone_range + surround_range
    horizontal_range = vertical_range

    surrounding_condition = ventral_dorsal_string(CellNumList, vertical_range)

    if (close):
        head_cells, tail_cells = mfc.boundary_x(ncol, CellNumList)
        for head in head_cells:
            head_box = head_tail_box(head, True, False, vertical_range,
                                     horizontal_range)
            for head_pixel in head_box:
                surrounding_condition.append(head_pixel)
        for tail in tail_cells:
            tail_box = head_tail_box(tail, False, True, vertical_range,
                                     horizontal_range)
            for tail_pixel in tail_box:
                surrounding_condition.append(tail_pixel)

    surrounding_condition = set(map(tuple, surrounding_condition))
    surrounding_condition = list(map(list, surrounding_condition))

    surrounding_condition = np.array(surrounding_condition)

    surrounding_inframe = surrounding_condition[:, 1]
    surrounding_circle = surrounding_condition.compress(surrounding_inframe,
                                                        axis=0)[:, 0]

    ### origin_backbone = surrounding_condition.compress(surrounding_inframe, axis = 0)[:,[0,2]]
    ### ready to output the origin position(cellnums)?

    return list(surrounding_circle)  #list(surrounding_origin)
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 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..")