ax.yaxis.set_ticks_position('left')
        ax2.yaxis.set_ticks_position('right')
        plt.xlim(10, 2000)
        ax2.set_ylim(10,10000)
        ax.xaxis.set_ticks_position('bottom')
        ax.set_xlabel(r'CW/projectile ($m_{1}/m_{2}$) mass ratio')
        ax.set_ylabel(r'Arm ratio')
        h1, l1 = ax.get_legend_handles_labels()
        h2, l2 = ax2.get_legend_handles_labels()
        handles = h1 + h2
        labels = l1 + l2
        plt.legend(handles, labels, loc=0)


        plt.tight_layout()
        lpt.savefig(trebDict['optiPlotName'])
        plt.clf()

        # Reset colorcycler
        #colorCycler = itertools.cycle(lpt.tableau10)
        if trebDict['trebType'] == trebDicts.murlinDict['trebType'] or trebDict['trebType'] == trebDicts.simpleMurlinDict['trebType']:
            # Plot a and range on the other graph
            fig, ax = lpt.newfig(0.6)

            plt.semilogx(massRatioSpace, resultDataFrame['a'], markeredgecolor = next(colorCycler), marker=next(markerCycler), markersize=2,
                         markerfacecolor='None', linestyle="None", label=r'$a$')
            plt.semilogx(massRatioSpace,resultDataFrame['b'], markeredgecolor = next(colorCycler), marker=next(markerCycler), markersize=2,
                         markerfacecolor='None', linestyle="None", label=r'$b$')

            # Plot the range on the y-axis two.
            ax2 = ax.twinx()
Example #2
0
# Plot the proj trajectory curve.
#Maximum index calculating the initial V0x and V0y
# gamma = 3*pi/2 - alpha
#z[0] = theta
#z[1] = phi
#z[2] = alpha
#z[3] = theta_dot
#z[4] = phi_dot
#z[5] = alpha_dot
V0x = L2 * z[max_index, 3] * np.cos(np.pi - z[max_index, 0]) + L3 * z[
    max_index, 5] * np.cos(3 * np.pi / 2 - z[max_index, 2])
V0y = L2 * z[max_index, 3] * np.sin(np.pi - z[max_index, 0]) + L3 * z[
    max_index, 5] * np.sin(3 * np.pi / 2 - z[max_index, 2])
print("V0x: %.3f V0y: %.3f" % (V0x, V0y))
SyPlot = []
SxPlot = []
tproj = np.linspace(
    0, ((V0y + np.sqrt((V0y**2) + (2 * g * (y3[max_index] - h)))) / g), 100)
#((Vy+np.sqrt((Vy**2)+(2*g*y2)))/g)
for i in range(len(tproj)):
    ithxpos = V0x * tproj[i] + x3[max_index]
    SxPlot.append(ithxpos)
    ithypos = y3[max_index] + V0y * tproj[i] - 0.5 * g * tproj[i]**2
    SyPlot.append(ithypos)
