Beispiel #1
0
def icontest(options, alifile, outsize, cmdsfilepath, aliextension):

    passtest = False

    while not passtest and outsize > 63:

        it1, it2, it3 = calciterations(outsize)

        iterationsstring = str(it1) + ',' + str(it2) + ',' + str(it3)
        print("iterationsstring is {} of type {} ".format(
            iterationsstring, type(iterationsstring)))

        tmpdir = "tmpicontest"

        #print "options.gpus={}, type={}".format(options.gpus,type(options.gpus))
        #print "tmpdir={}, type={}".format(tmpdir,type(tmpdir))
        #print "alifile={}, type={}".format(alifile,type(alifile))
        #print "options.tltfile={}, type={}".format(options.tltfile,type(options.tltfile))

        icongpucmd = "ICON-GPU -input " + alifile + " -tiltfile " + options.tltfile + " -outputPath " + tmpdir + " -slice 0,1 -ICONIteration " + iterationsstring + " -dataType 1 -threshold 0 -gpu " + options.gpus
        cmdicontest = "mkdir " + tmpdir + " ; " + icongpucmd

        try:
            runcmd(options, cmdicontest, cmdsfilepath)

            findirtest = os.listdir(tmpdir + '/reconstruction/')

            for f in findirtest:
                if '.mrc' in f[-4:]:
                    imgpath = tmpdir + '/reconstruction/' + f
                    img = EMData(imgpath, 0)
                    sigma = img['sigma']
                    sigmanonzero = img['sigma_nonzero']

                    shutil.rmtree(tmpdir)
                    if sigma and sigmanonzero:
                        passtest = True
                        print(
                            "\nthe test passed; the tiltseries has a good size now nx={}, ny={}"
                            .format(img['nx'], img['ny']))
                        return alifile, outsize, iterationsstring
                    else:
                        passtest = False
                        outsize -= 2
                        print(
                            "\nICON-GPU failed becase the image size was bad; cropping the images in the tiltseries to this new size, nx={}, nx={}"
                            .format(outsize, outsize))
                        alifile = cropper(options, alifile, aliextension,
                                          outsize, cmdsfilepath)
                        break
        except:
            print(
                "\nWARNING: ICON-GPU command failed; the command run was cmd={}"
                .format(icongpucmd))

    return
Beispiel #2
0
def iconpreprocfunc(options, alifile, extension, cmdsfilepath):

    #from shutil import copyfile

    outfile = options.tiltseries.replace(
        extension, '_iconpreproc_th' + str(options.thickness) + '.st')
    backupst = 'backup.' + options.tiltseries
    backupali = 'backup.' + alifile

    if options.verbose:
        print("\n(e2tomo_icongpu)(iconpreprocfunc) running ICONPreProcess")
    cmd1 = "ICONPreProcess -input " + options.tiltseries + " -tiltfile " + options.tltfile + " -thickness " + str(
        options.thickness) + " -output " + outfile
    runcmd(options, cmd1, cmdsfilepath)

    if options.verbose:
        print(
            "\n(e2tomo_icongpu)(iconpreprocfunc) backing up raw (x-ray corrected) tiltseries {} to file {}"
            .format(options.tiltseries, backupst))
    shutil.copyfile(options.tiltseries, backupst)
    #cmd2 = "cp " + options.tiltseries + " " + backupst
    #runcmd(options,cmd2,cmdsfilepath)

    if options.verbose:
        print(
            "\n(e2tomo_icongpu)(iconpreprocfunc) copying the preprocessed tiltseries {} to the original tiltseries file {}"
            .format(outfile, options.tiltseries))
    shutil.copyfile(outfile, options.tiltseries)
    #cmd4 = "cp " + outfile + " " + options.tiltseries
    #runcmd(options,cmd4,cmdsfilepath)

    if options.verbose:
        print(
            "\n(e2tomo_icongpu)(iconpreprocfunc) backing up aligned tiltseries {} to file {}"
            .format(alifile, backupali))
    shutil.copyfile(alifile, backupali)
    #cmd3 = "cp " + alifile + " " + backupali
    #runcmd(options,cmd3,cmdsfilepath)

    if options.verbose:
        print(
            "\n(e2tomo_icongpu)(iconpreprocfunc) generating new .ali file after ICONPreProcess"
        )
    cmd2 = "subm newst"
    runcmd(options, cmd2, cmdsfilepath)

    return
