Example #1
0
def fit_gauss(lroi, imp, p, peak_id, id_, type_, rm):
	lroi.setName("{}_{}_{}".format(str(id_), peak_id, type_))
	imp.setRoi(lroi)
	rm.addRoi(lroi)
	
	prof = ProfilePlot(imp)
	y = prof.getProfile()
	x = xrange(len(y))
	
	fitter = CurveFitter(x, y)
	fitter.doFit(CurveFitter.GAUSSIAN)
	param_values = fitter.getParams()
	std = param_values[3]
	fwhm = 2.3548 * std
	r2 = fitter.getFitGoodness()

	y_ = [fitter.f(x_) for x_ in x]
	
	area_profile = sum(y)  - len(y) *min(y)
	area_gauss   = sum(y_) - len(y_)*min(y_)
	
	output = {}
	output["x_pos"] = p.x
	output["y_pos"] = p.y
	output["fwhm"] = fwhm
	output["fwhm_nm"] = pixel_size_nm * fwhm
	output["r2_GoF"] = r2
	output["id"] = id_
	output["peak_id"] = peak_id
	output["type"] = type_
	# yai, excel maagic :-)
	output["avg_fwhm"] = '=AVERAGEIFS(F:F,B:B,B{},F:F,"<>"&"")'.format(id_+2)
	output["area_profile"] = area_profile
	output["area_gauss"] = area_gauss

	if peak_id == DEBUG:		
		plot = Plot("ROI peak {} type {}".format(peak_id, type_), "X (gray)", "Y (fit window)")
		plot.setLineWidth(2)
		plot.setColor(Color.RED)
		plot.addPoints(x, y, Plot.LINE)
		plot.setColor(Color.BLUE)
		plot.addPoints(x, y_, Plot.LINE)
		plot.show()
		
	return  output
Example #2
0
def create_plot(imp, method, average, threshold=0.1):
	intensity = cross_section_intensity(imp, method)
	cal = imp.getCalibration()
	x_inc = cal.pixelWidth;
	units = cal.getUnits();
	x_label = "Distance (%s)" % units
	y_label = 'Intensity' # cal.getValueUnit()
	x_values = [i*x_inc for i in range(len(intensity))]

	lastindex = len(x_values)-1
	for i in range(1, len(x_values)+1):
		index = len(x_values)-i
		if intensity[index] == 0:
			lastindex = index-1
		else:
			break
	ax = [x_values[i] for i in range(lastindex)]
	ay = [intensity[i] for i in range(lastindex)]
	average_x, average_y = rolling_average(ax, ay, average)

	firstidx, lastidx, threshold_intensity = get_thresholded_idx(average_y, threshold=threshold)
	perform_trim = firstidx!=-1 and lastidx!=-1
	if perform_trim:
	    trim_x = [average_x[i] for i in range(firstidx, lastidx+1)]
	    trim_y = [average_y[i] for i in range(firstidx, lastidx+1)]

	# raw data
	flags = Plot.getDefaultFlags()
	flags = flags - Plot.Y_GRID - Plot.X_GRID
	plot = Plot("%s-Plot" % imp.getTitle(), x_label, y_label, flags)
	plot.setLineWidth(1)
	plot.setColor(Color.BLACK)
	plot.addPoints(x_values, intensity,Plot.LINE)

	# threshold line
	plot.setLineWidth(2)
	plot.setColor(Color.BLACK)
	plot.addPoints([0,x_inc * imp.getWidth()], [threshold_intensity,threshold_intensity],Plot.LINE)

	# rolling average
	plot.setLineWidth(2)
	plot.setColor(Color.MAGENTA)
	plot.addPoints(average_x,average_y,Plot.LINE)

	# standard legend labels
	labels = "\t".join(['Raw Data (%s)' % method, 'Intensity threshold (%d%s)' % (100*threshold, '%'), 'Rolling Average (n=%d)' % average])

	# trimmed rolling average
	if perform_trim:
	    plot.setLineWidth(2)
	    plot.setColor(Color.GREEN)
	    plot.addPoints(trim_x,trim_y,Plot.LINE)
	    labels+='\tTrimmed Rolling Average (n=%d)' % average

	plot.setColor(Color.BLACK)
	plot.setLimitsToFit(False)
	plot.addLegend(labels)

	rt = ResultsTable()
	for row,x in enumerate(x_values):
		rt.setValue(DIST_RAW_COL, row, x)
		rt.setValue(INT_RAW_COL, row, intensity[row])
	for row,x in enumerate(average_x):
		rt.setValue(DIST_AVG_COL, row, x)
		rt.setValue(INT_AVG_COL, row, average_y[row])
	if perform_trim:
	    for row,x in enumerate(trim_x):
		    rt.setValue(DIST_TRIM_COL, row, x)
		    rt.setValue(INT_TRIM_COL, row, trim_y[row])
    
	return plot, rt
