示例#1
0
def processTrajectories(fileName):
    """
    处理弹道数据,输出图形。
    :param fileName:
    :return: None,显示图形,用一次和二次多项式拟合弹道轨迹。
    """
    distances, heights = getTrajectoryData(fileName)
    numTrials = len(heights)
    distances = pylab.array(distances)
    #生成一个数组,用于存储每个距离的高度,并计算平均值
    totHeights = pylab.array([0] * len(distances))
    for h in heights:
        totHeights = totHeights + pylab.array(h)
    meanHeights = totHeights / len(heights)
    # 绘图
    title = 'Trajectory of Projectile (Mean of ' + str(numTrials) + ' Trials)'
    pylab.figure(title)
    pylab.title(title)
    pylab.xlabel('Inches from Launch Point')
    pylab.ylabel('Inches Above Launch Point')
    pylab.plot(distances, meanHeights, 'ko')
    fit = pylab.polyfit(distances, meanHeights, 1)
    altitudes = pylab.polyval(fit, distances)
    pylab.plot(distances, altitudes, 'b', label='Linear Fit')
    print('RSquare of linear fit =', rSquared(meanHeights, altitudes))
    fit = pylab.polyfit(distances, meanHeights, 2)
    # 用实验数据对应的点位distances来绘图,导致点少的区域上,曲线不够平滑。
    altitudes = pylab.polyval(fit, distances)
    pylab.plot(distances, altitudes, 'k:', label='Quadratic Fit')
    print('RSquare of quadratic fit =', rSquared(meanHeights, altitudes))
    pylab.legend()
    # 计算落地时的水平速度,打印输出。
    getHorizontalSpeed(fit, distances[-1], distances[0])
示例#2
0
def plotPopulations(numSteps):
    """ Plots populations of Foxes & Rabbits for given timesteps. """
    rab_pop, fox_pop = runSimulation(numSteps)
    # for i in range(len(rab_pop)):
    #     print(rab_pop[i], fox_pop[i])

    r_style = 'bo'  # blue - continuous line
    f_style = 'ro'  # red  - continuous line

    pylab.figure('Fox / Rabit Populations')

    pylab.plot(rab_pop, r_style, label='Rabbit Pop')
    pylab.plot(fox_pop, f_style, label='Fox Pop')

    pylab.title('Fox / Rabit Populations: {} timesteps'.format(numSteps))
    pylab.xlabel('Time Steps')
    pylab.ylabel('Population')
    pylab.legend(loc='best')

    degree = 2
    rab_coeff = pylab.polyfit(range(len(rab_pop)), rab_pop, degree)
    pylab.plot(pylab.polyval(rab_coeff, range(len(rab_pop))), 'b-')
    fox_coeff = pylab.polyfit(range(len(fox_pop)), fox_pop, degree)
    pylab.plot(pylab.polyval(fox_coeff, range(len(fox_pop))), 'r-')

    pylab.show()
def evaluate_models_on_training(x, y, models):
    """
    For each regression model, compute the R-square for this model with the
    standard error over slope of a linear regression line (only if the model is
    linear), and plot the data along with the best fit curve.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        R-square of your model evaluated on the given data points
    Args:
        x: a list of length N, representing the x-coords of N sample points
        y: a list of length N, representing the y-coords of N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a numpy array storing the coefficients of
            a polynomial.
    Returns:
        None
    """
    r_sqr=0
    for model in models:
        if r_squared(y,pylab.polyval(model,x)) > r_sqr :
            r_sqr=r_squared(y,pylab.polyval(model,x))
            best=model
            
    EST_values= pylab.polyval(best,x)
    pylab.plot(x,y,'bo',label='points')
    pylab.plot(x,EST_values,'r',label='linear fit , R^2 = '+str(round(r_squared(y,EST_values),5)))
    pylab.legend(loc='best')
    pylab.show()    
示例#4
0
文件: misc.py 项目: MMaus/mutils
def getApices(y):
    """ 
    returns the time (in frames) and position of initial and final apex
    height from a given trajectory y, which are obtained by fitting a cubic
    spline 
    
    ==========
    parameter:
    ==========
    y : *array* (1D)
        the trajectory. Should ideally start ~1 frame before an apex and end ~1
        frame behind an apex

    ========
    returns:
    ========

    [x0, xF], [y0, yF] : location (in frames) and value of the first and final
    apices

    """
    # the math behind here is: fitting a 2nd order polynomial and finding
    # the root of its derivative. Here, only the results are applied, that's
    # why it appears like "magic" numbers
    c = dot(array([[.5, -1, .5], [-1.5, 2., -.5], [1., 0., 0.]]), y[:3])
    x0 = -1. * c[1] / (2. * c[0])
    y0 = polyval(c, x0)

    c = dot(array([[.5, -1, .5], [-1.5, 2., -.5], [1., 0., 0.]]), y[-3:])
    xF = -1. * c[1] / (2. * c[0])
    yF = polyval(c, xF)
    xF += len(y) - 3

    return [x0, xF], [y0, yF]
示例#5
0
def plotPopulations(numSteps):
    """ Plots populations of Foxes & Rabbits for given timesteps. """
    rab_pop, fox_pop = runSimulation(numSteps)
    # for i in range(len(rab_pop)):
    #     print(rab_pop[i], fox_pop[i])

    r_style = 'bo'    # blue - continuous line
    f_style = 'ro'    # red  - continuous line

    pylab.figure('Fox / Rabit Populations')

    pylab.plot(rab_pop, r_style, label='Rabbit Pop')
    pylab.plot(fox_pop, f_style, label='Fox Pop')

    pylab.title('Fox / Rabit Populations: {} timesteps'.format(numSteps))
    pylab.xlabel('Time Steps')
    pylab.ylabel('Population')
    pylab.legend(loc='best')

    degree = 2
    rab_coeff = pylab.polyfit(range(len(rab_pop)), rab_pop, degree)
    pylab.plot(pylab.polyval(rab_coeff, range(len(rab_pop))), 'b-')
    fox_coeff = pylab.polyfit(range(len(fox_pop)), fox_pop, degree)
    pylab.plot(pylab.polyval(fox_coeff, range(len(fox_pop))), 'r-')

    pylab.show()
 def fitData(fileName):
     xVals, yVals = getData(fileName)
     xVals = pylab.array(xVals)
     yVals = pylab.array(yVals)
     xVals = xVals * 9.81  #get force
     pylab.plot(xVals, yVals, 'bo', label='Measured points')
     model = pylab.polyfit(xVals, yVals, 1)
     xVals = xVals + [2]
     yVals = yVals + []
     estYVals = pylab.polyval(model, xVals)
     pylab.plot(xVals,
                estYVals,
                'r',
                label='Linear fit, r**2 = ' +
                str(round(rSquared(yVals, estYVals), 5)))
     model = pylab.polyfit(xVals, yVals, 2)
     estYVals = pylab.polyval(model, xVals)
     pylab.plot(xVals,
                estYVals,
                'g--',
                label='Quadratic fit, r**2 = ' +
                str(round(rSquared(yVals, estYVals), 5)))
     pylab.title('A Linear Spring')
     labelPlot()
     pylab.legend(loc='best')