Beispiel #3
0
def cropper(options,alifile,extension,outsize,cmdsfilepath):
	
	hdr = EMData(alifile,0,True)
	nx=hdr['nx']
	ny=hdr['ny']

	if options.verbose:
		print("\nWARNING: the tiltseries will be resized since its images are not squares. The original size is nx={}, ny={}, and will be cropped to nx={}, ny={}".format(nx,ny,outsize,outsize))
	
	outcrop = alifile.replace(extension,'_clip' + str(outsize) + extension)
	if '_clip' in alifile:
		outcrop = alifile.split('_clip')[0]+extension 
		outcrop = outcrop.replace(extension,'_clip' + str(outsize) + extension)

	cmdcrop = "e2proc2d.py " + alifile + ' ' + outcrop + ' --clip ' + str(outsize) + ',' + str(outsize)
	
	runcmd(options,cmdcrop,cmdsfilepath)

	return outcrop
Beispiel #4
0
def icongpufunc(options, alifile, cmdsfilepath):

    alifilename, aliextension = os.path.splitext(alifile)

    hdr = EMData(alifile, 0, True)
    nx = hdr['nx']
    ny = hdr['ny']

    outsize = nx

    if nx != ny:

        if ny < nx:
            outsize = ny

        if outsize % 2:
            outsize -= 1

        alifile = cropper(options, alifile, aliextension, outsize,
                          cmdsfilepath)

    alifile, outsize, iterationsstring = icontest(options, alifile, outsize,
                                                  cmdsfilepath, aliextension)

    icondir = options.path

    thickness = old_div(float(outsize), 4.0)

    if options.thickness:
        thickness = float(options.thickness)
        #print "\noptions.thickness has changed thickness to {}".format(thickness)
    if options.sizez:
        thickness = float(options.sizez)
        #print "\noptions.sizez has changed thickness to {}".format(thickness)

    thickenss = int(round(thickness))
    print("\naaaafter options, thickness is {}".format(thickness))

    outtomogram = alifile.replace(aliextension, '_icongpu.mrc')

    if options.verbose:
        print("\n(e2tomo_icongpu)(icongpufunc) calling ICON-GPU.")
    cmdicon1 = 'ICON-GPU -input ' + alifile + ' -tiltfile ' + options.tltfile + ' -outputPath ' + icondir + ' -slice 0,' + str(
        outsize - 1
    ) + ' -ICONIteration ' + iterationsstring + ' -dataType 1 -threshold 0 -gpu ' + options.gpus
    runcmd(options, cmdicon1, cmdsfilepath)

    findir = os.listdir(icondir + '/crossValidation')

    if 'crossV.frc' in findir:
        sigma = 1000000000
        sigmanonzero = 100000000
        try:
            hdr = EMData(icondir + '/crossValidation/crossV.frc')
            sigma = hdr['sigma']
            sigmanonzero = hdr['sigma_nonzero']
        except:
            with open(icondir + '/crossValidation/crossV.frc',
                      'r') as crossVfrcfile:
                lines = crossVfrcfile.readlines()

                if not lines: sigma = sigmanonzero = 0.0
                elif int(len(lines)) < int(old_div(nx, 2.0) - 1.0):
                    sigma = 0.0
                    sigmanonzero = 0.0

        if float(sigma) == 0.0 or float(sigmanonzero) == 0.0:
            print(
                "\nWARNING: the crossV.frc file generated by ICON-GPU is empty; generating it 'manually' with e2proc3d"
            )
            cmdcrossvfrc = 'cd ' + icondir + '/crossValidation && e2proc3d.py crossV_reprojection.mrc --calcfsc=GroundTruth.mrc crossV.frc'
            runcmd(options, cmdcrossvfrc, cmdsfilepath)

            #hdr = EMData( icondir + '/crossValidation/crossV.frc' )
            #sigma = hdr['sigma']
            #sigmanonzero = hdr['sigma_nonzero']

            #if float(sigma) == 0.0 or float(sigmanonzero) == 0.0:
            #	print("\nERROR: manual computation of crossV.frc with e2proc3d failed")
            #	sys.exit(1)

    elif 'crossV.frc' not in findir:
        print(
            "\nERROR: no crossV.frc file found inside {}/crossValidation directory"
            .format(icondir))
        sys.exit(1)

    if options.verbose:
        print("\n(e2tomo_icongpu)(icongpufunc) calling ICONMask3.")
    cmdicon2 = 'ICONMask3 -inputPath ' + icondir + '/reconstruction -tiltfile ' + options.tltfile + ' -output ' + outtomogram + ' -slice 0,' + str(
        outsize - 1
    ) + ' -thickness ' + str(
        thickness
    ) + ' -crossVfrc ' + icondir + '/crossValidation/crossV.frc -fullRecfrc ' + icondir + '/crossValidation/fullRec.frc'
    runcmd(options, cmdicon2, cmdsfilepath)

    outtomogramzshort = outtomogram.replace('.mrc', '_ZSHORT.mrc')
    if options.verbose:
        print(
            "\n(e2tomo_icongpu)(icongpufunc) calling IMOD to rotate the reconstructed volume around x and shrink it if --shrink > 1 was specified."
        )
    cmdimod1 = 'clip rotx ' + outtomogram + ' ' + outtomogramzshort
    runcmd(options, cmdimod1, cmdsfilepath)
    os.remove(outtomogram)
    sourcetomo = outtomogramzshort

    outtomogramzshortbinned = outtomogramzshort.replace(
        '.mrc', '_bin' + str(options.shrink) + '.mrc')
    if options.shrink and int(options.shrink) > 1:
        cmdimod2 = 'binvol ' + outtomogramzshort + ' ' + outtomogramzshortbinned + ' --binning ' + str(
            options.shrink) + ' --antialias -1'
        runcmd(options, cmdimod2, cmdsfilepath)
        sourcetomo = outtomogramzshortbinned

    outtomogramzshortpostproc = sourcetomo
    if options.lowpassresolution and not options.highpasspixels:
        outtomogramzshortpostproc = sourcetomo.replace(
            '.mrc', '_lp' + str(options.lowpassresolution))
        cmdeman2 = 'e2proc3d.py ' + sourcetomo + ' ' + outtomogramzshortpostproc + ' --process filter.lowpass.tanh:cutoff_freq=' + str(
            old_div(1.0, options.lowpassresolution))
        runcmd(options, cmdeman2, cmdsfilepath)

    elif options.highpasspixels and not options.lowpassresolution:
        outtomogramzshortpostproc = sourcetomo.replace(
            '.mrc', '_hpp' + str(options.highpasspixels) + '.mrc')
        cmdeman2 = 'e2proc3d.py ' + sourcetomo + ' ' + outtomogramzshortpostproc + ' --process filter.highpass.gauss:cutoff_pixels=' + str(
            options.highpasspixels)
        runcmd(options, cmdeman2, cmdsfilepath)

    elif options.lowpassresolution and options.highpasspixels:
        outtomogramzshortpostproc = sourcetomo.replace(
            '.mrc', '_lp' + str(int(round(options.lowpassresolution))) +
            '_hpp' + str(int(options.highpasspixels)) + '.mrc')
        cmdeman2 = 'e2proc3d.py ' + sourcetomo + ' ' + outtomogramzshortpostproc + ' --process filter.lowpass.tanh:cutoff_freq=' + str(
            old_div(1.0, options.lowpassresolution)
        ) + ' --process filter.highpass.gauss:cutoff_pixels:' + str(
            options.highpasspixels)
        runcmd(options, cmdeman2, cmdsfilepath)

    os.rename(outtomogramzshort, options.path + '/' + outtomogramzshort)

    if options.shrink and options.shrink > 1:
        os.rename(outtomogramzshortbinned,
                  options.path + '/' + outtomogramzshortbinned)

    if options.lowpassresolution or options.highpasspixels:
        os.rename(outtomogramzshortpostproc,
                  options.path + '/' + outtomogramzshortpostproc)

    return