Example #3
0
		
	# Means per frame and then mean of mean
		listmeans = ImagesMean(dataset, z)
		stackmeans = computeMean(listmeans)
		filemeans.append(stackmeans)
		
	# Stds per frame.
		liststds = ImagesStd(dataset,listmeans, z)
		grouped = group_stds(liststds)
		#std the std.
		filestds.append(grouped)
	
	return filemeans, filestds



# MAIN CODE
srcDir = DirectoryChooser("Choose").getDirectory()
filelist = get_file_list(srcDir, '.tif')
means, stds = main(filelist)


# PLOTTING
plot = Plot("PTC", "Mean", "Std")
plot.setLimits(0.00, 200.0, 0.00, 100.0)
plot.setColor(Color.BLUE)
plot.addPoints(means, stds, Plot.CROSS)
plot.show()
print means, stds

from ij.gui import Plot
from java.awt import Color
import jarray
import os

# start clean
IJ.run("Close All")

# create example data arrays
xa = [1, 2, 3, 4]
ya = [3, 3.5, 4, 4.5]

# convert to java array
jxa = jarray.array(xa, 'd')
jya = jarray.array(ya, 'd')

# Create filled plot
plt = Plot("Line plot", "X", "Y")
plt.setLimits(0, 5, 0, 5)
plt.setFrameSize(600, 300)
plt.setColor("blue", "#ccccff")

# the circles are small. Can't figure out how to make
# them larger... These 2 calls are equivalent...
# plt.addPoints(jxa,jya, Plot.CIRCLE)
plt.add("circles", jxa, jya)
plt.setColor(Color.RED)
plt.setLineWidth(1)
plt.drawLine(0.0, 2.5, 4.0, 4.5)
plt.setXYLabels("X", "Y")
plt.show()
Example #5
0
mx1 = []
mx2 = []
my1 = []
my2 = []
for i in range(0, len(x1)):
    mx1.append(x1[i] - dx[i] / 2)
    my1.append(y1[i] - dy[i] / 2)
    mx2.append(x2[i] - dx[i] / 2)
    my2.append(y2[i] - dy[i] / 2)

#plt = Plot(fName, "degrees","degrees")
#plt.setLimits(-10,10, -10, 10)
##plt.setAxes(False,False,True, True,False, False, 1, 10);
#plt.setFrameSize(500,500);
#plt.draw()
#plt.addPoints(cx,cy,Plot.CIRCLE);
#plt.drawVectors(x1,y1,x2,y2)
#plt.show()