示例#7
0
def fitData(inputFile):
    masses, distances = getData(inputFile)
    distances = pylab.array(distances)
    forces = pylab.array(masses) * 9.81
    pylab.plot(forces, distances, 'ko', label='Measured displacements')
    pylab.title('Measured displacement of spring')
    pylab.xlabel('|Force| (Newtons)')
    pylab.ylabel('Distances (meters)')

    a, b = pylab.polyfit(forces, distances, 1)
    k = 1 / a
    predVals = pylab.polyval((a, b), forces)
    pylab.plot(forces,
               predVals,
               label='Displacements predicted by \nlinear fit, k = ' +
               str(round(k, 5)))
    forces2 = numpy.append(forces, [1.5 * 9.81])
    fitAll = pylab.polyfit(forces, distances, 3)
    k2 = 1 / fitAll[0]
    cubePredVals = pylab.polyval(fitAll, forces2)
    pylab.plot(forces2,
               cubePredVals,
               'k:',
               label='Displacements predicted by \nlinear fit, k = ' +
               str(round(k2, 5)))
    pylab.legend(loc='best')
示例#8
0
def runSimulation(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the 
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """
    rabbits = []
    foxes = []
    for i in range(numSteps):
        rabbitGrowth()
        foxGrowth()
        rabbits.append(CURRENTRABBITPOP)
        foxes.append(CURRENTFOXPOP)
    pylab.plot(rabbits, label='rabbits')
    pylab.plot(foxes, label='foxes')
    pylab.legend(loc='upper center')
    coeff1 = pylab.polyfit(range(len(rabbits)), rabbits, 2)
    pylab.plot(pylab.polyval(coeff1, range(len(rabbits))))
    coeff2 = pylab.polyfit(range(len(foxes)), foxes, 2)
    pylab.plot(pylab.polyval(coeff2, range(len(foxes))))
    pylab.show
    return rabbits, foxes
示例#9
0
def equil():


    eq_m = -0.0001
    rise_rate = 0.0125
    mag = 20
    ts = linspace(0, 400, 500)
    f = F(ts, mag=mag)
#     g = eq_m * f
    g = G(ts, f, rate=eq_m)
    b = rise_rate * ts

    fg = f + g + b
    plot(ts, f, label='F Equilibration')
    plot(ts, g, label='G Consumption')
    plot(ts, fg, label='F-G (Sniff Evo)')

    rf, rollover_F, vi_F = calc_optimal_eqtime(ts, f)
    rfg, rollover_FG, vi_FG = calc_optimal_eqtime(ts, fg)
    m = 2 * eq_m * mag

    axvline(x=rollover_F, ls='--', color='blue')
    axvline(x=rollover_FG, ls='--', color='red')

    idx = list(ts).index(rollover_F)

    b = fg[idx] - m * rollover_F
    evo = polyval((m, b), ts)
    plot(ts, evo, ls='-.', color='blue', label='Static Evo. A')
    # ee = where(evo > mag)[0]
    # to_F = ts[max(ee)]
    # print 'F', rollover_F, b, to_F


    b = vi_FG - m * rollover_FG
    evo = polyval((m, b), ts)
    plot(ts, evo, ls='-.', color='red', label='Static Evo. B')

    print polyval((m, b), 200)
    ee = where(evo > mag)[0]
#     to_FG = ts[max(ee)]
#     print 'FG', rollover_FG, b, to_FG

#     axvline(x=to_FG, ls='-', color='red')
#     axvline(x=to_F, ls='-', color='blue')

    axhline(y=mag, ls='-', color='black')
#    plot([ti], [mag], 'bo')

    legend(loc=0)
#     ylim(2980, 3020)
    ylim(18, 21)
    xlim(0, 20)
    ylabel('Intensity')
    xlabel('t (s)')
#    fig = gcf()
#    fig.text(0.1, 0.01, 'asdfasfasfsadfsdaf')


    show()
示例#10
0
文件: problem3.py 项目: franzip/edx
def plotFittingCurve(rabbits, foxes):
    r_coeff = pylab.polyfit(range(len(rabbits)), rabbits, 2) 
    f_coeff = pylab.polyfit(range(len(foxes)), foxes, 2)
    pylab.plot(pylab.polyval(r_coeff, range(len(rabbits))), label = "Rabbits Curve")
    pylab.plot(pylab.polyval(f_coeff, range(len(foxes))), label = "Foxes Curve")
    pylab.legend()
    pylab.show()
示例#11
0
def runSimulation(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the 
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """
    
    rabbitPop = []
    foxPop = []
    for i in range(numSteps):
        rabbitGrowth()
        foxGrowth()
        rabbitPop.append(CURRENTRABBITPOP)
        foxPop.append(CURRENTFOXPOP)
    #return (rabbitPop,foxPop)
    pylab.plot(rabbitPop)
    pylab.plot(foxPop)
    pylab.show()
    rabbitPopulationOverTime = rabbitPop[:]
    coeff = pylab.polyfit(range(len(rabbitPopulationOverTime)), rabbitPopulationOverTime, 2)
    pylab.plot(pylab.polyval(coeff, range(len(rabbitPopulationOverTime))))
    pylab.show()
    rabbitPopulationOverTime = foxPop[:]
    coeff = pylab.polyfit(range(len(rabbitPopulationOverTime)), rabbitPopulationOverTime, 2)
    pylab.plot(pylab.polyval(coeff, range(len(rabbitPopulationOverTime))))
    pylab.show()
示例#12
0
def evaluate_models_on_training(x, y, models):
    """
    For each regression model, compute the R-square for this model with the
    standard error over slope of a linear regression line (only if the model is
    linear), and plot the data along with the best fit curve.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        R-square of your model evaluated on the given data points
    Args:
        x: a list of length N, representing the x-coords of N sample points
        y: a list of length N, representing the y-coords of N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a numpy array storing the coefficients of
            a polynomial.
    Returns:
        None
    """
    pyplot.plot(x, y, 'bo')
    for i in models:
        pyplot.plot(x,
                    pylab.polyval(i, x),
                    label='R^2 = ' + str(r_squared(y, pylab.polyval(i, x))))
    pylab.title('Year vs Temp.')
    pylab.legend(loc='best')
    pylab.xlabel('Year')
    pylab.ylabel('Temperature')
示例#13
0
def fitData(inputFile):
    masses, distances = getData(inputFile)
    distances = pylab.array(distances)
    masses = pylab.array(masses)
    forces = pylab.array(masses) * 9.81
    pylab.plot(forces, distances, 'ko', label="Measurement Displacements")
    pylab.title("Measured Displacement of Spring")
    pylab.xlabel("|Force| (Newtons)")
    pylab.ylabel("Distance (Meters)")
    # find linear fit
    a, b = pylab.polyfit(forces, distances, 1)
    predictedDistances = a * pylab.array(forces) + b
    k = 1.0 / a  # a is dDist/dForce, k is dForce/dDist or a inverse
    pylab.plot(forces,
               predictedDistances,
               label="Displacements Predicted by \nLinear Fit, k = " +
               str(round(k, 5)))
    pylab.legend(loc='best')
    # find cubic fit
    fit = pylab.polyfit(forces, distances, 3)
    predictedDistances = pylab.polyval(fit, forces)
    forces_extend = pylab.append(forces, pylab.array([15]))
    predicted_distances_extend = pylab.polyval(fit, forces_extend)
    pylab.plot(forces_extend,
               predicted_distances_extend,
               'k:',
               label='cubic fit')
    pylab.xlim(0, 16)
示例#14
0
def equil():


    eq_m = -0.0001
    rise_rate = 0.0125
    mag = 20
    ts = linspace(0, 400, 500)
    f = F(ts, mag=mag)
#     g = eq_m * f
    g = G(ts, f, rate=eq_m)
    b = rise_rate * ts

    fg = f + g + b
    plot(ts, f, label='F Equilibration')
    plot(ts, g, label='G Consumption')
    plot(ts, fg, label='F-G (Sniff Evo)')

    rf, rollover_F, vi_F = calc_optimal_eqtime(ts, f)
    rfg, rollover_FG, vi_FG = calc_optimal_eqtime(ts, fg)
    m = 2 * eq_m * mag

    axvline(x=rollover_F, ls='--', color='blue')
    axvline(x=rollover_FG, ls='--', color='red')

    idx = list(ts).index(rollover_F)

    b = fg[idx] - m * rollover_F
    evo = polyval((m, b), ts)
    plot(ts, evo, ls='-.', color='blue', label='Static Evo. A')
    # ee = where(evo > mag)[0]
    # to_F = ts[max(ee)]
    # print 'F', rollover_F, b, to_F


    b = vi_FG - m * rollover_FG
    evo = polyval((m, b), ts)
    plot(ts, evo, ls='-.', color='red', label='Static Evo. B')

    print polyval((m, b), 200)
    ee = where(evo > mag)[0]
#     to_FG = ts[max(ee)]
#     print 'FG', rollover_FG, b, to_FG

#     axvline(x=to_FG, ls='-', color='red')
#     axvline(x=to_F, ls='-', color='blue')

    axhline(y=mag, ls='-', color='black')
#    plot([ti], [mag], 'bo')

    legend(loc=0)
#     ylim(2980, 3020)
    ylim(18, 21)
    xlim(0, 20)
    ylabel('Intensity')
    xlabel('t (s)')
#    fig = gcf()
#    fig.text(0.1, 0.01, 'asdfasfasfsadfsdaf')


    show()
示例#15
0
def runSimulation2(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """

    rabbitPopulationOverTime = []
    foxPopulationOverTime = []
    for step in range(numSteps):
        rabbitGrowth()
        rabbitPopulationOverTime.append(CURRENTRABBITPOP)
        foxGrowth()
        foxPopulationOverTime.append(CURRENTFOXPOP)
    print "CURRENTRABBITPOP", CURRENTRABBITPOP, rabbitPopulationOverTime
    print "CURRENTFOXPOP", CURRENTFOXPOP, foxPopulationOverTime
    pylab.plot(range(numSteps), rabbitPopulationOverTime, '-g', label='Rabbit population')
    pylab.plot(range(numSteps), foxPopulationOverTime, '-o', label='Fox population')
    rabbit_coeff = pylab.polyfit(range(len(rabbitPopulationOverTime)), rabbitPopulationOverTime, 2)
    pylab.plot(pylab.polyval(rabbit_coeff, range(len(rabbitPopulationOverTime))))
    fox_coeff = pylab.polyfit(range(len(foxPopulationOverTime)), foxPopulationOverTime, 2)
    pylab.plot(pylab.polyval(fox_coeff, range(len(rabbitPopulationOverTime))))
    pylab.title('Fox and rabbit population in the wood')
    xlabel = "Plot for simulation of {} steps".format(numSteps)
    pylab.xlabel(xlabel)
    pylab.ylabel('Current fox and rabbit population')
    pylab.legend(loc='upper right')
    pylab.tight_layout()
    pylab.show()
    pylab.clf()
示例#16
0
文件: Final.py 项目: mai1346/600.2x
def runSimulation(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the 
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """
    rabbit,fox=[],[]
    for i in range(numSteps):
        rabbitGrowth()
        foxGrowth()
        rabbit.append(CURRENTRABBITPOP)
        fox.append(CURRENTFOXPOP)
    pylab.plot(rabbit)
    pylab.plot(fox)
    coeffr = pylab.polyfit(range(len(rabbit)), rabbit, 2)
    pylab.plot(pylab.polyval(coeffr, range(len(rabbit))),label='rabbit')
    coefff = pylab.polyfit(range(len(fox)), fox, 2)
    pylab.plot(pylab.polyval(coefff, range(len(fox))),label='fox') 
    pylab.legend()
    return rabbit,fox
示例#17
0
文件: misc.py 项目: MMaus/mutils
def getApices(y):
    """ 
    returns the time (in frames) and position of initial and final apex
    height from a given trajectory y, which are obtained by fitting a cubic
    spline 
    
    ==========
    parameter:
    ==========
    y : *array* (1D)
        the trajectory. Should ideally start ~1 frame before an apex and end ~1
        frame behind an apex

    ========
    returns:
    ========

    [x0, xF], [y0, yF] : location (in frames) and value of the first and final
    apices

    """
    # the math behind here is: fitting a 2nd order polynomial and finding 
    # the root of its derivative. Here, only the results are applied, that's
    # why it appears like "magic" numbers
    c = dot(array([[.5, -1, .5], [-1.5, 2., -.5], [1., 0., 0.]]), y[:3])
    x0 = -1. * c[1] / (2. * c[0])
    y0 = polyval(c, x0)

    c = dot(array([[.5, -1, .5], [-1.5, 2., -.5], [1., 0., 0.]]), y[-3:])
    xF = -1. * c[1] / (2. * c[0])
    yF = polyval(c, xF)
    xF += len(y) - 3

    return [x0, xF], [y0, yF]
示例#18
0
def runSimulation(numSteps):
    """
    Runs the simulation for `numSteps` time steps.

    Returns a tuple of two lists: (rabbit_populations, fox_populations)
      where rabbit_populations is a record of the rabbit population at the 
      END of each time step, and fox_populations is a record of the fox population
      at the END of each time step.

    Both lists should be `numSteps` items long.
    """
    foxpop = []
    rabbitpop = []
    for i in range(numSteps):
        rabbitGrowth()
        foxGrowth()
        rabbitpop.append(CURRENTRABBITPOP)
        foxpop.append(CURRENTFOXPOP)
        pylab.plot(rabbitpop, 'b')
        pylab.plot(foxpop, 'r')
    rabbit_coeff = pylab.polyfit(range(len(rabbitpop)), rabbitpop, 2)
    pylab.plot(pylab.polyval(rabbit_coeff, range(len(rabbitpop))))
    fox_coeff = pylab.polyfit(range(len(foxpop)), foxpop, 2)
    pylab.plot(pylab.polyval(fox_coeff, range(len(foxpop))))
    pylab.show()
    return rabbitpop, foxpop
示例#19
0
def evaluate_models_on_testing(x, y, models):
    """
    For each regression model, compute the RMSE for this model and plot the
    test data along with the model’s estimation.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        RMSE of your model evaluated on the given data points. 

    Args:
        x: an 1-d pylab array with length N, representing the x-coordinates of
            the N sample points
        y: an 1-d pylab array with length N, representing the y-coordinates of
            the N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a pylab array storing the coefficients of
            a polynomial.

    Returns:
        None
    """
    for model in models:
        estimates=pylab.polyval(model,x)
        pylab.plot(x,y,'o',markersize=6)
        #xmin=1961
        #xmax=2010
        pylab.plot(x, estimates,'r-')        
        pylab.title('Model with RMSE = ' + str(rmse(y,pylab.polyval(model,x))) + '\n' + ' degrees = ' + str(len(model)-1) )            
        pylab.xlabel('year')
        pylab.ylabel('degrees Celsius')
        pylab.show()
示例#20
0
def processTrajectories(fileName):
    distances, heights = getTrajectoryData(fileName)
    numTrials = len(heights)
    distances = pylab.array(distances)
    # Get array containing mean height at each distance
    totHeights = pylab.array([0] * len(distances))
    for h in heights:
        totHeights = totHeights + pylab.array(h)
    meanHeights = totHeights / len(heights)

    pylab.title("Trajectory of Projectile (Mean of " + str(numTrials) +
                'Trials)')
    pylab.xlabel("Inches from Launch Point")
    pylab.ylabel("Inches Above Launch Point")
    pylab.plot(distances, meanHeights, 'ko')

    fit = pylab.polyfit(distances, meanHeights, 1)
    altitudes = pylab.polyval(fit, distances)
    pylab.plot(distances, altitudes, 'b', label="Linear Fit")
    print('RSquare of Linear Fit = ', rSquared(meanHeights, altitudes))

    fit = pylab.polyfit(distances, meanHeights, 2)
    altitudes = pylab.polyval(fit, distances)
    pylab.plot(distances, altitudes, 'k:', label="Quadratic Fit")
    print('Rsquare of Quadratic Fit = ', rSquared(meanHeights, altitudes))
    pylab.legend()
    getHorizontalSpeed(fit, distances[-1], distances[0])
示例#21
0
文件: problem3.py 项目: jinjustin/edx
def plotFittingCurve(rabbits, foxes):
    r_coeff = pylab.polyfit(range(len(rabbits)), rabbits, 2)
    f_coeff = pylab.polyfit(range(len(foxes)), foxes, 2)
    pylab.plot(pylab.polyval(r_coeff, range(len(rabbits))),
               label="Rabbits Curve")
    pylab.plot(pylab.polyval(f_coeff, range(len(foxes))), label="Foxes Curve")
    pylab.legend()
    pylab.show()
示例#22
0
def make_joining_whisker(px,py,dist,lthick,lscore,rthick,rscore):
  w = Whisker_Seg()
  tt = linspace(0,1,round(dist))
  w.x = polyval(px,tt).astype(float32)
  w.y = polyval(py,tt).astype(float32) 
  w.thick  = polyval( [rthick-lthick,lthick], tt ).astype(float32) 
  w.scores = polyval( [rscore-lscore,lscore], tt ).astype(float32)  
  return w
示例#23
0
def plotFitSimulation(numSteps):
    ans = runSimulation(numSteps)
    rabbitCoeff = pylab.polyfit(range(numSteps), ans[0], 2)
    foxCoeff = pylab.polyfit(range(numSteps), ans[1], 2)
    print rabbitCoeff, foxCoeff
    pylab.plot(pylab.polyval(rabbitCoeff, range(numSteps)), 'r')
    pylab.plot(pylab.polyval(foxCoeff, range(numSteps)), 'g')
    pylab.title("polyfit result")
    pylab.show()
示例#24
0
def evaluate_models_on_training(x, y, models):
    """
    For each regression model, compute the R-squared value for this model with the
    standard error over slope of a linear regression line (only if the model is
    linear), and plot the data along with the best fit curve.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        R-square of your model evaluated on the given data points,
        and SE/slope (if degree of this model is 1 -- see se_over_slope). 

    Args:
        x: an 1-d pylab array with length N, representing the x-coordinates of
            the N sample points
        y: an 1-d pylab array with length N, representing the y-coordinates of
            the N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a pylab array storing the coefficients of
            a polynomial.

    Returns:
        None
    """
    # TODO
    for m in models:
        if len(m) == 2:
            estimated = pylab.array(pylab.polyval(m, x))
            pylab.scatter(x, y, c="b")
            pylab.plot(x, estimated, c="r")
            pylab.xlabel("years")
            pylab.ylabel("Celsius")
            r = r_squared(y, estimated)
            se_over_slope2 = se_over_slope(x, y, estimated, m)
            pylab.title("For model with degree: " + str(len(m) - 1) + " and " +
                        "with R-square: " + str(r) + "\n" +
                        "The data is linear so ratio of se_over_slope is " +
                        "\n" + str(se_over_slope2))
            pylab.show()
            pylab.pause(15)
            pylab.close()
        else:
            estimated = pylab.array(pylab.polyval(m, x))
            pylab.scatter(x, y, c="b")
            pylab.plot(x, estimated, c="r")
            pylab.xlabel("years")
            pylab.ylabel("Celsius")
            r = r_squared(y, estimated)
            pylab.title("For model with degree: " + str(len(m) - 1) + " and " +
                        "with R-square: " + str(r))
            pylab.show()
            pylab.pause(15)
            pylab.close()
    return None
示例#25
0
def plotSimulation(numSteps):
    rabbits, foxes = runSimulation(numSteps)

    pylab.plot(range(numSteps), rabbits, label='Rabbits')
    rabbit_coefficients = pylab.polyfix(range(len(rabbits)), rabbits, 2)
    pylab.plot(pylab.polyval(rabbit_coefficients, range(numSteps)))
    pylab.plot(range(numSteps), foxes, label='Foxes')
    fox_coefficients = pylab.polyfix(range(len(foxes)), foxes, 2)
    pylab.plot(pylab.polyval(fox_coefficients, range(numSteps)))
    pylab.show()
示例#26
0
def compute_join_curvature( px, py ):
  from scipy.integrate import quad
  xp  = polyder( px, 1 )
  xpp = polyder( px, 2 )
  yp  = polyder( py, 1 )
  ypp = polyder( py, 2 )
  pn = polyadd( polymul( xp, ypp ), polymul( yp, xpp )) #numerator
  pd = polyadd( polymul( xp, xp ) , polymul( yp, yp ) ) #denominator
  integrand = lambda t:  fabs(polyval( pn, t )/( polyval( pd, t )**(1.5)) ) 
  return quad(integrand, 0, 1) [0]
示例#27
0
def plotSimulation():
    rabbits, foxes = runSimulation(200)
    pylab.plot(rabbits, label='Rabbits')
    pylab.plot(foxes, label='Foxes')
    a, b, c = pylab.polyfit(range(len(rabbits)), rabbits, 2)
    pylab.plot(pylab.polyval([a, b, c], range(len(rabbits))), label='Rabbits')
    d, e, f = pylab.polyfit(range(len(foxes)), foxes, 2)
    pylab.plot(pylab.polyval([d, e, f], range(len(foxes))), label='Foxes')
    pylab.grid()
    pylab.legend()
    pylab.show()
示例#28
0
def plot(steps):
    z = runSimulation(steps)
    pylab.plot(range(steps), z[0], label='Rabbits')
    pylab.plot(range(steps), z[1], label='Foxes')
    pylab.xlabel('Time Steps')
    pylab.ylabel('Population')
    Rcoef = pylab.polyfit(range(steps), z[0], 2)
    pylab.plot(range(steps), pylab.polyval(Rcoef, range(steps)), label='Rabz')
    Fcoef = pylab.polyfit(range(steps), z[1], 2)
    pylab.plot(range(steps), pylab.polyval(Fcoef, range(steps)), label='Foxez')
    pylab.legend()
示例#29
0
    def createPlots(data):
        x = data[0]
        y = data[1]

        a, b, c = polyFit(x, y, 2)

        x = pylab.arange(201)
        y = a * x**2 + b * x + c

        print pylab.polyval((a, b, c), 200)
        pylab.plot(x, y)
        pylab.show()
示例#30
0
    def createPlots(data):
        x = data[0]
        y = data[1]

        a,b,c = polyFit(x, y, 2)

        x = pylab.arange(201)
        y = a*x**2 + b*x + c

        print pylab.polyval((a,b,c), 200)
        pylab.plot(x, y)
        pylab.show()
def plotLineFit():
    rabbitPops, foxPops = runSimulation(200)
    steps = [n for n in range(1, 201)]
    coeff = pylab.polyfit(range(len(rabbitPops)), rabbitPops, 2)
    pylab.plot(pylab.polyval(coeff, range(len(rabbitPops))))
    coeff = pylab.polyfit(range(len(foxPops)), foxPops, 2)
    pylab.plot(pylab.polyval(coeff, range(len(foxPops))))
    pylab.title('Fox vs. Rabbit')
    pylab.legend(('Rabbit Pop', 'Fox Pop'))
    pylab.xlabel('Step')
    pylab.ylabel('Population')
    pylab.show()
示例#32
0
def simPlot(numSteps):
    rabbit_populations, fox_populations = runSimulation(numSteps)
    pylab.plot(np.arange(numSteps), rabbit_populations, '-r')
    pylab.plot(np.arange(numSteps), fox_populations, '-b')

    coeff = pylab.polyfit(np.arange(numSteps), rabbit_populations, 2)
    pylab.plot(pylab.polyval(coeff, np.arange(numSteps)))

    coeff = pylab.polyfit(np.arange(numSteps), fox_populations, 2)
    pylab.plot(pylab.polyval(coeff, np.arange(numSteps)))

    pylab.show()
示例#33
0
def plot():
    rp, fp = runSimulation(200)
    rabbitCoeff = pylab.polyfit(range(len(rp)), rp, 2)
    foxCoeff = pylab.polyfit(range(len(fp)), fp, 2)
    pylab.plot(rp, label="rabbit")
    pylab.plot(fp, label="fox")
    pylab.plot(pylab.polyval(rabbitCoeff, range(len(rp))), label="rabbitEst")
    pylab.plot(pylab.polyval(foxCoeff, range(len(fp))), label="foxEst")
    pylab.xlabel("time step")
    pylab.ylabel("population")
    pylab.legend(loc="best")
    pylab.show()
示例#34
0
def plotLineFit():
    rabbitPops, foxPops = runSimulation(200)
    steps = [n for n in range(1, 201)]
    coeff = pylab.polyfit(range(len(rabbitPops)), rabbitPops, 2)
    pylab.plot(pylab.polyval(coeff, range(len(rabbitPops))))
    coeff = pylab.polyfit(range(len(foxPops)), foxPops, 2)
    pylab.plot(pylab.polyval(coeff, range(len(foxPops))))
    pylab.title('Fox vs. Rabbit')
    pylab.legend(('Rabbit Pop', 'Fox Pop'))
    pylab.xlabel('Step')
    pylab.ylabel('Population')
    pylab.show()
示例#35
0
def plot(rabbits, foxes):
    N = len(rabbits)
    pylab.plot(range(N), rabbits, 'go', label = "rabbit pop")
    pylab.plot(range(N), foxes, 'ro', label = "foxes pop")
    rab_coeff = pylab.polyfit(range(N), rabbits, 2)
    fox_coeff = pylab.polyfit(range(N), foxes, 2)
    pylab.plot(pylab.polyval(rab_coeff, range(N)), 'g-', label = "rabbit polyfit")
    pylab.plot(pylab.polyval(fox_coeff, range(N)), 'r-', label = "fox polyfit")
    pylab.xlabel("Time")
    pylab.ylabel("Population")
    pylab.title("Dynamics of Rabbit and Fox Population")
    pylab.legend()
    pylab.show()
示例#36
0
def ddPsi(a,s):
    '''
    # second derivative of polynomial
    # a = polynomical constants (needs to be in list/array form so len() command works)
    # s = position along polynomial (needs to be in list/array form so len() command works)
    '''
    n = len(a) # number of variables in polynimal
    a1 = a[:-1]*(pl.arange(n-1,0,-1)+1)*pl.arange(n-1,0,-1)
    a2 = a*(pl.arange(n-1,-1,-1)+2)*(pl.arange(n-1,-1,-1)+1)
    
    psi = pl.polyval(a1,s) - pl.polyval(a2,s)
   
    return psi
示例#37
0
def fitDataWithBreakFlat(fileName):
    xValsBase, yValsBase = getData(fileName)
    bestFitSoFar = None
    bestFitBreak = None
    for br in range(3, len(xValsBase) - 3):
        xValsLow = pylab.array(xValsBase[:br])
        xValsHigh = pylab.array(xValsBase[br:])
        yValsLow = pylab.array(yValsBase[:br])
        yValsHigh = pylab.array(yValsBase[br:])
        xValsLow = xValsLow * 9.81
        xValsHigh = xValsHigh * 9.81
        modelLow = pylab.polyfit(xValsLow, yValsLow, 1)
        modelHigh = pylab.polyfit(xValsHigh, yValsHigh, 0)
        estYValsLow = pylab.polyval(modelLow, xValsLow)
        estYValsHigh = pylab.polyval(modelHigh, xValsHigh)
        fit = aveMeanSquareError(yValsLow, estYValsLow) + \
              aveMeanSquareError(yValsHigh, estYValsHigh)
        if bestFitSoFar == None or bestFitSoFar > fit:
            bestFitSoFar = fit
            bestFitBreak = br
    pylab.figure()
    pylab.plot(xValsLow, yValsLow, 'bo', label='Measured points')
    pylab.plot(xValsHigh, yValsHigh, 'bo', label='Measured points')
    labelPlot()
    br = bestFitBreak
    xValsLow = pylab.array(xValsBase[:br])
    xValsHigh = pylab.array(xValsBase[br:])
    yValsLow = pylab.array(yValsBase[:br])
    yValsHigh = pylab.array(yValsBase[br:])
    xValsLow = xValsLow * 9.81
    xValsHigh = xValsHigh * 9.81
    modelLow = pylab.polyfit(xValsLow, yValsLow, 1)
    modelHigh = pylab.polyfit(xValsHigh, yValsHigh, 0)
    estYValsLow = pylab.polyval(modelLow, xValsLow)
    estYValsHigh = pylab.polyval(modelHigh, xValsHigh)
    pylab.plot(xValsLow,
               estYValsLow,
               'g',
               label='Linear fit, k = ' + str(round(1 / modelLow[0], 5)))
    pylab.plot(xValsHigh,
               estYValsHigh,
               'g',
               label='Linear fit,, k = ' + str(round(1 / modelHigh[0], 5)))
    pylab.legend(loc='best')
    print('rSquared value, low = ', rSquared(yValsLow, estYValsLow))
    print('rSquared value, high = ', rSquared(yValsHigh, estYValsHigh))


## for slide 57

#fitDataWithBreakFlat('springData.txt')
示例#38
0
def plotSimulation(numSteps):
    rabbits, foxes = [], []
    for _ in range(numSteps):
        rabbitGrowth()
        foxGrowth()
        rabbits.append(CURRENTRABBITPOP)
        foxes.append(CURRENTFOXPOP)
    pylab.plot(range(numSteps), rabbits, label='Rabbits')
    rabbit_coeff = pylab.polyfit(range(numSteps), rabbits, 2)
    pylab.plot(pylab.polyval(rabbit_coeff, range(numSteps)))
    pylab.plot(range(numSteps), foxes, label='Foxes')
    fox_coeff = pylab.polyfit(range(numSteps), foxes, 2)
    pylab.plot(pylab.polyval(fox_coeff, range(numSteps)))
    pylab.show()
示例#39
0
def plotSim():
    numSim = 400
    rabbit_populations, fox_populations = runSimulation(numSim)
    pylab.figure(1)
    pylab.plot(range(numSim), rabbit_populations, label = "rabit")
    pylab.plot(range(numSim), fox_populations, label = "fox")

#    pylab.figure(2)
    coeff = pylab.polyfit(range(numSim), rabbit_populations, 2)
    pylab.plot(pylab.polyval(coeff, range(numSim)), label = "rabit fitting")
    coeff = pylab.polyfit(range(numSim), fox_populations, 2)
    pylab.plot(pylab.polyval(coeff, range(numSim)), label = "fox fitting") 
    
    pylab.legend()
    pylab.show()
示例#40
0
def animate_line(i, x, y, order=1, mu=1E-4):
    global anim_coeffs
    N = len(x)
    plt.title('Iteration %d\n%s' % (i, Eqn_Str3(anim_coeffs)))
    for i in range(N):
        Err = y[i] - polyval(anim_coeffs, x[i])
        # anim_coeffs = anim_coeffs + mu*Err*np.array([x[i]**2, x[i], 1])
        X_Vect = np.fliplr(np.polynomial.polynomial.polyvander(x[i], order))[0]
        anim_coeffs = anim_coeffs + mu * Err * X_Vect\
                      #/(np.linalg.norm(X_Vect)**2)

        # print(anim_coeffs, np.fliplr(np.polynomial.polynomial.polyvander(x[i], 2)))
    line.set_xdata(x)
    line.set_ydata(polyval(anim_coeffs, x))
    return line,
示例#41
0
文件: misc.py 项目: MMaus/mutils
def get_minmax(data, deg=2):
    """
    returns the interpolated extremum and position (in fractions of frames)

    :args:
        data (iterable): data to be fitted with a <deg> degree polynomial
        deg (int): degree of polynomial to fit

    :returns:
        val, pos: a tuple of floats indicating the position
    """

    x = arange(len(data))
    p = polyfit(x, data, deg)
    d = (arange(len(p))[::-1] * p)[:-1]
    r = roots(d)
    cnt = 0
    idx = None
    for nr, rx in enumerate(r):
        if isreal(r):
            idx = nr
            cnt +=1
            if cnt > 1:
                raise ValueError("Too many real roots found." + 
                        "Reduce order of polynomial!")
    x0 = r[nr].real
    return x0, polyval(p, x0)
示例#42
0
def evaluate_models_on_training(x, y, models):
    """
    For each regression model, compute the R-square for this model with the
    standard error over slope of a linear regression line (only if the model is
    linear), and plot the data along with the best fit curve.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        R-square of your model evaluated on the given data points
    Args:
        x: a list of length N, representing the x-coords of N sample points
        y: a list of length N, representing the y-coords of N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a numpy array storing the coefficients of
            a polynomial.
    Returns:
        None
    """
    for model in models:
        print(model)
        estimated = pylab.polyval(model, x)
        pylab.clf()
        pylab.plot(x, y, 'bo', label='Observed Data')
        pylab.plot(x, estimated, 'r', label='Estimated Model')
        pylab.title(
            str(len(model - 1)) + ' Degree Model' + '\n' + "R Squared: " +
            str(r_squared(y, estimated)))
        pylab.xlabel('Years')
        pylab.ylabel('Temperature')
        pylab.legend()
        pylab.show()
示例#43
0
文件: misc.py 项目: MMaus/mutils
def get_minmax(data, deg=2):
    """
    returns the interpolated extremum and position (in fractions of frames)

    :args:
        data (iterable): data to be fitted with a <deg> degree polynomial
        deg (int): degree of polynomial to fit

    :returns:
        val, pos: a tuple of floats indicating the position
    """

    x = arange(len(data))
    p = polyfit(x, data, deg)
    d = (arange(len(p))[::-1] * p)[:-1]
    r = roots(d)
    cnt = 0
    idx = None
    for nr, rx in enumerate(r):
        if isreal(r):
            idx = nr
            cnt += 1
            if cnt > 1:
                raise ValueError("Too many real roots found." +
                                 "Reduce order of polynomial!")
    x0 = r[nr].real
    return x0, polyval(p, x0)
示例#44
0
def part1():
    # I (amps)
    x = [3.12, 6.18, 9.28, 12.36, 15.52, 18.62, 21.8, 24.9, 28.0, 31.4]
    # V (Volts)
    y = [float(v) for v in range(1, 11)]

    # This gives m,b from (y = mx + b)
    m, b = pylab.polyfit(x, y, 1)
    # This calculates the slope for us
    slope = pylab.polyval([m, b], x)

    # Acordding to the lab R = m, but it's * 10 ^-3
    R_slope = m * 10**-3
    R_dmm = .000325
    print("Part 1")
    print("R_slope = %f" % (R_slope))
    percent_diff = (abs(R_dmm - R_slope) / R_dmm + R_slope / 2) * 100
    print("percent difference %f" % (percent_diff))

    plt.plot(x, slope, "-r", label="slope")
    plt.scatter(x, y)
    plt.title("Carbon Resistor ")
    plt.ylabel("V (Volts)")
    plt.xlabel("I (amps) * 10^-3")
    plt.show()
示例#45
0
def evaluate_models_on_training(x, y, models):
    """
    For each regression model, compute the R-square for this model with the
    standard error over slope of a linear regression line (only if the model is
    linear), and plot the data along with the best fit curve.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        R-square of your model evaluated on the given data points
    Args:
        x: a list of length N, representing the x-coords of N sample points
        y: a list of length N, representing the y-coords of N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a numpy array storing the coefficients of
            a polynomial.
    Returns:
        None
    """
    pylab.plot(x, y, 'o', label='Data')
    for i in range(len(models)):
        y_estimated = pylab.polyval(models[i], x)
        error = r_squared(y, y_estimated)
        pylab.plot(x, y_estimated,
                   label = 'Fit of degree '\
                   + '2'\
                   + ', R2 = ' + str(round(error, 5)))
    pylab.legend(loc='best')
    pylab.title("Problem 3")
    pylab.show()
示例#46
0
def part2():

    # I (amps)
    x = [67.3, 93.0, 114.7, 133.6, 150.4, 166.4, 180.9, 194.6]
    # V (Volts)
    y = [(v * .50) for v in range(0, 8)]

    # This gives m,b from (y = mx + b)
    m, b = pylab.polyfit(x, y, 1)
    # This calculates the slope for us
    slope = pylab.polyval([m, b], x)

    # Acordding to the lab R_min and R_max are the lowest and highest values of the slope
    # removing the first value becaue it's negative
    slope1 = list(filter(lambda x: x > 0, slope))
    print(slope1)
    R_min = min(slope1) * 10**-3
    R_max = max(slope1) * 10**-3
    print("Part 2")
    print("R_min = %f" % (R_min))
    print("R_max = %f" % (R_max))
    percent_diff = (abs(R_max - R_min) / R_max + R_min / 2) * 100
    print("percent difference %f" % (percent_diff))

    plt.plot(x, slope, "-r", label="slope")
    plt.scatter(x, y)
    plt.title("Light Bulb")
    plt.ylabel("V (Volts)")
    plt.xlabel("I (amps) * 10^-3")
    plt.show()
	def PolinomialRegression(self,Data,FileOutPath,hasHeader,polinoimalDegree):
		NVars = len(Data[0])
		# Plot column name if both are the same variables (diagonal).
		# For different variables, a scatter plot with both variables and their regression.
		Header = []
		if (hasHeader):
			Header = Data[0]
			Data = Data[1:]
		else:
			for i in range(NVars):
				Header.append("column "+str(i+1))
				Data = Data

		loc = 1
		for i in range(NVars):
			for j in range(NVars):
				P.subplot(NVars, NVars, loc)
				if (i==j):
					P.text(0.2, 0.5, Header[i], size=12)
				else:
					fit = P.polyfit(Data[:,i],Data[:,j],polinoimalDegree)
					yp = P.polyval(fit,np.sort(Data[:,i]))
	
					P.plot(np.sort(Data[:,i]),yp,'g-',Data[:,i],Data[:,j],'b.')
					P.grid(True)
					
				loc = loc + 1
		
		# Store as SVG
		P.savefig(FileOutPath)
示例#48
0
def visualize(numStep):
    foxPop, rabbitPop = runSimulation(numStep)
    print foxPop
    print rabbitPop
    x = range(numStep)
    # coeff = [a, b, c] where ax^2 + bx + c
    coeff = pylab.polyfit(x, rabbitPop, 2)
    rabbitPred = pylab.polyval(coeff, x)
    coeff = pylab.polyfit(x, foxPop, 2)
    foxPred = pylab.polyval(coeff, x)
    pylab.figure()
    pylab.plot(x, foxPop, "r")
    pylab.plot(x, foxPred, "y")
    pylab.plot(x, rabbitPop, "b")
    pylab.plot(x, rabbitPred, "g")
    pylab.show()
示例#49
0
文件: plot.py 项目: 0mp/freebsd
def parse():
    # Split the input up
    rows = [x.strip().split(':') for x in fileinput.input()]
    # Automatically turn numbers into the base type
    rows = [[to_float(y) for y in x] for x in rows]

    # Scan once to calculate the overhead
    r = [Record(*(x + [0, 0, 0])) for x in rows]
    bounces = pylab.array([(x.loops, x.rawtime) for x in r if x.test == 'bounce'])
    fit = pylab.polyfit(bounces[:,0], bounces[:,1], 1)

    records = []

    for row in rows:
        # Make a dummy record so we can use the names
        r1 = Record(*(row + [0, 0, 0]))

        bytes = r1.size * r1.loops
        # Calculate the bounce time
        delta = pylab.polyval(fit, [r1.loops])
        time = r1.rawtime - delta
        rate = bytes / time

        records.append(Record(*(row + [time, bytes, rate])))

    return records
示例#50
0
文件: ps4.py 项目: 1337tester/pyfund
def evaluate_models_on_training(x, y, models):
    """
    For each regression model, compute the R-square for this model with the
    standard error over slope of a linear regression line (only if the model is
    linear), and plot the data along with the best fit curve.

    For the plots, you should plot data points (x,y) as blue dots and your best
    fit curve (aka model) as a red solid line. You should also label the axes
    of this figure appropriately and have a title reporting the following
    information:
        degree of your regression model,
        R-square of your model evaluated on the given data points
    Args:
        x: a list of length N, representing the x-coords of N sample points
        y: a list of length N, representing the y-coords of N sample points
        models: a list containing the regression models you want to apply to
            your data. Each model is a numpy array storing the coefficients of
            a polynomial.
    Returns:
        None
    """
    for m in models:
        estYVals = pylab.polyval(m, x)
        R_v_2 = r_squared(y, estYVals)
        pylab.figure()
        pylab.plot(x, y, 'o', label = 'Actual data')
        pylab.plot(x, estYVals, 'r--', label = 'Predictive values')
        print('R-squared = ', rSquared(y, estYVals))
        pylab.legend(loc = 'best')
        pylab.title('evaluate_models_on_training')
        pylab.show()
示例#51
0
def plot_test(px,py,thick=2):
  from pylab import plot 
  tt = linspace(0,1,50)
  dpx = polyder(px)
  dpy = polyder(py)
  dL2 = polymul(dpx,dpx) + polymul(dpy,dpy)
  ux  = polyval( px,tt )
  uy  = polyval( py,tt )
  dx  = diff(ux) #polyval( px,tt )
  dy  = diff(uy) #polyval( py,tt )
  dx  = r_[dx[0],dx]
  dy  = r_[dy[0],dy]
  dL  = sqrt( dx**2 + dy**2 )

  plot( ux, uy , '.-')
  plot( ux + thick*dy/dL , uy - thick*dx/dL ,'-')
  plot( ux - thick*dy/dL , uy + thick*dx/dL ,'-' )
示例#52
0
def fit_data(xval,yval,n):
    # fit poly of order n to x,y and return poly values
    ave_x = npy.average(xval)
    ave_y = npy.average(yval)
    
    cof = pl.polyfit(xval-ave_x,yval-ave_y,n)
    ynew = pl.polyval(cof,xval-ave_x)
    return xval,ynew+ave_y
示例#53
0
def dPsi(a,s,psi1,psi2):
    ''' 
    First derivative of polynomial
    # a = polynomical constants (needs to be in list/array form so len() command works)
    # s = position along polynomial
    # psi1,psi2: start and end orientation
    '''
    
    n = len(a) # number of variables in polynimal
    ns = len(s) # number of parts to use for the contour
    a1 = a*(pl.arange(n-1,-1,-1)+1)
    a2 = pl.zeros(n+1)
    a2[:-1] = a*(pl.arange(n-1,-1,-1)+2)
    
    psi = -psi1 + psi2 + pl.polyval(a1,s) -pl.polyval(a2,s)
   
    return psi
示例#54
0
def compute_join_score( im, px, py, thick = 2 ):
  tt = linspace(0,1,50)
  dpx = polyder(px)
  dpy = polyder(py)
  dL2 = polymul(dpx,dpx) + polymul(dpy,dpy)
  ux  = polyval( px,tt )
  uy  = polyval( py,tt )
  dx  = diff(ux) #polyval( px,tt )
  dy  = diff(uy) #polyval( py,tt )
  dx  = r_[dx[0],dx]
  dy  = r_[dy[0],dy]
  dL  = sqrt( dx**2 + dy**2 )

  a = _compute_intensity(im, ux, uy )
  b = _compute_intensity(im, ux + thick*dy/dL , uy - thick*dx/dL )
  c = _compute_intensity(im, ux - thick*dy/dL , uy + thick*dx/dL )
  return (2*a - b - c)/4.0
示例#55
0
def compute_join_length( px, py, tlow = 0.0, thigh = 1.0 ):
  from scipy.integrate import quad
  xp  = polyder( px, 1 )
  yp  = polyder( py, 1 )
  xp2 = polymul( xp, xp )
  yp2 = polymul( yp, yp )
  p   = polyadd( xp2, yp2 )
  integrand = lambda t: sqrt( polyval( p, t ) )
  return quad(integrand, tlow, thigh) [0]
def test1():
    n = 200
    r,f = runSimulation(n)
    coeff_r = pylab.polyfit(range(len(r)), r, 2)
    coeff_f = pylab.polyfit(range(len(f)), f, 2)
        
    pylab.plot(range(n), r, label="Rabbit Count")
    pylab.plot(range(n), f, label="Fox Count")
    pylab.plot(pylab.polyval(coeff_r, range(len(r))), label="Rabbit Fit")
    pylab.plot(pylab.polyval(coeff_f, range(len(f))), label="Fox Fit")
    pylab.title('Number of critters at time t')
    pylab.xlabel('Time')
    pylab.ylabel('Count')
    pylab.legend(title="Legend")
    
 
    pylab.show()
    
    
示例#57
0
def Psi(a,s,psi1,psi2):
    ''' 
    Basic function for the polynomial for the curve
    # a = polynomical constants (needs to be in list/array form so len() command works)
    # s = position along polynomial
    # psi1,psi2: start and end orientation
    '''
    psi = (1-s)*psi1 + s*psi2 + s*(1-s)*pl.polyval(a,s)
    # note: the function polyval takes its arguments backwards, so that output is e.g. a1*x**3 + a2*x**2 + a1*x etc.
    return psi
示例#58
0
def testFits(models, degrees, xVals, yVals, title):
    pylab.plot(xVals, yVals, 'o', label = 'Data')
    for i in range(len(models)):
        estYVals = pylab.polyval(models[i], xVals)
        error = rSquared(yVals, estYVals)
        pylab.plot(xVals, estYVals,
                   label = 'Fit of degree '\
                   + str(degrees[i])\
                   + ', R2 = ' + str(round(error, 5)))
    pylab.legend(loc = 'best')
    pylab.title(title)
示例#59
0
文件: lorentzian.py 项目: HMP1/bumps
def demo():
    import pylab
    x,y,dy = data['x'],data['y'],data['dy']
    A,B,C = coeff['A'],coeff['B'],coeff['C']
    Io,Eo,Gamma = coeff['Io'],coeff['Eo'],coeff['Gamma']
    pylab.errorbar(x, y, yerr=dy, label="data")
    pylab.plot(x, pylab.polyval([C,B,A], x), label="background")
    pylab.plot(x, lorentzian(x,Eo=Eo,Io=Io,Gamma=Gamma), label="peak")
    pylab.plot(x, lorentzian(x,**coeff), label="peak+bkg")
    pylab.legend()
    pylab.show()
示例#60
0
def DFA(data, npoints=None, degree=1, use_median=False):
    """
    computes the detrended fluctuation analysis
    returns the fluctuation F and the corresponding window length L

    :args:
        data (n-by-1 array): the data from which to compute the DFA
        npoints (int): the number of points to evaluate; if omitted the log(n)
            will be used
        degree (int): degree of the polynomial to use for detrending
        use_median (bool): use median instead of mean fluctuation

    :returns:
        F, L: the fluctuation F as function of the window length L

    """
    # max window length: n/4

    #0th: compute integral
    integral = cumsum(data - mean(data))

    #1st: compute different window lengths
    n_samples = npoints if npoints is not None else int(log(len(data)))
    lengths = sort(array(list(set(
            logspace(2,log(len(data)/4.),n_samples,base=exp(1)).astype(int)
             ))))

    #print lengths
    all_flucs = []
    used_lengths = []
    for wlen in lengths:
        # compute the fluctuation of residuals from a linear fit
        # according to Kantz&Schreiber, ddof must be the degree of polynomial,
        # i.e. 1 (or 2, if mean also counts? -> see in book)
        curr_fluc = []
#        rrt = 0
        for startIdx in arange(0,len(integral),wlen):
            pt = integral[startIdx:startIdx+wlen]
            if len(pt) > 3*(degree+1):
                resids = pt - polyval(polyfit(arange(len(pt)),pt,degree),
                                  arange(len(pt)))
#                if abs(wlen - lengths[0]) < -1:
#                    print resids[:20]
#                elif rrt == 0:
#                    print "wlen", wlen, "l0", lengths[0]
#                    rrt += 1
                curr_fluc.append(std(resids, ddof=degree+1))
        if len(curr_fluc) > 0:
            if use_median:
                all_flucs.append(median(curr_fluc))
            else:
                all_flucs.append(mean(curr_fluc))
            used_lengths.append(wlen)
    return array(all_flucs), array(used_lengths)