Ejemplo n.º 1
0
def plotConstantDisplacementHistogram(df,source='diff', nbins=None, measurementName="", nmPerPx=1, figure=None, axes=None, **kwargs):
    titlesDict = {'diff': 'differential','mp': 'moving peak', 'ref': 'reference peak'}
    
    if not figure:    
        figure = _plt.figure('Position histogram: %s (%s)' % (titlesDict[source], measurementName))
    if not axes:
        axes = _plt.subplot(111)
    histogramKwargs = {'facecolor':'green', 'alpha':0.5,'normed': True}
    
    if (source == 'diff'):
        displacementValues = df.displacement
        
    elif (source == 'mp'):
        displacementValues = df.displacement_mp
        
    elif (source == 'ref'):
        displacementValues = df.displacement_ref
    
    if not nbins:
        nbins = int(round(_np.sqrt(len(displacementValues))))
    
    _plt.hist(displacementValues,bins=nbins,**histogramKwargs)
    
    sd = _ODMStats.makeStatsDescriptionDict(displacementValues * nmPerPx)
    peakDistanceToEdge = [abs(sd['mean']-x*nmPerPx) for x in axes.get_xlim()]
    xtext = 0.1 if peakDistanceToEdge[0] > peakDistanceToEdge[1] else 0.7
        
    _plt.text(xtext,0.7,_ODMStats.printStatsDescriptionDict(sd),transform=axes.transAxes)
    _plt.xlabel('position (px)')
    ty = axes.twiny()
    ty.set_xlabel('position (nm)')
    ty.set_xlim(nmPerPx * px for px in axes.get_xlim())

    
    def save(path):
        figure.savefig(path,dpi=200)
    
    return figure, axes, save
def main():
    if len(sys.argv) > 1 and os.path.exists(sys.argv[1]) and os.path.isfile(sys.argv[1]):
        filename = sys.argv[1]
    else:
        filename = gui.get_path("*.csv", defaultFile="odmanalysis.csv")

    commonPath = os.path.abspath(os.path.split(filename)[0])

    try:
        settings = odm.CurveFitSettings.loadFromFile(commonPath + "/odmSettings.ini")
        print "settings loaded from local odmSettings.ini"
    except:
        settings = gui.getSettingsFromUser(None)
        settings.saveToFile(commonPath + "/odmSettings.ini")
        print "settings saved to local odmSettings.ini"

    nmPerPx = settings.pxToNm

    df = odm.readAnalysisData(filename)
    plt.plot(np.arange(len(df.displacement)), df.displacement * nmPerPx)

    plt.interactive(False)
    coordinateGrabber = gui.InteractiveCoordinateGrabber(plt.gcf(), 2, "Select range for fitting a polynomial...")
    coordinateGrabber.promptMessages = ["Select lower limit...", "Select upper limit..."]
    coordinates = coordinateGrabber.getValuesFromUser()

    xLimits = [int(c[0]) for c in coordinates]

    dfs = df.iloc[slice(*xLimits)]

    validInput = False
    while validInput == False:
        try:
            deg = int(raw_input("Polynomial degree: "))
            validInput = True
        except:
            pass

    xValues = np.arange(len(dfs.displacement))
    p = cp.polyfit(xValues, dfs.displacement, deg)
    noise = (dfs.displacement - cp.polyval(p, xValues)) * nmPerPx

    ax = plt.subplot(111)
    ax.plot(xValues, dfs.displacement * nmPerPx)
    ax.plot(xValues, cp.polyval(p, xValues) * nmPerPx, "r--")
    ax.set_xlabel("Actuator Voltage (V)")
    ax.set_ylabel("Displacement (nm)")

    fig, (ax1, ax2) = plt.subplots(nrows=1, ncols=2, sharex=False, sharey=True, squeeze=True)
    ax1.plot(np.arange(len(noise)), noise, "o")
    ax2.hist(noise, bins=50, orientation="horizontal", facecolor="green", alpha=0.5)

    sd = ODMStats.makeStatsDescriptionDict(nmPerPx * dfs.displacement)
    peakDistanceToEdge = [abs(sd["mean"] - x * nmPerPx) for x in ax2.get_xlim()]
    xtext = 0.1 if peakDistanceToEdge[0] > peakDistanceToEdge[1] else 0.7
    ax2.text(xtext, 0.7, ODMStats.printStatsDescriptionDict(sd), transform=ax2.transAxes)

    ax1.set_ylabel("Displacement (nm)")
    ax2.set_xlabel("Count")
    fig.savefig(os.path.join(commonPath, "Displacement noise.png"), dpi=150)

    stats = noise.describe()
    with open(os.path.join(commonPath, "position_noise_stats.txt"), "w") as f:
        f.write(str(stats))

    plt.show()