plt2 = Plot(fName, "degrees", "degrees")
plt2.setLimits(-10, 10, -10, 10)
plt2.setAxes(False, False, True, True, False, False, 1, 10)
plt2.setFrameSize(500, 500)
plt2.draw()
plt2.addPoints(cx, cy, Plot.CIRCLE)
plt2.drawVectors(mx1, my1, mx2, my2)
plt2.setColor(java.awt.Color.RED)
plt2.setLineWidth(2)
plt2.addPoints(x1, y1, Plot.CIRCLE)
plt2.show()
    for filename, row, row_value in all_ydata:
        table.set(filename, row, row_value)
    uiservice.show("MergedFiles_%s" % data_identifier, table)

    log("Retrieving statistics for merged Y-data...")
    list_of_rows = defaultdict(list)
    for data in all_ydata:
        list_of_rows[data[1]].append(data[2])

    row_stats = {}
    for row_key, row_values in list_of_rows.iteritems():
        row_stats[row_key] = (mean(row_values), stdev(row_values), len(row_values))

    table = newtable(xcolumn_header, xvalues)
    for key, value in row_stats.iteritems():
        table.set("Mean", int(key), value[0])
        table.set("StdDev", int(key), value[1])
        table.set("N", int(key), value[2])
    uiservice.show("Stats_%s" % data_identifier, table)

    plot = Plot("Mean Sholl Plot [%s]" % ycolumn_header, xcolumn_header, "N. of intersections")
    plot.setLegend("Mean"+ u'\u00B1' +"SD", Plot.LEGEND_TRANSPARENT + Plot.AUTO_POSITION)
    plot.setColor("cyan", "blue")
    plot.addPoints(table.get(0), table.get(1), table.get(2), Plot.CONNECTED_CIRCLES, data_identifier)
    plot.show()

    log("Parsing concluded.")


main()
Example #7
0
# Find the best linear fit of mean gray level vs camera exposure
cf = CurveFitter(exposures, list(levels))
cf.doFit(CurveFitter.STRAIGHT_LINE)
fitParams = cf.getParams()
slope = fitParams[1]
intercept = fitParams[0]
rSqr = cf.getRSquared()

print("slope=", slope, " ; intercept=", intercept, " ; rSquared=", rSqr)

# Plot the data and the regression line
newPlotFlags = Plot.TRIANGLE + Plot.X_GRID + Plot.X_NUMBERS + Plot.Y_GRID + Plot.Y_NUMBERS
newPlot = Plot("DARK NOISE", "EXPOSURE, ms", "MEAN GRAY LEVEL", newPlotFlags)
newPlot.setLineWidth(2)
newPlot.setColor("red")
newPlot.add("triangle", exposures, list(levels))
newPlot.setLineWidth(1)
newPlot.setColor("black")
newPlot.drawLine(exposures[0], cf.f(exposures[0]), exposures[-1],
                 cf.f(exposures[-1]))
newPlot.setColor("blue")
newPlot.setFontSize(20)
newPlot.addText("y = a+bx", 100.0, 13000.0)
newPlot.addText("a = " + str(round(intercept, 2)), 100.0, 12250.0)
newPlot.addText("b = " + str(round(slope, 2)), 100.0, 11500.0)
newPlot.addText("R squared = " + str(round(rSqr, 3)), 100.0, 10750.0)
newPlot.show()

# Place the plot data into a ResultsTable
rt = newPlot.getResultsTable()
Example #8
0
			row=[ str(p[i]) for p in profiles ]
			row=",".join(row)
			f.write(row+"\n")

# Generate a plot
if doPlot:
	from ij.gui import Plot
	from java.awt import Color
	p = Plot('Profiles','Channel #','Intensity')
	p.setSize(640,480)
	maxP = len(profiles)
	maxV = 0
	for iprofile,profile in enumerate(profiles):
		h = 0.66-(float(iprofile)/maxP)
		if h<0:
			h=h+1
		p.setColor(Color.getHSBColor( h,.8,1))
		p.addPoints(range(len(profile)),profile,p.LINE)
	
		maxV_=max(profile)
		if maxV < maxV_:
			maxV = maxV_
	p.setLimits(0,len(profile)-1,0,maxV*1.2)
	p.setLegend("\n".join(names),p.TOP_LEFT|p.LEGEND_TRANSPARENT)
	p.show()
	
	# Save the plot as PNG
	if doSavePlot:
		imp = p.getImagePlus()
		IJ.saveAs(imp,'PNG',file.absolutePath + "_compensationPlot.png")