Beispiel #5
0
def main():

    progname = os.path.basename(sys.argv[0])
    usage = """This program allows you to examine density variations along one or more volumes.
				It calculates the mean intensity either for slices (planes) along any of the three cartesian axes (X, Y or Z), 
				or for radial consecutive shells of increasing radius, 
				or for cylindrical shells of varying or fixed height, starting from the center of the volume. 
				All mean density values are saved to .txt files, and plots are produced from them are saved as .png images. 
				To compare the density variations across different volumes, you can plot all curves in a single plot.
				To reduce complexity and anomalies induced by the missign wedge, and option is provided to project the volumes onto 2-D images first."""

    parser = EMArgumentParser(usage=usage, version=EMANVERSION)

    parser.add_argument(
        "--classifymaxpeaks",
        type=int,
        default=0,
        help=
        """default=0. Number of highest peaks to consider for classification. Amongst the n peaks provided, --classifymaxpeaks=n, the peak occurring at the largest radius will be used as the classifier. If --classifymaxpeaks=1, the highest peak will be the classifier. To smooth the radial density curve consider low pass filtering through --lowpass. To remove aberrant peaks consider masking with --mask."""
    )

    parser.add_argument(
        "--fitgaussian",
        action="store_true",
        default=False,
        help=
        """default=false. Fits a Gaussian to the radial density plot (only appropriate in certain cases; look at the raw plot first and rerun program if the plot looks like a bell curve)."""
    )
    parser.add_argument(
        "--fixedcylinderheight",
        type=int,
        default=0,
        help=
        """Default=0. Works only if --mode=cylinder, and keeps the height of the cylinder at a constant value, while varying the radius."""
    )

    parser.add_argument(
        "--highpass",
        type=str,
        default=None,
        help=
        """default=none. A highpass filtering processor (see e2help.py --verbose=10) applied to each volume prior to radial density plot computation."""
    )

    parser.add_argument(
        "--input",
        type=str,
        default=None,
        help=
        """Volume whose radial density plot you want to compute. For multiple volumes, either provide them as an .hdf stack, or separate them by commas --vols=first.hdf,second.hdf,etc..."""
    )

    parser.add_argument(
        "--lowpass",
        type=str,
        default=None,
        help=
        """default=None. A lowpass filtering processor (see e2help.py --verbose=10) applied to each volume prior to radial density plot computation."""
    )

    parser.add_argument(
        "--mask",
        type=str,
        default=None,
        help=
        """default=none. Masking processor (see e2help.py --verbose=10) applied to each volume prior to radial density plot computation."""
    )
    parser.add_argument(
        "--mode",
        type=str,
        default='sphere',
        help=
        """default=sphere. provide --mode=x, y, or z to get the average density per slice in the indicated direction. --mode=cylinder for concentric cylindrical shells. For MULTIPLE modes, separate them by commas, for example --mode=x,y,z,cylinder"""
    )

    parser.add_argument(
        "--normproc",
        type=str,
        default=None,
        help=
        """default=none. Normalization processor (see e2help.py --verbose=10) applied to each volume prior to radial density plot computation. If normalize.mask is used, results of the mask option will be passed in automatically."""
    )
    parser.add_argument(
        "--normalizeplot",
        action="store_true",
        default=False,
        help=
        """default=false. This will make the maximum density in each plot or curve equal to 1."""
    )

    parser.add_argument('--path',
                        type=str,
                        default='spt_radialplot',
                        help="""Directory to save the results.""")
    parser.add_argument(
        "--plotmaxima",
        action="store_true",
        default=False,
        help=
        """default=false. If on, this plots a vertical line at each maxima (peak) for easier visualization."""
    )
    parser.add_argument(
        "--preprocess",
        type=str,
        default=None,
        help=
        """Any processor (see e2help.py --verbose=10) applied to each volume prior to radial density plot computation."""
    )

    parser.add_argument(
        "--savetxt",
        action="store_true",
        default=False,
        help=
        """default=false. Save plot files as .txt, so that they can be replotted with other software if necessary."""
    )
    parser.add_argument(
        "--shrink",
        type=int,
        default=0,
        help=
        """default=0 (not used). Optionally shrink the input volumes by an integer amount."""
    )
    parser.add_argument(
        "--singlefinalplot",
        action="store_true",
        default=False,
        help=
        """default=false. Plot all the Radial Density Profiles of the volumes provided in all .hdf stacks in one FINAL single 'master' plot."""
    )
    parser.add_argument(
        "--singleplotperfile",
        action="store_true",
        default=False,
        help=
        """default=false. Plot all the Radial Density Profiles of the volumes provided in each .hdf stack in one single plot."""
    )
    parser.add_argument(
        "--subset",
        type=int,
        default=0,
        help="""An n-subset of particles from --input to use.""")
    parser.add_argument(
        "--sym",
        dest="sym",
        default='c1',
        help=
        """default=c1. Symmetry to impose choices are: c<n>, d<n>, h<n>, tet, oct, icos. For this to make any sense in the context of this program, the particles need to be aligned to the symmetry axis first, which can be accomplished by running them through e2symsearch3d.py."""
    )

    parser.add_argument(
        "--threshold",
        type=str,
        default=None,
        help=
        """default=None. A threshold  processor (see e2help.py --verbose=10) applied to each volume prior to radial density plot computation."""
    )

    parser.add_argument(
        "--ppid",
        type=int,
        help=
        """Set the PID of the parent process, used for cross platform PPID""",
        default=-1)

    parser.add_argument(
        "--verbose",
        "-v",
        default=0,
        help=
        """default=0. Verbose level [0-9], higher number means higher level of verboseness""",
        dest="verbose",
        action="store",
        metavar="n",
        type=int)

    (options, args) = parser.parse_args()

    import matplotlib.pyplot as plt

    from EMAN2_utils import makepath, runcmd, sptOptionsParser
    options = makepath(options, 'spt_radialplot')

    if not options.input:
        parser.print_help()
        exit(0)
    elif options.subset:
        subsetStack = options.path + '/subset' + str(options.subset).zfill(
            len(str(options.subset))) + '.hdf'
        print("\nSubset to be written to", subsetStack)

        subsetcmd = 'e2proc3d.py ' + options.input + ' ' + subsetStack + ' --first=0 --last=' + str(
            options.subset - 1)
        print("Subset cmd is", subsetcmd)

        runcmd(subsetcmd)
        #p=subprocess.Popen( subsetcmd, shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE )
        #text=p.communicate()
        #p.stdout.close()

        options.input = subsetStack

    logger = E2init(sys.argv, options.ppid)

    options = sptOptionsParser(options)

    #if options.normproc:
    #	options.normproc=parsemodopt(options.normproc)

    #if options.mask:
    #	options.mask=parsemodopt(options.mask)

    #if options.preprocess:
    #	options.preprocess=parsemodopt(options.preprocess)

    #if options.lowpass:
    #	options.lowpass=parsemodopt(options.lowpass)

    #if options.highpass:
    #	options.highpass=parsemodopt(options.highpass)

    #if options.threshold:
    #	options.threshold=parsemodopt(options.threshold)

    files = options.input
    files = files.split(',')

    for i in range(0, len(files)):
        for j in range(i + 1, len(files)):
            if files[i] == files[j]:
                print(
                    "ERROR: You have supplied a file twice, see file[i]={}, file[j]={}"
                    .format(files[i], files[j]))
                sys.exit(1)

    modes = options.mode.split(',')

    for m in modes:
        options.mode = m
        modetag = '_MODE' + m
        finalvalues = {}
        imgsperstack = 1

        names = []
        finalvalues = []
        maxsall = {}
        minsall = {}

        for i in files:
            n = EMUtil.get_image_count(i)

            print("Stack={} has n={} images in it".format(i, n))

            kk = 0
            stack = {}
            stackvalues = []
            suffix = modetag
            for j in range(n):
                ptcl = EMData(i, j)
                if n > 1:
                    suffix = modetag + str(kk).zfill(len(str(n)))

                values = calcvalues(ptcl, options)

                ret = calcmaxima(values)
                maxima = ret[
                    0]  #These are a list of lists [[pixel,value],[pixel,value],...] with all maxima and minima
                minima = ret[-1]

                uniquetag = i + '_indextag' + str(j)
                maxsall.update({uniquetag: maxima})
                minsall.update({uniquetag: minima})

                print("For file={} img number={} the max={}".format(
                    i, j, max(values)))

                if options.normalizeplot:

                    minv = min(values)
                    for v in range(len(values)):
                        values[v] = values[v] - minv

                    maxv = max(values)
                    for v in range(len(values)):
                        values[v] = old_div(values[v], maxv)
                    print("Therefore, max={}".format(max(values)))

                id = i.replace('.', suffix + '.')
                stackvalues.append([id, values])
                kk += 1
            stack.update({i: stackvalues})
            finalvalues.append(stack)

        plotname = 'finalplot_MODE' + m + '.png'
        fileid = ''

        if options.classifymaxpeaks:
            classifymax(options, maxsall)

        cc = 0
        for ele in finalvalues:
            thisfile = list(ele.keys())[0]
            key = thisfile

            n = EMUtil.get_image_count(thisfile)

            if options.singleplotperfile:
                fileid = i.split('.')[0]
                plotname = fileid + modetag + '.png'

            kk = 0
            maxvallocs_pixels = []
            maxvallocs_angs = []

            maxslope_pixels = []
            maxslope_postmax_pixels = []
            maxslope_postlastpeak_pixels = []

            minslope_pixels = []
            for index in range(n):

                apix = EMData(thisfile, index, True)['apix_x']

                values = ele[key][index][1]
                id = ele[key][index][0]

                xs = list(range(len(values)))

                for j in range(len(xs)):
                    xs[j] = int(round(xs[j] * apix))

                if options.savetxt:

                    txtname = options.path + '/' + thisfile.split(
                        '.')[0] + modetag + str(kk).zfill(len(str(n))) + '.txt'
                    textwriter(values, options, txtname)
                    #txtf = open(txtname,'w')
                    #lines = []
                    #for v in range(len(values)):
                    #	line = str(v) +  ' ' + str(values[v]) + '\n'
                    #	lines.append(line)
                    #txtf.writelines(lines)
                    #txtf.close()

                maxval = max(values)
                maxvalloc = values.index(maxval)
                maxvallocs_pixels.append(maxvalloc)
                maxvallocs_angs.append(maxvalloc * apix)

                uniquetag = thisfile + '_indextag' + str(
                    index)  #i=filename, f=index of img in filename
                maxima = maxsall[uniquetag]

                lastpeakloc = maxima[-1][0]

                ziplist = list(zip(values[:-1], values[1:]))
                ziplistpostmax = list(
                    zip(values[maxvalloc:-1], values[maxvalloc + 1:]))
                ziplistpostlastpeak = list(
                    zip(values[lastpeakloc:-1], values[lastpeakloc + 1:]))

                diflist = [a1 - a2 for a1, a2 in ziplist]
                diflistpostmax = [a1 - a2 for a1, a2 in ziplistpostmax]
                diflistpostlastpeak = [
                    a1 - a2 for a1, a2 in ziplistpostlastpeak
                ]
                #print("\nziplist is".format(ziplist))
                #print("\ndiflist is".format(diflist))

                max_slope = max(diflist)
                indexmaxslope = diflist.index(max_slope)
                maxslope_pixels.append(indexmaxslope)

                max_slope_postmax = max(diflistpostmax)
                indexmaxslope_postmax = diflist.index(max_slope_postmax)
                maxslope_postmax_pixels.append(indexmaxslope_postmax)

                #max_slope_postlastpeak = indexmaxslope_postlastpeak = None

                try:
                    max_slope_postlastpeak = max(diflistpostlastpeak)
                    indexmaxslope_postlastpeak = diflist.index(
                        max_slope_postlastpeak)
                    maxslope_postlastpeak_pixels.append(
                        indexmaxslope_postlastpeak)

                except:
                    if options.verbose:
                        print(
                            '\n\n!!!!!ERROR computing slope after last peak; skipping particle'
                        )

                if options.verbose:
                    print(
                        "\nmaxpeak at pixel={}; maxslope at pixel={}; after maxpeak, maxslope at pixel={}; after lastpeak, maxslope at pixel={}"
                        .format(maxvalloc, indexmaxslope,
                                indexmaxslope_postmax,
                                indexmaxslope_postlastpeak))

                min_slope = min(diflist)
                indexminslope = diflist.index(min_slope)
                print("\nmin slope is at pixel={}".format(indexminslope))

                plt.plot(xs, values, linewidth=2, alpha=0.5)

                if options.plotmaxima:
                    nm = len(maxima)
                    peaklocs = []
                    peakvals = []
                    for ii in range(nm):
                        peakloc = maxima[ii][0] * apix
                        peaklocs.append(peakloc)

                        peakval = maxima[ii][1]
                        peakvals.append(peakval)

                        plt.axvline(x=peakloc,
                                    linewidth=2,
                                    alpha=0.5,
                                    color='k',
                                    linestyle='--')

                    #takes data of the form: textwriter(yvalues,options,txtname,invert=0,xvalues=None)
                    maxtxtname = options.path + '/' + thisfile.split(
                        '.')[0] + modetag + str(kk).zfill(len(
                            str(n))) + '_maxima.txt'

                    textwriter(peakvals, options, maxtxtname, 0, peaklocs)

                if not options.singleplotperfile and not options.singlefinalplot:
                    #plotname=i.split('.')[0]+str(kk).zfill(len(str(n))) + '.png'
                    plotname = id.split('.')[0] + '.png'
                    fileid = plotname.split('.')[0]

                if options.mode == 'sphere':
                    plt.title("Spherical radial density plot " + fileid)
                    plt.xlabel("Radius (angstroms)")
                    plt.ylabel("Density (arbitrary units)")

                if options.mode == 'x':
                    plt.title("Density plot of slices along x-axis " + fileid)
                    plt.xlabel("X (angstroms)")
                    plt.ylabel("Density (arbitrary units)")

                if options.mode == 'y':
                    plt.title("Density plot of slices along y-axis " + fileid)
                    plt.xlabel("Y (angstroms)")
                    plt.ylabel("Density (arbitrary units)")

                if options.mode == 'z':
                    plt.title("Density plot of slices along z-axis " + fileid)
                    plt.xlabel("Z (angstroms)")
                    plt.ylabel("Density (arbitrary units)")

                if options.mode == 'cylinder':
                    plt.title(
                        "Density plot of concentric cylyndrical shells " +
                        fileid)
                    plt.xlabel("Radius (angstroms)")
                    plt.ylabel("Density (arbitrary units)")

                if not options.singleplotperfile and not options.singlefinalplot:
                    if options.path not in plotname:
                        plotname = options.path + '/' + plotname
                    plt.savefig(plotname)
                    plt.clf()
                else:
                    pass
                kk += 1
                cc += 1

            maxtxtname_pixels = options.path + '/' + thisfile.split(
                '.')[0] + modetag + str(kk).zfill(len(
                    str(n))) + '_maxima_pixels.txt'
            textwriter(maxvallocs_pixels, options, maxtxtname_pixels, 0)

            maxtxtname_angs = options.path + '/' + thisfile.split(
                '.')[0] + modetag + str(kk).zfill(len(
                    str(n))) + '_maxima_angstroms.txt'
            textwriter(maxvallocs_angs, options, maxtxtname_angs, 0)

            maxslopetxtname_pixels = options.path + '/' + thisfile.split(
                '.')[0] + modetag + str(kk).zfill(len(
                    str(n))) + '_maxslope_pixels.txt'
            textwriter(maxslope_pixels, options, maxslopetxtname_pixels, 0)

            maxslopetxtname_postmax_pixels = options.path + '/' + thisfile.split(
                '.')[0] + modetag + str(kk).zfill(len(
                    str(n))) + '_maxslope_postmax_pixels.txt'
            textwriter(maxslope_postmax_pixels, options,
                       maxslopetxtname_postmax_pixels, 0)

            maxslopetxtname_postlastpeak_pixels = options.path + '/' + thisfile.split(
                '.')[0] + modetag + str(kk).zfill(len(
                    str(n))) + '_maxslope_postlastpeak_pixels.txt'
            textwriter(maxslope_postlastpeak_pixels, options,
                       maxslopetxtname_postlastpeak_pixels, 0)

            if options.singleplotperfile:
                if options.path not in plotname:
                    plotname = options.path + '/' + plotname
                plt.savefig(plotname)
                plt.clf()

        if options.singlefinalplot:
            if options.path not in plotname:
                plotname = options.path + '/' + plotname
            plt.savefig(plotname)
            plt.clf()
    return