plt.plot(SxPlot, SyPlot, dashes=([2, 2]), color='k', linewidth=1)
ax.set_xlabel(r'x (m)')
ax.set_ylabel(r'y (m)')
plt.tight_layout()
lpt.savefig('StandardTrebThrowOutline')
def pendTreb(x):
    global g
    global m1
    global m2
    global L2
    global L1
    global x1, y1, x2, y2, t, Sx, z, h
    g = 9.81
    m1 = x
    m2 = 1
    L2 = 2
    #Set max length of total arm to be 3m.
    L1 = 0.5
    h = -np.cos(45 * pi / 180) * L2
    endtime = 1
    dt = 300
    t = np.linspace(0, endtime, dt)
    zinit = np.array([45 * pi / 180, 0])
    z = odeint(deriv, zinit, t)

    x1 = L1 * np.sin(z[:, 0])
    y1 = L1 * np.cos(z[:, 0])
    x2 = -L2 * np.sin(z[:, 0])
    y2 = -L2 * np.cos(z[:, 0])

    Sx = []
    for i in range(0, len(t)):
        Sx.append(ThrowRange(z[i, 0], z[i, 1]))
        #Grab the largest range value. ThrowRange function args: theta,thetadot,alpha,alphadot
    #Sx = Sx[0:400]
    import operator
    global max_index, max_value
    max_index, max_value = max(enumerate(Sx), key=operator.itemgetter(1))
    rangethrown = max_value
    #figure(figsize=(10,6), dpi=80)
    fig, ax = lpt.newfig(0.5)
    plt.subplot(1, 1, 1)
    patches = []
    #subplot(1,1,1)

    #Vertical line
    patches.append(
        ax.add_line(
            plt.Line2D((max_index / dt, max_index / dt), (-5, max_value),
                       lw=1,
                       dashes=([2, 2]),
                       color='r')))
    #Horizontal line
    patches.append(
        ax.add_line(
            plt.Line2D((0, max_index / dt), (max_value, max_value),
                       lw=1,
                       dashes=([2, 2]),
                       color='r')))
    plt.plot(t, Sx[:], color="k", marker="o", markersize=2, linewidth=0.5)
    ax.set_xlabel(r'Time (s)')
    ax.set_ylabel(r'Range (m)')
    ylimits = plt.ylim(min(Sx) - 1, max(Sx) * 1.1)
    plt.tight_layout()
    plt.show()
    lpt.savefig('PendulumRange')
    return rangethrown
Example #4
0
m1 = 50.0
a = 1.22
L2 = 4.0
L3 = 4.0
range, throwAngle = treb.runTreb(L2=L2, L3=L3, a=a, m1=m1, endtime=2.0, zinit=zinit, theta0=np.pi/4)
# Throw step index
maxThrowIndex = treb.maxThrowIndex
print('range', range, 'throw Angle', throwAngle, 'maxThrowIndex', maxThrowIndex)
fig = plt.figure(figsize=(10, 6), dpi=80)
plt.subplot(1, 1, 1, aspect='equal')

bounds = 6
xlimits = plt.xlim(-bounds, bounds)
ylimits = plt.ylim(-bounds, bounds)
ax = plt.axes(xlim=xlimits, ylim=ylimits, aspect='equal')

fig, ax = plt.subplots()
frameInterval = 5
for frame in np.arange(0, maxThrowIndex, step=frameInterval):
    ax = treb.plotTreb(ax, i=int(frame), projRadius=0.2, CWRadius=0.2, lineThickness=1.0, beamCentreRadius=0.1,
                       imageAlpha=0.2)
# Plot the throw point
ax = treb.plotTreb(ax, i=maxThrowIndex, projRadius=0.2, CWRadius=0.2, lineThickness=1.0, beamCentreRadius=0.1)
bounds = 10
ax.set_xlim(-bounds, bounds)
ax.set_ylim(-bounds, bounds)
ax.set_aspect('equal')
plotName = 'murlinTimeInterval'
lpt.savefig(plotName)
#fig.savefig('./murlinTimeInterval.png', dpi=500)
V0y = L2 * z[max_index, 1] * np.cos(z[max_index, 0] - pi / 2)
SyPlot = []
SxPlot = []
tproj = np.linspace(
    0, ((V0y + np.sqrt((V0y**2) + (2 * g * (y2[max_index] - h)))) / g), 100)
#((Vy+np.sqrt((Vy**2)+(2*g*y2)))/g)
for i in range(len(tproj)):
    ithxpos = V0x * tproj[i] + x2[max_index]
    SxPlot.append(ithxpos)
    ithypos = y2[max_index] + V0y * tproj[i] - 0.5 * g * tproj[i]**2
    SyPlot.append(ithypos)