Example #9
0
from ij.gui import Plot
from math import sin, cos, radians

# title, X label, Y label
plot = Plot("My data", "time", "value")

# Series 1
plot.setColor("blue")
plot.add("circle", [50 + sin(radians(i * 5)) * 50 for i in xrange(100)])

# Series 2
plot.setColor("magenta")
plot.add("diamond", [50 + cos(radians(i * 5)) * 50 for i in xrange(100)])

# Series 3
plot.setColor("black")
plot.add("line", [50 + cos(-1.0 + radians(i * 5)) * 50 for i in xrange(100)])

plot.show()
        else:
            sliceAvgInt[currentSlice - 1] = 0
            sliceAboveZeroNorm[currentSlice - 1] = 0
            sliceExpectedRadNorm[currentSlice - 1] = 0

print("writing to file...")

# Find
thisStr = IJ.getDirectory("image")
upStr = thisStr[:thisStr.find("merged_videos/")]
rezPath = upStr + "blink_files/result_new.txt"

myfile = open(rezPath, 'w')
for i in range(len(slicesIdx)):
    myfile.write(
        str(slicesIdx[i]) + " " + str(sliceAvgInt[i]) + " " +
        str(sliceAboveZeroNorm[i]) + " " + str(sliceExpectedRadNorm[i]) + "\n")
myfile.close()

print("plotting...")

