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
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
#show progress! IJ.showProgress(i, size+1) #find the mean using the getMean function, then append it to the list mean = getMean(ip, imp) means.append(mean) IJ.showProgress(1) IJ.resetMinAndMax() #set up the variables for plotting and then plot! x = xrange(1, size + 1) y = means plot = Plot("Illumination intensity stability (" + path.basename(stackpath) + ")", "Frame", "Mean frame intensity", [], []) plot.setLineWidth(1) #plot.setColor(Color.BLACK) plot.addPoints(x, y, Plot.LINE) plot_window = plot.show() def stdev(s): avg = sum(s)*1.0/len(s) variance = map(lambda x: (x-avg)**2, s) return math.sqrt(average(variance)) def average(x): average = sum(x)*1.0/len(x) return average IJ.log("Results for " + path.basename(stackpath) + ":")
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()
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()
levels = zPlot.getYValues() # 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
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
fitter = CurveFitter(xtofit, ytofit) fitter.doFit(CurveFitter.EXP_RECOVERY_NOOFFSET) IJ.log("Fit FRAP curve by " + fitter.getFormula() ) 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