plt.plot(SxPlot, SyPlot, dashes=([2, 2]), color='k', linewidth=1)
ax.set_xlabel(r'x (m)')
ax.set_ylabel(r'y (m)')
plt.show()
lpt.savefig('PendulumThrowOutline')
'''
#Animate this shit!

fig = plt.figure(figsize=(10,6), dpi=80)
plt.subplot(1,1,1,aspect='equal')

xlimits = plt.xlim(-4,4)
ylimits = plt.ylim(-4,4)
ax = plt.axes(xlim = xlimits, ylim = ylimits,aspect='equal')


def init():

    return []
Example #6
0
def doParameterStudy(useDict,
                     computeParameterStudy,
                     pickleFileName,
                     plotName,
                     numPoints=30):
    if computeParameterStudy is True:
        trebClass = useDict[
            'TrebClass']  # FATTreb('TestTreb') # Replace to either standardTreb or standardTreb on Wheels
        zinit = useDict['zinit']
        m1 = useDict['m1']
        m3 = useDict['m3']
        endtime = 2.0
        dt = 0.01
        size = numPoints

        rangeSpace = np.zeros((size, size))
        # L2 loop
        L2s = np.linspace(useDict['L2sMin'], useDict['L2sMax'], size)
        L3s = np.linspace(useDict['L3sMin'], useDict['L3sMax'], size)
        L2Space, L3Space, rangeSpace = np.zeros(size**2), np.zeros(
            size**2), np.zeros(size**2)

        # ! itertools! who cares about the order!
        # Look how much I've improved in Python!
        import itertools
        for index, [L2, L3] in enumerate(itertools.product(L2s, L3s)):
            throwRange, throwAngle = trebClass.runTreb(m1=m1,
                                                       m3=m3,
                                                       L2=L2,
                                                       L3=L3,
                                                       endtime=endtime,
                                                       dt=dt,
                                                       zinit=zinit)
            L2Space[index] = L2
            L3Space[index] = L3
            rangeSpace[index] = throwRange
            print('Throw:', index, '/', size**2 - 1, 'L2:', L2, "L3:", L3,
                  'Throw range:', throwRange)

        # Pickle out the data
        outData = [L2Space, L2s, L3Space, L3s, rangeSpace, size]
        with open(pickleFilename, "wb") as f:
            print('Written data to:', pickleFilename)
            pickle.dump(outData, f)

    else:
        with open(pickleFilename, "rb") as f:
            [L2Space, L2s, L3Space, L3s, rangeSpace, size] = pickle.load(f)
            print('Loaded pickle data from:', pickleFilename)
    # --------------------------------------------------------------------------

    # Find the L2,L3 of the maximum range
    maxRangeIndex = np.nanargmax(rangeSpace)
    L2Max, L3Max, rangeMax = L2Space[maxRangeIndex], L3Space[
        maxRangeIndex], np.nanmax(rangeSpace)
    print('L2Max:', L2Max, 'L3Max:', L3Max, 'rangeMax:', rangeMax)
    fig, ax = lpt.newfig(0.6)
    plt.subplot(1, 1, 1)
    levels = np.linspace(np.nanmin(rangeSpace),
                         np.nanmax(rangeSpace) + 0.01,
                         size,
                         endpoint=True)
    patches = []

    plt.plot(L2Space, L3Space, 'k.', markersize=0.35)
    # Draw a plot point on the plot for the highest point.
    # plt.scatter(L3Space[j],L2Space[i],s = 2.0, color = 'r', lw = 0)
    plt.plot(L2Max, L3Max, 'r.', markersize=3.0)

    # Plot 3 times reduces the white lines around each contour level
    # Reshape rangeSpace into a size by size 2d array
    rangeSpace = np.reshape(rangeSpace, (size, size))
    for i in range(3):
        CS = plt.contourf(L2s,
                          L3s,
                          rangeSpace.T,
                          cmap='viridis',
                          levels=levels,
                          linestyle='None')

    cbar = plt.colorbar(ticks=np.linspace(
        np.nanmin(rangeSpace), np.nanmax(rangeSpace) + 0.01, 6, endpoint=True))

    cbar.ax.set_ylabel('Range (m)')
    ax.set_ylabel(r'$\frac{L_{3}}{L_{1}}$')
    ax.set_xlabel(r'$\frac{L_{2}}{L_{1}}$')

    plt.tight_layout()
    lpt.savefig(plotName)
    #plt.savefig(plotName + '.png', dpi=300)
    plt.clf()
Example #7
0
                                       yDot=treb.y3Dot)

        ax.plot(treb.t, TKE, color=next(colorCycler), label='TKE')
        ax.plot(treb.t, TPE, color=next(colorCycler), label='TPE')
        ax.plot(treb.t, projKE, color=next(colorCycler), label='Projectile KE')
        ax.plot(treb.t, projPE, color=next(colorCycler), label='Projectile PE')
        CWLineColor = next(colorCycler)
        ax.axhline(y=CWEnergy, color=CWLineColor, linestyle='-', dashes=[3, 1])
        ax.text(s='Total CW potential energy',
                color=CWLineColor,
                x=0.05,
                y=CWEnergy + 50)
        ax.axvline(x=treb.t[treb.maxThrowIndex],
                   color=next(colorCycler),
                   linestyle='-',
                   linewidth=0.8,
                   ymin=0,
                   ymax=CWEnergy)
        ax.set_ylabel('Energy (J)')
        ax.set_xlabel('Time (sec)')
        ax.set_ylim(ymin=0.0)
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        ax.yaxis.set_ticks_position('left')
        ax.xaxis.set_ticks_position('bottom')
        ax.legend()
        plt.tight_layout()
        lpt.savefig(trebDict['energyPlotName'])
        plt.clf()
        print(CWEnergy)
# Plot the range on the y-axis two.
ax2 = ax.twinx()
line3, = ax2.loglog(massRatioSpace, rangeSpace, color="g", marker="^", markersize = 2,markerfacecolor='None',markeredgecolor = 'g', linestyle = "None", label=r'Range')
#ax2.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax2.set_ylabel('Range')

#ax2.set_ylim(0.007,2.000)

ax.set_xlabel(r'CW/projectile ($m_{1}/m_{2}$) mass ratio')
ax.set_ylabel(r'Arm ratio')
h1, l1 = ax.get_legend_handles_labels()
h2, l2 = ax2.get_legend_handles_labels()
plt.legend(h1+h2, l1+l2, loc=0, handler_map={line1: HandlerLine2D(numpoints=1),line2: HandlerLine2D(numpoints=1),line3: HandlerLine2D(numpoints=1)})
xlimits = plt.xlim(10,2000)
plt.tight_layout()
lpt.savefig('MurlinOptimisation')


# Plot a and range on the other graph
fig, ax = lpt.newfig(0.6)
#lpt.subplot(2,1,1)

line1, = plt.semilogx(massRatioSpace,aSpace, color="r", marker="o", markersize = 2,markerfacecolor='None',markeredgecolor = 'r', linestyle = "None", label = r'$a$~value')
#plt.ylim(0.97*np.min(aSpace), 1.03*np.max(aSpace))
line2, = plt.semilogx(massRatioSpace,bSpace, color="b", marker="+", markersize = 2,markerfacecolor='w', linestyle = "None", label = r'$b$~value')
# Plot the range on the y-axis two.
ax2 = ax.twinx()
line3, = ax2.loglog(massRatioSpace, rangeSpace, color="g", marker="^", markersize = 2,markerfacecolor='None',markeredgecolor = 'g', linestyle = "None", label = 'range')
#ax2.yaxis.set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax2.set_ylabel('Range')
trebDicts = [
    pendulumDict, FATDict, standardDict, standardWheeledDict, simpleMurlinDict
]

for trebDict in trebDicts:
    pickleFileName = trebDict['pickleFileName']
    plotLabel = trebDict['trebType']
    print('Reading Name', pickleFileName)
    data = pd.read_pickle(pickleFileName)
    massRatioSpace = data.index.values
    plt.semilogx(massRatioSpace,
                 data['Range'] / massRatioSpace,
                 marker=next(markers),
                 markersize=2,
                 linewidth=0.5,
                 markerfacecolor='None',
                 label=plotLabel)

xlimits = plt.xlim(10, 1500)
plt.xlabel(r'CW/projectile ($m_{1}/m_{2}$) mass ratio')
plt.ylabel(r'$\frac{\mathrm{Range}}{m_{1}/m_{2}}$')
#box = ax.get_position()
#ax.set_position([box.x0 + box.width*0.1, box.y0 + box.height *0.4, box.width * 0.92, box.height * 0.6])
#ax.spines['top'].set_visible(False)
lgnd = plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.15), ncol=3)

#plt.tight_layout()
lpt.savefig('rangeRatioComparison',
            bbox_extra_artists=(lgnd, ),
            bbox_inches='tight')