plot = Plot("Title", "X", "Y")
plot.setLimits(1.0, img2.getNSlices(), 0.0, 1.0)
plot.setColor(Color.RED)
plot.addPoints(slicesIdx, sliceAvgInt, Plot.CROSS)
plot.setColor(Color.BLUE)
plot.addPoints(slicesIdx, sliceAboveZeroNorm, Plot.CROSS)
plot.setColor(Color.GREEN)
plot.addPoints(slicesIdx, sliceExpectedRadNorm, Plot.CROSS)
plot.show()
Example #11
0
def plots(values, timelist, Cell_number, value_type, Stim_List, dirs, parameters):
    """ Plots all calculated values, saves plots to generated directory, returns plot scale. """

    Mean_plot = 0
    # Flatten nested lists (normalized lists are not nested).
    if value_type == "Normalized aFRET mean":    
        values_concat = [ values[i:i+Cell_number] for i in range(0, (len(values)), Cell_number) ]
        Mean_sd = [ standard_deviation(values_concat[i]) for i in range(len(values_concat)) ]
        Mean_sd = [item for sublist in Mean_sd for item in sublist]
        Mean_plot = 1
    elif value_type == "Normalized dFRET mean":
        values_concat = [ values[i:i+Cell_number] for i in range(0, (len(values)), Cell_number) ]
        Mean_sd = [ standard_deviation(values_concat[i]) for i in range(len(values_concat)) ]
        Mean_sd = [item for sublist in Mean_sd for item in sublist]
        Mean_plot = 1

    else:
        if "Normalized" not in value_type:
            values = [item for sublist in values for item in sublist]

    #Repeats list items x cell_number (match timepoints with # of cells).
    timelist = [x for item in timelist for x in repeat(item, Cell_number)]

    # Scaling of plots.
    max_Y = 1
    if max(values) > 3:
        if not isinstance(values[0], list):
            max_Y = max(values)*1.3
    elif max(values) > 2.5:
        max_Y = 3.3
    elif max(values) > 2:
        max_Y = 2.7
    elif max(values) > 1.5:
        max_Y = 2.2
    elif max(values) > 1.3:
        max_Y = 1.7
    elif max(values) > 1:
        max_Y = 1.4


    min_Y = 0
    if min(values) > 2:
        min_Y = min(values)*0.8
    elif min(values) > 1.5:
        min_Y = 1.5
    elif min(values) > 1:
        min_Y = 1
    elif min(values) > 0.5: 
        min_Y = 0.2
                    
    elif min(values) < -0.5:
        min_Y = min(values)*1.3
    elif min(values) < -0.2:
        min_Y = -0.3
    elif min(values) < -0.1:
        min_Y = -0.15
    elif min(values) < -0.08:
        min_Y = -0.1
    elif min(values) < -0.05:
        min_Y = -0.08
    elif min(values) < -0.01:
        min_Y = -0.06

    # Scaling of normalized plots..
    if "Normalized" in value_type:
        min_Y, max_Y = float(parameters["p_min_n"]), float(parameters["p_max_n"])

    if value_type == "dFRET":
        max_Y = float(parameters["p_max"])
        min_y = float(parameters["p_min"])
    elif value_type =="aFRET":
        max_Y = float(parameters["p_max"])
        min_y = float(parameters["p_min"])

    # Call plot, set scale.
    plot = Plot(Title, "Time (minutes)", value_type)
    if len(timelist) > 1:      
        plot.setLimits(min(timelist), max(timelist), min_Y, max_Y)
    else:
        plot.setLimits(-1, 1, min_Y, max_Y)
    # Retrieve colors.
    Colors, Colors_old = colorlist()

    # Set colors, plot points.
    if Mean_plot == 0:
        for i in range(Cell_number):
            if i < 19:
                plot.setColor(Color(*Colors[i][0:3]))
            elif i >= 19:
                plot.setColor(eval(Colors_old[i]))
                print "Out of fancy colors, using java.awt.color defaults"
            elif i > 28:
                print "29 color limit exceeded"
                return
                    
            plot.setLineWidth(1.5)
            plot.addPoints(timelist[i :: Cell_number], values[i :: Cell_number], Plot.LINE)
            plot.setLineWidth(1)

            # Comment in to define color + fillcolor for circles.
            plot.setColor(Color(*Colors[i][0:3]), Color(*Colors[i][0:3]))
            #plot.addPoints(timelist[i :: Cell_number], values[i :: Cell_number], Plot.CIRCLE)
    else:
        min_Y, max_Y = 0.6, 1.6
        if len(timelist) > 1:
            plot.setLimits(min(timelist), max(timelist), min_Y, max_Y)
        else: 
            plot.setLimits(-1, 1, min_Y, max_Y)
        plot.setColor("Color.BLACK")
        plot.setLineWidth(1.5)
        plot.addPoints(timelist[0 :: Cell_number], Mean_sd[0::2], Plot.LINE)
        plot.setLineWidth(1)
        plot.setColor("Color.BLACK", "Color.BLACK")
        plot.addPoints(timelist[0 :: Cell_number], Mean_sd[0::2], Plot.CIRCLE)
        plot.setColor(Color(*Colors[6][0:3]))
        plot.addErrorBars(Mean_sd[1::2])

    # Get's stim name from input.
    if not Stim_List == False:
        text = [ sublist[i] for sublist in Stim_List for i in range(len(Stim_List)) ]
        Stim_List = [ sublist[1:] for sublist in Stim_List ]

        # Plot stimulation markers. 
        plot.setLineWidth(2)
        for sublist in Stim_List:
           plot.setColor("Color.GRAY")
           plot.drawLine(sublist[0], min_Y+((max_Y-min_Y) * 0.82), sublist[1], min_Y+((max_Y-min_Y) * 0.82))
           plot.drawDottedLine(sublist[0], min_Y+((max_Y-min_Y) * 0.82), sublist[0], -1, 4)
           plot.drawDottedLine(sublist[1], min_Y+((max_Y-min_Y) * 0.82), sublist[1], -1, 4)
           plot.setFont(Font.BOLD, 16)
           plot.addText(text[0], sublist[0], min_Y+((max_Y-min_Y) * 0.82))

    cell_num = 0
    if "concentration" not in value_type:
        testfile = open(os.path.join(dirs["Tables"], value_type + ".txt"), "w")
        data = plot.getResultsTable()
        headings = data.getHeadings()
        datadict = {}
        for heading in headings:         
            index = data.getColumnIndex(heading)
            if "Y" in heading:
                column = { "Cell "+str(cell_num).zfill(2) : [round(float(i), 4) for i in data.getColumn(index)] }
            elif "X" in heading:
                column = {"X" : [round(float(i), 4) for i in data.getColumn(index)] }
            cell_num += 1
            datadict.update(column)

        sorted_data = []
        for row in zip(*([key] + value for key, value in sorted(datadict.items()))):
            sorted_data.append(row)

        testfile.write("\t\t".join(sorted_data[0]))

        # Prints output in columns, copy paste directly to sigma/prisma/excel etc.
        for cell in range (1, len(sorted_data), 1):
            testfile.write("\n")
            for times in range(len(sorted_data[cell])):
                testfile.write(str(sorted_data[cell][times]) + "\t\t")  

        # Dumps sorted data to JSON format, for use in eg. matplotlib.
        with open(os.path.join(dirs["Tables"], value_type + ".json"), "w") as outfile:
            datadict["Stim"] = Stim_List
            json.dump(datadict, outfile, sort_keys=True)
        
        testfile.close()


    # Generate High-res plot with anti-aliasing (Scale x 1). 
    plot = plot.makeHighResolution(Title, 1, True, True)    
    #PlotWindow.noGridLines = True

    # Save plot with appropriate title.
    IJ.saveAs(plot, "PNG", os.path.join(dirs["Plots"], str(Title)+str(value_type)))

    # (For ratiometric image-generator)
    return max_Y, min_Y
param_values = fitter.getParams()
IJ.log( fitter.getResultString() )
  
# Overlay fit curve, with oversampling (for plot)
xfit = [ (t / 10.0  + bleach_frame) * frame_interval for t in range(10 * len(xtofit) ) ]
yfit = []
for xt in xfit:
    yfit.append( fitter.f( fitter.getParams(), xt - xfit[0]) )
 
  
plot = Plot("Normalized FRAP curve for " + current_imp.getTitle(), "Time ("+time_units+')', "NU", [], [])
plot.setLimits(0, max(x), 0, 1.5 );
plot.setLineWidth(2)
 
 
plot.setColor(Color.BLACK)
plot.addPoints(x, y, Plot.LINE)
plot.addPoints(x,y,PlotWindow.X);
 
  
plot.setColor(Color.RED)
plot.addPoints(xfit, yfit, Plot.LINE)
 
plot.setColor(Color.black);
plot_window =  plot.show()
 
 
# Output FRAP parameters
thalf = math.log(2) / param_values[1]
mobile_fraction = param_values[0]
 
Example #13
0
from ij.gui import Plot
from math import sin, radians
plot = Plot("My data", "time", "value")
plot.setColor("blue")
plot.add("circle", [sin(radians(i)) for i in xrange(1000)])
plot.show()
Example #14
0
    # Store the measurement in the list
    intensities.append(mean)

IJ.log('For image ' + current_imp.getTitle())
IJ.log('Time interval is ' + str(frame_interval) + ' ' + time_units)

# Build plot
x = [i * frame_interval for i in range(n_slices)]
y = intensities

plot = Plot("Backgrouncurve " + current_imp.getTitle(),
            "Time (" + time_units + ')', "NU", [], [])
plot.setLimits(0, max(x), 0, max(y))
plot.setLineWidth(2)

plot.setColor(Color.BLACK)
plot.addPoints(x, y, Plot.LINE)
plot.addPoints(x, y, PlotWindow.X)

plot.setColor(Color.black)
plot_window = plot.show()

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

# Save data as a json file

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

# Ask for filename
savename_temp = os.path.splitext(stack_title)[0] + '_cell_XX'
save_file = SaveDialog('Please choose a location to save results', file_dir,