Beispiel #1
0
    def __init__(self, ui, ally=None, active=True, interval=250):
        super(Ally, self).__init__()

        if ally is None:
            return

        self.ally = ally

        # Create a dict so we now where we currently are
        self.current = {
            'velocity': None,
            'my_state': None,
            'opponent_state': None,
            'ball_state': None,
            'pidinfo': None,
            'desired_position': None,
            'desired_position_safe': None,
            'other_opponent_state': None,
            'other_ally_state': None
        }

        # Create a dictionary for last messages of different types
        self.last = copy.deepcopy(self.current)

        # Click to Drive positions (CTD)
        self.CTD_x1 = self.CTD_y1 = None
        self.CTD_x2 = self.CTD_y2 = None

        # Setup the UI for this ally
        self.ui = AllyUI(ui, ally=ally)

        # After we've set up the GUI, if this ally is not active just bail
        if not active:
            self.ui.append_title('Inactive')
            return

        # Placeholders for child windows
        self._step_resp = None

        # Figure out my namespace based on who I am
        ns = '/ally{}'.format(ally)
        self.ns = ns

        # If I am this ally, who is the other ally?
        other_ally = 1 if ally == 2 else 2
        
        # Connect ROS things
        rospy.Subscriber('{}/ally{}_state'.format(ns,ally), \
                            RobotState, self._handle_my_state)
        rospy.Subscriber('{}/ally{}_state'.format(ns,other_ally), \
                            RobotState, self._handle_other_ally_state)
        rospy.Subscriber('{}/opponent{}_state'.format(ns,ally), \
                            RobotState, self._handle_opponent_state)
        rospy.Subscriber('{}/opponent{}_state'.format(ns,other_ally), \
                            RobotState, self._handle_other_opponent_state)
        rospy.Subscriber('{}/ball_state'.format(ns), \
                            BallState, self._handle_ball_state)
        rospy.Subscriber('{}/desired_position'.format(ns), \
                            Pose2D, self._handle_des_pos)
        rospy.Subscriber('{}/desired_position_safe'.format(ns), \
                            Pose2D, self._handle_des_pos_safe)
        rospy.Subscriber('{}/vel_cmds'.format(ns), \
                            Twist, self._handle_vel)
        rospy.Subscriber('{}/pidinfo'.format(ns), \
                            PIDInfo, self._handle_PID_error)

        self.pub_des_pos = rospy.Publisher('{}/desired_position'.format(ns), \
                            Pose2D, queue_size=10)

        # Connect Qt Buttons
        self.ui.btn_clear.clicked.connect(self._btn_clear)
        self.ui.btn_kick.clicked.connect(self._btn_kick)
        self.ui.btn_battery.clicked.connect(self._btn_battery)
        self.ui.btn_set_des_pos.clicked.connect(self._btn_des_pos)
        self.ui.btn_stop_moving.clicked.connect(self._btn_stop_moving)
        self.ui.btn_step_resp.clicked.connect(self._btn_step_resp)

        # Connect Plot Mouse events
        self.ui.plot_field.canvas.mpl_connect('button_press_event', self._plot_field_mouse_down)
        self.ui.plot_field.canvas.mpl_connect('motion_notify_event', self._plot_field_mouse_move)
        self.ui.plot_field.canvas.mpl_connect('button_release_event', self._plot_field_mouse_up)

        # matplotlib create animation
        # Look into using the same event_source for the two -- maybe this would help
        # decrease overhead/latency? See matplotlib source code for more info
        ## Interval - I had interval=8ms and everything was smooth, but CPU was
        ## at 130%. I changed it to 500ms and it went down to 30%! But the plotting
        ## was severly discretized. A good in between was at 250ms (~60% CPU), but if
        ## you're on a faster machine, you may want to increase interval to ~100ms
        self.animation_field = animation.FuncAnimation(self.ui.plot_field.canvas.fig, \
                            self._animate_field, init_func=self._animate_init_field, \
                            frames=None, interval=interval, blit=False, event_source=None)
    if pkt.addr2 != None and pkt.addr2 not in excluded_macs and pkt.addr2 not in found_macs:
        add_mac(pkt.addr2)


if args.exclude_file != None:
    for mac in args.exclude_file:
        excluded_macs.append(mac.strip().split()[0])


class PseudoPacket:
    def __init__(self, mac):
        self.addr2 = mac


if args.import_file != None:
    for mac in args.import_file:
        PacketHandler(PseudoPacket(mac.strip().split()[0]))

if not args.disable:
    if args.graph:
        # Start Packet Sniffer in separate thread
        thread.start_new_thread(sniff, (),
                                dict(iface=args.interface, prn=PacketHandler))
    else:
        sniff(iface=args.interface, prn=PacketHandler)
if args.graph:
    # Setup Pie Chart, Begin 1s refresh, and show initial graph
    update_pie_chart(0)
    ani = animation.FuncAnimation(fig, update_pie_chart, interval=1000)
    plt.show()
Beispiel #3
0
idf = pd.read_csv('data/SPY_20110701_20120630_Bollinger.csv',
                  index_col=0,
                  parse_dates=True)
idf.shape
idf.head(3)
idf.tail(3)
df = idf.loc['2011-07-01':'2011-12-30', :]

fig = mpf.figure(style='charles', figsize=(7, 8))
ax1 = fig.add_subplot(2, 1, 1)
ax2 = fig.add_subplot(3, 1, 3)


def animate(ival):
    if (22 + ival) > len(df):
        print('no more data to plot')
        ani.event_source.interval *= 3
        if ani.event_source.interval > 12000:
            exit()
        return
    data = df.iloc[0 + ival:(22 + ival)]
    ax1.clear()
    ax2.clear()
    mpf.plot(data, ax=ax1, volume=ax2, type='ohlc')


ani = animation.FuncAnimation(fig, animate, interval=250)

mpf.show()
# animation function.  This will be called sequentially with the frame number
def animate(i):
    # we'll step two time-steps per frame.  This leads to nice results.
    i = (2 * i) % x_t.shape[1]

    for line, pt, xi in zip(lines, pts, x_t):
        x, y, z = xi[:i].T
        line.set_data(x, y)
        line.set_3d_properties(z)

        pt.set_data(x[-1:], y[-1:])
        pt.set_3d_properties(z[-1:])

    ax.view_init(30, 0.3 * i)
    fig.canvas.draw()
    return lines + pts


# instantiate the animator.
anim = animation.FuncAnimation(fig,
                               animate,
                               init_func=init,
                               frames=500,
                               interval=30,
                               blit=True)

# Save as mp4. This requires mplayer or ffmpeg to be installed
#anim.save('lorentz_attractor.mp4', fps=15, extra_args=['-vcodec', 'libx264'])

plt.show()
Beispiel #5
0
line2, = ax.plot([], [], lw=2)

tot_time = 20
intv = 20


def init():
    line.set_data([], [])
    line2.set_data([], [])
    return line,


def animate(i):
    x = np.linspace(-8, 8, 1000)
    y = np.sin(0.1 * x * i)
    y2 = np.cos(0.1 * x * i)
    line.set_data(x, y)
    line2.set_data(x, y2)
    return line,


anim = animation.FuncAnimation(fig,
                               animate,
                               init_func=init,
                               frames=(tot_time * 1000) // intv,
                               interval=intv,
                               blit=True)
#anim.save('basic_animation.mp4', fps=30, extra_args=['-vcodec', 'libx264'])

plt.show()
def plot(title):
    ani = animation.FuncAnimation(fig, animate, interval=2)
    print(title)
    plt.title("{}\n".format(title))
    plt.show()
Beispiel #7
0
    ep.set_data([x_OA[k], x_OBp[k]], [y_OA[k], y_OBp[k]])
    for j in range(theta.size):
        es[j].set_data([x_OC[j][k], x_OBs[j][k]], [y_OC[j][k], y_OBs[j][k]])
    for j in range(theta.size):
        e0[j].set_data([x_OA[k], x_OC[j][k]], [y_OA[k], y_OC[j][k]])
    ea.set_data([0., x_OA[k]], [0., y_OA[k]])

    cp.set_data(alpha[0:k], OBp[0:k])
    for j in range(theta.size):
        cs[j].set_data(alpha[0:k], OBs[j][0:k])

    return artists

if blit:
    animation = ani.FuncAnimation(fig, animate, frames=frames, init_func=init,
                                  interval=interval, blit=True)
else:
    animation = ani.FuncAnimation(fig, animate, frames=frames,
                                  interval=interval)


# *************************************
# - Output file generation -

# If selected the output option, graphic window will not be shown.

# !!! <--droid> option added to have a fast way to watch this animations
#     in every android cell phone.
if filename:
    print('Generating animation...')
    animation.save(filename + '.mp4', fps=fps, writer='ffmpeg',
Beispiel #8
0
    def draw_it(self, **kwargs):

        sliding_window_size = (3, 3)
        if 'sliding_window_size' in kwargs:
            sliding_window_size = kwargs['sliding_window_size']

        stride = 1
        if 'stride' in kwargs:
            stride = kwargs['stride']

        # initialize figure
        fig = plt.figure(figsize=(10, 4))
        artist = fig

        # create subplot with 3 panels, plot input function in center plot
        gs = gridspec.GridSpec(1, 3, width_ratios=[1, 3, 1])
        ax1 = plt.subplot(gs[0])
        ax1.axis('off')
        ax3 = plt.subplot(gs[2])
        ax3.axis('off')
        ax = plt.subplot(gs[1])

        slider = []
        for i in np.arange(
                0,
                np.shape(self.image)[0] - sliding_window_size[0] + 1, stride):
            for j in np.arange(
                    0,
                    np.shape(self.image)[1] - sliding_window_size[1] + 1,
                    stride):
                slider.append((i, j))

        num_frames = np.shape(slider)[0]

        print('starting animation rendering...')

        # animation sub-function
        def animate(k):

            # clear the panel
            ax.cla()

            # print rendering update
            if np.mod(k + 1, 25) == 0:
                print('rendering animation frame ' + str(k + 1) + ' of ' +
                      str(num_frames))
            if k == num_frames - 1:
                print('animation rendering complete!')
                time.sleep(1.5)
                clear_output()

            # plot original image
            ax.imshow(cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB))

            # plot sliding window
            ax.add_patch(
                patches.Rectangle(
                    (slider[k][1], slider[k][0]),  # (x,y)
                    sliding_window_size[1],  # width
                    sliding_window_size[0],  # height
                    edgecolor="red",
                    linewidth=2,
                    facecolor="none"))

            # remove tickmarks
            ax.set_xticks([])
            ax.set_yticks([])

            return artist,

        anim = animation.FuncAnimation(fig,
                                       animate,
                                       frames=num_frames,
                                       interval=num_frames,
                                       blit=True)

        return (anim)
Beispiel #9
0
def spectral_anim(
        RawData_Frames,
        spectra_wl,
        ts,
        interval=15,
        time_template = 'Gate Delay = %.1fns'
):
    """
    Matplotlib Animation Example
    
    author: Jake Vanderplas
    email: [email protected]
    website: http://jakevdp.github.com
    license: BSD
    Please feel free to use and modify this, but keep the above information.
    Thanks!

    TODO: add documentation

    Parameters
    ----------
    RawData_Frames
    spectra_wl
    ts
    interval

    Returns
    -------

    """

    xs = spectra_wl

    # First set up the figure, the axis, and the plot element we want to animate
    fig = plt.figure()
    ax = plt.axes(
        xlim=(xs[0], xs[-1]),
        ylim=(0, 1.1)
    )

    line, = ax.plot(
        [],
        [],
        lw=2
    )

    
    time_text = ax.text(
        0.05,
        0.9,
        '',
        transform=ax.transAxes
    )

    fig.tight_layout()

    #
    def init():
        """
        TODO: improve documentation

        initialization function: plot the background of each frame

        Returns
        -------
        line
        """
        line.set_data([], [])
        time_text.set_text('')
        ax.set_ylabel("Normalized Emission Intensity (a.u.)")
        ax.set_xlabel("Wavelength (nm)")
        return line,

    def animate(i):
        """
        TODO: improve documentation

        animation function.  This is called sequentially

        Parameters
        ----------
        i : int

        Returns
        -------

        """
        y = RawData_Frames.iloc[:, i]#.as_matrix()
        y = y / RawData_Frames.max().max()
        line.set_data(
            xs,
            y
        )
        if time_template is not None:
            time_text.set_text(time_template % ts[i])
        else:
            time_text.set_text(str(ts[i].astype('datetime64[ms]')))
        return line, time_text

    # call the animator.
    # blit=True means only re-draw the parts that have changed.
    anim = animation.FuncAnimation(
        fig,
        animate,
        init_func=init,
        frames=len(ts),
        interval=interval,
        blit=True
    )

    # # equivalent to rcParams['animation.html'] = 'html5'
    # rc(
    #     'animation',
    #     html='html5'
    # )

    return anim
# initialization function: plot the background of each frame
def init():
    points.set_data([], [])
    return points,


# animation function.  This is called sequentially
def animate(i):
    x = real_values[i, :]
    y = imag_values[i, :]
    points.set_data(x, y)
    return points,


# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig,
                               animate,
                               init_func=init,
                               frames=len(indivs[:, 0]),
                               interval=800,
                               blit=True)

# save the animation as an mp4.  This requires ffmpeg or mencoder to be
# installed.  The extra_args ensure that the x264 codec is used, so that
# the video can be embedded in html5.  You may need to adjust this for
# your system: for more information, see
# http://matplotlib.sourceforge.net/api/animation_api.html
anim.save(filename + '_animation.mp4', fps=fps)

plt.show()
Beispiel #11
0
y2 = -L2*cos(y[:, 2]) + y1

fig = plt.figure()
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2))
ax.set_aspect('equal')
ax.grid()

line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)


def init():
    line.set_data([], [])
    time_text.set_text('')
    return line, time_text


def animate(i):
    thisx = [0, x1[i], x2[i]]
    thisy = [0, y1[i], y2[i]]

    line.set_data(thisx, thisy)
    time_text.set_text(time_template % (i*dt))
    return line, time_text


ani = animation.FuncAnimation(fig, animate, range(1, len(y)),
                              interval=dt*1000, blit=True, init_func=init)
plt.show()
Beispiel #12
0
def init():
    line.set_data([], [])
    return line,


''' animation function.  This is called sequentially and will be called by FuncAnimation repeatedly
    in order to create the animation dictatedd by curve equation.'''


def animate(i):
    '''print(i) #$$$$$To check if animation.FuncAnimation is calling this animate function multiple times or not$$$$$'''
    (y, yt) = evw.evo_time(
    )  # The Getter, wave_evo(self) is a void method, instead the computation is done by the written method.
    evw.wave_evo = y  # Calls Setter
    line.set_data(z, yt)
    return line,


#----------------------------------------------------------------------------------------------

# CALL THE ANIMATOR.  blit=true MEANS ONLY RE-DRAW THE PARTS THAT HAVE CHANGED.
anim = animation.FuncAnimation(fig, animate, init_func=init,\
                               frames=t, interval=30, blit=False)
#anim = anim.save('schrodinger_barrier.mp4', fps=20, extra_args=['-vcodec', 'libx264'])
plt.show()

#----------------------------------------------------------------------------------------------
sys.exit(
    'TIMEOUT: MANIPULATE VARIABLES FOR DESIRED OUTCOME FOR THE NEXT ANIMATION')
Beispiel #13
0
mean1 = data[:,0].mean ()
mean2 = data[:,1].mean ()
std1  = data[:,0].std ()
std2  = data[:,1].std ()
params = np.array ( [(mean1 - 0.2, mean2 - 1, std1, std2, 0),
                     (mean1 + 0.2, mean2 + 1, std1, std2, 0)] )
weights = np.array ( [ 0.5, 0.5 ] )

#EM (data, params, weights)

res_EM = EM_2( data, params, weights )
#print(res_EM)


bounds = find_video_bounds ( data, res_EM )

# création de l'animation : tout d'abord on crée la figure qui sera animée
fig = plt.figure ()
ax = fig.gca (xlim=(bounds[0], bounds[1]), ylim=(bounds[2], bounds[3]))

# exécution de l'animation
anim = animation.FuncAnimation(fig, animate, frames = len ( res_EM ), interval=500 )
plt.show ()


'''
f= open('data.pkl','wb')
pkl.dump(data,f) # penser à sauver les données pour éviter de refaire les opérations
f.close()
'''
import matplotlib.animation as animation
import data_local as dataDevice

PADDING = 5
myData = dataDevice.device()
dispdata = []
timeplot = 0
fig, ax = plt.subplots()
line, = ax.plot(dispdata)


def update(data):
    global dispdata, timeplot
    timeplot += 1
    dispdata.append(data)
    ax.set_xlim(0, timeplot)
    ymin = min(dispdata) - PADDING
    ymax = max(dispdata) + PADDING
    ax.set_ylim(ymin, ymax)
    line.set_data(range(timeplot), dispdata)
    return line


def data_gen():
    while True:
        yield myData.getNew()[1] / 1000


ani = animation.FuncAnimation(fig, update, data_gen, interval=1000)
plt.show()
#End
Beispiel #15
0

def update(num, data, line):
    line.set_data(data[:2, :num])
    line.set_3d_properties(data[2, :num])


#ROBERTO CARLOS FREE KICK
fig, cx = plt.subplots()

cx = plt.axes(projection='3d')
line, = cx.plot3D(x, y, z, '-r', label='soccer ball')

ani = animation.FuncAnimation(fig,
                              update,
                              N,
                              fargs=(data, line),
                              interval=10000 / N,
                              blit=False)

#SAVE ANIMATION
#Set up formatting for the movie files
#Writer = animation.writers['ffmpeg']
#writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
#ani.save('Roberto_carlos.mp4', writer=writer)

#GOAL PLACEMENT
goal_z_p = np.linspace(2.44, 2.44, 50)
goal_x_p = np.linspace(Rf[0], Rf[0], 50)
goal_y_p = np.linspace(Rf[1], -Rf[1], 50)

cx.plot3D(goal_x_p, goal_y_p, goal_z_p, '-b', label='goal')
Beispiel #16
0
def spectral_anim_xr(
        da,
        interval=15,
        time_template = 'Gate Delay = %.1fns'
):


    xs = da.coords['wavelength'].values
    ts = da.coords['time'].values

    # First set up the figure, the axis, and the plot element we want to animate
    fig, ax = plt.subplots()

    lines = da.isel(time=0).plot(ax=ax)

    line = lines[0]

    
    time_text = ax.text(
        0.05,
        0.9,
        '',
        transform=ax.transAxes
    )

    ax.set_ylim(0,1.1*da.max().item())
    ax.set_title('')

    fig.tight_layout()

    #
    def init():
        line.set_ydata([np.nan]*len(ts))
        return line,

    def animate(i):
        """
        TODO: improve documentation

        animation function.  This is called sequentially

        Parameters
        ----------
        i : int

        Returns
        -------

        """
        y = da.isel(time=i).values
        # y = y / RawData_Frames.max().max()
        line.set_data(
            xs,
            y
        )
        if time_template is not None:
            time_text.set_text(time_template % ts[i])
        else:
            time_text.set_text(str(ts[i].astype('datetime64[ms]')))
        return line, time_text

    # call the animator.
    # blit=True means only re-draw the parts that have changed.
    anim = animation.FuncAnimation(
        fig,
        animate,
        init_func=init,
        frames=len(ts),
        interval=interval,
        blit=True
    )

    # # equivalent to rcParams['animation.html'] = 'html5'
    # rc(
    #     'animation',
    #     html='html5'
    # )

    return anim
Beispiel #17
0
m.colorbar(location='right')
m.drawcoastlines()
m.fillcontinents()
m.drawmapboundary()
m.drawparallels(W.lat[0:-1:5],labels=[1,0,0,0])
m.drawmeridians(W.lon[0:-1:5],labels=[0,0,0,1])

def update_quiver(t,plt,u,v) :
    """method required to animate quiver and contour plot
    """
    plt.C=m.pcolormesh(x,y,W.wMag[t],shading='flat',cmap=plt.cm.jet)
    plt.Q=m.quiver(x,y,W.u[t],W.v[t])

    return plt

anim = animation.FuncAnimation(fig, update_quiver, frames=range(np.size(W.time)), fargs=(plt,W.u,W.v),
                               interval=50, blit=False)

plt.show()


#%%
# convert the lat/lon values to x/y projections.
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

X, Y = np.mgrid[:2*np.pi:0.2,:2*np.pi:0.2]
U = np.cos(X)
V = np.sin(Y)

fig, ax = plt.subplots(1,1)
Beispiel #18
0
def show_data(indir,
              plot_type,
              print_flag,
              save_flag,
              data_only,
              vOut=None,
              pOut=None,
              tOut=None):
    pfx = 'mpet.'
    sStr = "_"
    ttl_fmt = "% = {perc:2.1f}"
    # Read in the simulation results and calcuations data
    dataFileName = "output_data.mat"
    dataFile = os.path.join(indir, dataFileName)
    data = sio.loadmat(dataFile)
    try:
        data[pfx + 'current'][0][0]
    except KeyError:
        pfx = ''
    try:
        data[pfx + "partTrodecvol0part0" + sStr + "cbar"]
    except KeyError:
        sStr = "."
    # Read in the parameters used to define the simulation
    dD_s, ndD_s = IO.read_dicts(os.path.join(indir, "input_dict_system"))
    # simulated (porous) electrodes
    Nvol = ndD_s["Nvol"]
    trodes = ndD_s["trodes"]
    dD_e = {}
    ndD_e = {}
    for trode in trodes:
        dD_e[trode], ndD_e[trode] = IO.read_dicts(
            os.path.join(indir, "input_dict_{t}".format(t=trode)))
    # Pick out some useful constants/calculated values
    k = dD_s['k']  # Boltzmann constant, J/(K Li)
    Tref = dD_s['Tref']  # Temp, K
    e = dD_s['e']  # Charge of proton, C
    F = dD_s['F']  # C/mol
    td = dD_s["td"]
    Etheta = {"a": 0.}
    for trode in trodes:
        Etheta[trode] = -(k * Tref / e) * ndD_s["phiRef"][trode]
#        Etheta[trode] = -(k*Tref/e) * ndD_e[trode]["muR_ref"]
    Vstd = Etheta["c"] - Etheta["a"]
    Nvol = ndD_s["Nvol"]
    Npart = ndD_s["Npart"]
    psd_len = dD_s["psd_len"]
    # Discretization (and associated porosity)
    Lfac = 1e6
    Lunit = r"$\mu$m"
    dxc = ndD_s["L"]["c"] / Nvol["c"]
    dxvec = np.array(Nvol["c"] * [dxc])
    porosvec = np.array(Nvol["c"] * [ndD_s["poros"]["c"]])
    cellsvec = dxc * np.arange(Nvol["c"]) + dxc / 2.
    if Nvol["s"]:
        dxs = ndD_s["L"]["s"] / Nvol["s"]
        dxvec_s = np.array(Nvol["s"] * [dxs])
        dxvec = np.hstack((dxvec_s, dxvec))
        poros_s = np.array(Nvol["s"] * [ndD_s["poros"]["s"]])
        porosvec = np.hstack((poros_s, porosvec))
        cellsvec += dD_s["L"]["s"] / dD_s["L"]["c"]
        cellsvec_s = dxs * np.arange(Nvol["s"]) + dxs / 2.
        cellsvec = np.hstack((cellsvec_s, cellsvec))
    if "a" in trodes:
        dxa = ndD_s["L"]["a"] / Nvol["a"]
        dxvec_a = np.array(Nvol["a"] * [dxa])
        dxvec = np.hstack((dxvec_a, dxvec))
        poros_a = np.array(Nvol["a"] * [ndD_s["poros"]["a"]])
        porosvec = np.hstack((poros_a, porosvec))
        cellsvec += dD_s["L"]["a"] / dD_s["L"]["c"]
        cellsvec_a = dxa * np.arange(Nvol["a"]) + dxa / 2.
        cellsvec = np.hstack((cellsvec_a, cellsvec))
    cellsvec *= dD_s["Lref"] * Lfac
    facesvec = np.insert(np.cumsum(dxvec), 0, 0.) * dD_s["Lref"] * Lfac
    # Extract the reported simulation times
    times = data[pfx + 'phi_applied_times'][0]
    numtimes = len(times)
    tmin = np.min(times)
    tmax = np.max(times)
    # Simulation type
    profileType = ndD_s['profileType']
    # Colors for plotting concentrations
    to_yellow = 0.3
    to_red = 0.7
    scl = 1.0  # static
    #    scl = 1.2  # movies
    figsize = (scl * 6, scl * 4)

    # Print relevant simulation info
    if print_flag:
        print("profileType:", profileType)
        #        for i in trodes:
        #            print "PSD_{l}:".format(l=l)
        #            print psd_len[l].transpose()
        #            print "Actual psd_mean [nm]:", np.mean(psd_len[l])
        #            print "Actual psd_stddev [nm]:", np.std(psd_len[l])
        print("Cell structure:")
        print(("porous anode | " if Nvol["a"] else "flat anode | ") +
              ("sep | " if Nvol["s"] else "") + "porous cathode")
        if Nvol["a"]:
            print("capacity ratio cathode:anode, 'z':", ndD_s["z"])
        for trode in trodes:
            print("solidType_{t}:".format(t=trode), ndD_e[trode]['type'])
            print("solidShape_{t}".format(t=trode), ndD_e[trode]['shape'])
            print("rxnType_{t}:".format(t=trode), ndD_e[trode]['rxnType'])
        if profileType == "CC":
            print("C_rate:", dD_s['Crate'])
            print("current:", dD_s['currset'], "A/m^2")
        else:  # CV
            print("Vset:", dD_s['Vset'])
        print("Specified psd_mean, c [{unit}]:".format(unit=Lunit),
              np.array(dD_s['psd_mean']["c"]) * Lfac)
        print("Specified psd_stddev, c [{unit}]:".format(unit=Lunit),
              np.array(dD_s['psd_stddev']["c"]) * Lfac)
        #        print "reg sln params:"
        #        print ndD["Omga"]
        print("ndim B_c:", ndD_e["c"]["B"])
        if Nvol["s"]:
            print("Nvol_s:", Nvol["s"])
        print("Nvol_c:", Nvol["c"])
        if Nvol["a"]:
            print("Nvol_a:", Nvol["a"])
        print("Npart_c:", Npart["c"])
        if Nvol["a"]:
            print("Npart_a:", Npart["a"])
        print("Dp [m^2/s]:", dD_s['Dp'])
        print("Dm [m^2/s]:", dD_s['Dm'])
        print("Damb [m^2/s]:", dD_s['Damb'])
        print("td [s]:", dD_s["td"])
        for trode in trodes:
            print("k0_{t} [A/m^2]:".format(t=trode), dD_e[trode]['k0'])
            rxnType = ndD_e[trode]['rxnType']
            if rxnType == "BV":
                print("alpha_" + trode + ":", ndD_e[trode]['alpha'])
            elif rxnType in ["Marcus", "MHC"]:
                print("lambda_" + trode + "/(kTref):", ndD_e[trode]["lambda"])
            if ndD_s['simBulkCond'][trode]:
                print(trode + " bulk conductivity loss: Yes -- " +
                      "sigma_s [S/m]: " + str(dD_s['sigma_s'][trode]))
            else:
                print(trode + " bulk conductivity loss: No")
            try:
                simSurfCond = ndD_e[trode]['simSurfCond']
                if simSurfCond:
                    print(trode + " surface conductivity loss: Yes -- " +
                          "dim_scond [S]: " + str(dD_e[trode]['scond']))
                else:
                    print(trode + " surface conductivity loss: No")
            except:
                pass
#            if ndD['simSurfCond'][l]:
#                print (l + " surface conductivity loss: Yes -- " +
#                        "dim_scond [S]: " + str(dD['scond'][l]))
#            else:
#                print l + " surface conductivity loss: No"

    if plot_type in ["params"]:
        return ndD_s, dD_s, ndD_e, dD_e
    if plot_type in ["discData"]:
        return cellsvec / Lfac, facesvec / Lfac

    # Plot voltage profile
    if plot_type in ["v", "vt"]:
        voltage = (Vstd - (k * Tref / e) * data[pfx + 'phi_applied'][0])
        ffvec = data[pfx + 'ffrac_c'][0]
        fig, ax = plt.subplots(figsize=figsize)
        if plot_type == "v":
            if data_only:
                plt.close(fig)
                return ffvec, voltage
            ax.plot(ffvec, voltage)
            xmin = 0.
            xmax = 1.
            ax.set_xlim((xmin, xmax))
            ax.set_xlabel("Cathode Filling Fraction [dimensionless]")
        elif plot_type == "vt":
            if data_only:
                plt.close(fig)
                return times * td, voltage
            ax.plot(times * td, voltage)
            ax.set_xlabel("Time [s]")
        ax.set_ylabel("Voltage [V]")
        if save_flag:
            fig.savefig("mpet_v.pdf", bbox_inches="tight")
        return fig, ax

    # Plot surface conc.
    if plot_type[:-2] in ["surf"]:
        trode = plot_type[-1]
        str_base = (
            pfx +
            "partTrode{trode}vol{{vInd}}part{{pInd}}".format(trode=trode) +
            sStr + "c")
        if data_only:
            sol_str = str_base.format(pInd=pOut, vInd=vOut)
            datay = data[sol_str][:, -1]
            return times * td, datay
        fig, ax = plt.subplots(Npart[trode],
                               Nvol[trode],
                               squeeze=False,
                               sharey=True,
                               figsize=figsize)
        ylim = (0, 1.01)
        datax = times
        for pInd in range(Npart[trode]):
            for vInd in range(Nvol[trode]):
                sol_str = str_base.format(pInd=pInd, vInd=vInd)
                # Remove axis ticks
                ax[pInd, vInd].xaxis.set_major_locator(plt.NullLocator())
                datay = data[sol_str][:, -1]
                line, = ax[pInd, vInd].plot(times, datay)
        return fig, ax

    # Plot SoC profile
    if plot_type[:-2] in ["soc"]:
        trode = plot_type[-1]
        ffvec = data[pfx + 'ffrac_{trode}'.format(trode=trode)][0]
        if data_only:
            return times * td, ffvec
        fig, ax = plt.subplots(figsize=figsize)
        print(ffvec[-1])
        ax.plot(times * td, ffvec)
        xmin = np.min(ffvec)
        xmax = np.max(ffvec)
        ax.set_ylim((0, 1.05))
        ax.set_xlabel("Time [s]")
        ax.set_ylabel("Filling Fraciton [dimless]")
        if save_flag:
            fig.savefig("mpet_soc.pdf", bbox_inches="tight")
        return fig, ax

    # Check to make sure mass is conserved in elyte
    if plot_type == "elytecons":
        fig, ax = plt.subplots(figsize=figsize)
        eps = 1e-2
        ymin = 1 - eps
        ymax = 1 + eps
        #        ax.set_ylim((ymin, ymax))
        ax.set_ylabel('Avg. Concentration of electrolyte [nondim]')
        sep = pfx + 'c_lyte_s'
        anode = pfx + 'c_lyte_a'
        cath = pfx + 'c_lyte_c'
        ax.set_xlabel('Time [s]')
        cvec = data[cath]
        if Nvol["s"]:
            cvec_s = data[sep]
            cvec = np.hstack((cvec_s, cvec))
        if "a" in trodes:
            cvec_a = data[anode]
            cvec = np.hstack((cvec_a, cvec))
        cavg = np.sum(porosvec * dxvec * cvec, axis=1) / np.sum(
            porosvec * dxvec)
        if data_only:
            plt.close(fig)
            return times * td, cavg
        np.set_printoptions(precision=8)
        print(cavg)
        ax.plot(times * td, cavg)
        return fig, ax

    # Plot current profile
    if plot_type == "curr":
        current = data[pfx + "current"][0] * 3600 / td
        ffvec = data[pfx + 'ffrac_c'][0]
        if data_only:
            return times * td, current
        fig, ax = plt.subplots(figsize=figsize)
        ax.plot(times * td, current)
        xmin = np.min(ffvec)
        xmax = np.max(ffvec)
        ax.set_xlabel("Time [s]")
        ax.set_ylabel("Current [C-rate]")
        if save_flag:
            fig.savefig("mpet_current.png", bbox_inches="tight")
        return fig, ax

    # Plot electrolyte concentration or potential
    elif plot_type in [
            "elytec", "elytep", "elytecf", "elytepf", "elytei", "elyteif",
            "elytedivi", "elytedivif"
    ]:
        fplot = (True if plot_type[-1] == "f" else False)
        t0ind = (0 if not fplot else -1)
        mpl.animation.Animation._blit_draw = _blit_draw
        datax = cellsvec
        c_sep, p_sep = pfx + 'c_lyte_s', pfx + 'phi_lyte_s'
        c_anode, p_anode = pfx + 'c_lyte_a', pfx + 'phi_lyte_a'
        c_cath, p_cath = pfx + 'c_lyte_c', pfx + 'phi_lyte_c'
        datay_c = data[c_cath]
        datay_p = data[p_cath]
        L_c = dD_s['L']["c"] * Lfac
        Ltot = L_c
        if Nvol["s"]:
            datay_s_c = data[c_sep]
            datay_s_p = data[p_sep]
            datay_c = np.hstack((datay_s_c, datay_c))
            datay_p = np.hstack((datay_s_p, datay_p))
            L_s = dD_s['L']["s"] * Lfac
            Ltot += L_s
        else:
            L_s = 0
        if "a" in trodes:
            datay_a_c = data[c_anode]
            datay_a_p = data[p_anode]
            datay_c = np.hstack((datay_a_c, datay_c))
            datay_p = np.hstack((datay_a_p, datay_p))
            L_a = dD_s['L']["a"] * Lfac
            Ltot += L_a
        else:
            L_a = 0
        xmin = 0
        xmax = Ltot
        if plot_type in ["elytec", "elytecf"]:
            ymin = 0
            ymax = 2.2
            ylbl = 'Concentration of electrolyte [M]'
            datay = datay_c * dD_s["cref"] / 1000.
        elif plot_type in ["elytep", "elytepf"]:
            ymin = -50
            ymax = 50
            ylbl = 'Potential of electrolyte [V]'
            datay = datay_p * (k * Tref / e) - Vstd
        elif plot_type in ["elytei", "elyteif", "elytedivi", "elytedivif"]:
            cGP_L, pGP_L = data["c_lyteGP_L"], data["phi_lyteGP_L"]
            cmat = np.hstack((cGP_L.T, datay_c, datay_c[:, -1].reshape(
                (numtimes, 1))))
            pmat = np.hstack((pGP_L.T, datay_p, datay_p[:, -1].reshape(
                (numtimes, 1))))
            disc = geom.get_elyte_disc(Nvol, ndD_s["L"], ndD_s["poros"],
                                       ndD_s["BruggExp"])
            i_edges = np.zeros((numtimes, len(facesvec)))
            for tInd in range(numtimes):
                i_edges[tInd, :] = mod_cell.get_lyte_internal_fluxes(
                    cmat[tInd, :], pmat[tInd, :], disc["dxd1"],
                    disc["eps_o_tau_edges"], ndD_s)[1]
            if plot_type in ["elytei", "elyteif"]:
                ylbl = r'Current density of electrolyte [A/m$^2$]'
                datax = facesvec
                datay = i_edges * (F * dD_s["cref"] * dD_s["Dref"] /
                                   dD_s["Lref"])
            elif plot_type in ["elytedivi", "elytedivif"]:
                ylbl = r'Divergence of electrolyte current density [A/m$^3$]'
                datax = cellsvec
                datay = np.diff(i_edges, axis=1) / disc["dxd2"]
                datay *= (F * dD_s["cref"] * dD_s["Dref"] / dD_s["Lref"]**2)
        if fplot:
            datay = datay[t0ind]
        if data_only:
            return datax, datay, L_a, L_s
        dataMin, dataMax = np.min(datay), np.max(datay)
        dataRange = dataMax - dataMin
        ymin = max(0, dataMin - 0.05 * dataRange)
        ymax = dataMax + 0.05 * dataRange
        fig, ax = plt.subplots(figsize=figsize)
        ax.set_xlabel('Battery Position [{unit}]'.format(unit=Lunit))
        ax.set_ylabel(ylbl)
        ttl = ax.text(0.5,
                      1.05,
                      ttl_fmt.format(perc=0),
                      transform=ax.transAxes,
                      verticalalignment="center",
                      horizontalalignment="center")
        ax.set_ylim((ymin, ymax))
        ax.set_xlim((xmin, xmax))
        # returns tuble of line objects, thus comma
        if fplot:
            line1, = ax.plot(datax, datay, '-')
        else:
            line1, = ax.plot(datax, datay[t0ind, :], '-')
        ax.axvline(x=L_a, linestyle='--', color='g')
        ax.axvline(x=(L_a + L_s), linestyle='--', color='g')
        if fplot:
            print("time =", times[t0ind] * td, "s")
            if save_flag:
                fig.savefig("mpet_{pt}.png".format(pt=plot_type),
                            bbox_inches="tight")
            return fig, ax

        def init():
            line1.set_ydata(np.ma.array(datax, mask=True))
            ttl.set_text('')
            return line1, ttl

        def animate(tind):
            line1.set_ydata(datay[tind])
            t_current = times[tind]
            tfrac = (t_current - tmin) / (tmax - tmin) * 100
            ttl.set_text(ttl_fmt.format(perc=tfrac))
            return line1, ttl

    # Plot solid particle-average concentrations
    elif plot_type[:-2] in ["cbarLine", "dcbardtLine"]:
        trode = plot_type[-1]
        fig, ax = plt.subplots(Npart[trode],
                               Nvol[trode],
                               squeeze=False,
                               sharey=True,
                               figsize=figsize)
        partStr = "partTrode{trode}vol{{vInd}}part{{pInd}}".format(
            trode=trode) + sStr
        type2c = False
        if ndD_e[trode]["type"] in ndD_s["1varTypes"]:
            if plot_type[:-2] in ["cbarLine"]:
                str_base = pfx + partStr + "cbar"
            elif plot_type[:-2] in ["dcbardtLine"]:
                str_base = pfx + partStr + "dcbardt"
        elif ndD_e[trode]["type"] in ndD_s["2varTypes"]:
            type2c = True
            if plot_type[:-2] in ["cbarLine"]:
                str1_base = pfx + partStr + "c1bar"
                str2_base = pfx + partStr + "c2bar"
            elif plot_type[:-2] in ["dcbardtLine"]:
                str1_base = pfx + partStr + "dc1bardt"
                str2_base = pfx + partStr + "dc2bardt"
        ylim = (0, 1.01)
        datax = times * td
        if data_only:
            plt.close(fig)
            if type2c:
                sol1_str = str1_base.format(pInd=pOut, vInd=vOut)
                sol2_str = str2_base.format(pInd=pOut, vInd=vOut)
                datay1 = data[sol1_str][0]
                datay2 = data[sol2_str][0]
                datay = (datay1, datay2)
            else:
                sol_str = str_base.format(pInd=pOut, vInd=vOut)
                datay = data[sol_str][0]
            return datax, datay
        xLblNCutoff = 4
        xLbl = "Time [s]"
        yLbl = "Particle Average Filling Fraction"
        for pInd in range(Npart[trode]):
            for vInd in range(Nvol[trode]):
                if type2c:
                    sol1_str = str1_base.format(pInd=pInd, vInd=vInd)
                    sol2_str = str2_base.format(pInd=pInd, vInd=vInd)
                    if Nvol[trode] > xLblNCutoff:
                        # Remove axis ticks
                        ax[pInd,
                           vInd].xaxis.set_major_locator(plt.NullLocator())
                    else:
                        ax[pInd, vInd].set_xlabel(xLbl)
                        ax[pInd, vInd].set_ylabel(yLbl)
                    datay1 = data[sol1_str][0]
                    datay2 = data[sol2_str][0]
                    line1, = ax[pInd, vInd].plot(times, datay1)
                    line2, = ax[pInd, vInd].plot(times, datay2)
                else:
                    sol_str = str_base.format(pInd=pInd, vInd=vInd)
                    if Nvol[trode] > xLblNCutoff:
                        # Remove axis ticks
                        ax[pInd,
                           vInd].xaxis.set_major_locator(plt.NullLocator())
                    else:
                        ax[pInd, vInd].set_xlabel(xLbl)
                        ax[pInd, vInd].set_ylabel(yLbl)
                    datay = data[sol_str][0]
                    line, = ax[pInd, vInd].plot(times, datay)
        return fig, ax

    # Plot all solid concentrations or potentials
    elif plot_type[:-2] in ["csld", "musld"]:
        timettl = False  # Plot the current simulation time as title
        # Plot title in seconds
        ttlscl, ttlunit = 1, "s"
        # For example, to plot title in hours:
        # ttlscl, ttlunit = 1./3600, "hr"
        save_shot = False
        if save_shot:
            t0ind = 300
            print("Time at screenshot: {ts} s".format(ts=times[t0ind] * td))
        else:
            t0ind = 0
        trode = plot_type[-1]
        if plot_type[0] == "c":
            plt_cavg = True
        else:
            plt_cavg = False
        plt_legend = True
        plt_axlabels = True
        if ndD_e[trode]["type"] in ndD_s["1varTypes"]:
            type2c = False
        elif ndD_e[trode]["type"] in ndD_s["2varTypes"]:
            type2c = True
        Nv, Np = Nvol[trode], Npart[trode]
        partStr = "partTrode{trode}vol{vInd}part{pInd}" + sStr
        fig, ax = plt.subplots(Np,
                               Nv,
                               squeeze=False,
                               sharey=True,
                               figsize=figsize)
        if not type2c:
            cstr_base = pfx + partStr + "c"
            cbarstr_base = pfx + partStr + "cbar"
            cstr = np.empty((Np, Nv), dtype=object)
            cbarstr = np.empty((Np, Nv), dtype=object)
            lines = np.empty((Np, Nv), dtype=object)
        elif type2c:
            c1str_base = pfx + partStr + "c1"
            c2str_base = pfx + partStr + "c2"
            c1barstr_base = pfx + partStr + "c1bar"
            c2barstr_base = pfx + partStr + "c2bar"
            c1str = np.empty((Np, Nv), dtype=object)
            c2str = np.empty((Np, Nv), dtype=object)
            c1barstr = np.empty((Np, Nv), dtype=object)
            c2barstr = np.empty((Np, Nv), dtype=object)
            lines1 = np.empty((Np, Nv), dtype=object)
            lines2 = np.empty((Np, Nv), dtype=object)
            lines3 = np.empty((Np, Nv), dtype=object)
        lens = np.zeros((Np, Nv))
        if data_only:
            print("tInd_{}".format(tOut), "time =", times[tOut] * td, "s")
            lenval = psd_len[trode][vOut, pOut]
            if type2c:
                c1str = c1str_base.format(trode=trode, pInd=pOut, vInd=vOut)
                c2str = c2str_base.format(trode=trode, pInd=pOut, vInd=vOut)
                c1barstr = c1barstr_base.format(trode=trode,
                                                pInd=pOut,
                                                vInd=vOut)
                c2barstr = c2barstr_base.format(trode=trode,
                                                pInd=pOut,
                                                vInd=vOut)
                datay1 = data[c1str[pOut, vOut]][tOut]
                datay2 = data[c2str[pOut, vOut]][tOut]
                if plot_type[:-2] in ["musld"]:
                    c1bar = data[c1barstr[pOut, vOut]][0][tOut]
                    c2bar = data[c2barstr[pOut, vOut]][0][tOut]
                    muRfunc = props_am.muRfuncs(
                        ndD_s["T"], ndD_e[trode]["indvPart"][vOut,
                                                             pOut]).muRfunc
                    datay1, datay2 = muRfunc((datay1, datay2), (c1bar, c2bar),
                                             ndD_e[trode]["muR_ref"])[0]
                datay = (datay1, datay2)
                numy = len(datay1)
            else:
                cstr = cstr_base.format(trode=trode, pInd=pOut, vInd=vOut)
                cbarstr = cbarstr_base.format(trode=trode,
                                              pInd=pOut,
                                              vInd=vOut)
                datay = data[cstr][tOut]
                if plot_type[:-2] in ["musld"]:
                    cbar = data[cbarstr[pOut, vOut]][0][tOut]
                    muRfunc = props_am.muRfuncs(
                        ndD_s["T"], ndD_e[trode]["indvPart"][vOut,
                                                             pOut]).muRfunc
                    datay = muRfunc(datay, cbar, ndD_e[trode]["muR_ref"])[0]
                numy = len(datay)
            datax = np.linspace(0, lenval * Lfac, numy)
            plt.close(fig)
            return datax, datay
        if plot_type[:-2] in ["csld"]:
            ylim = (0, 1.01)
        elif plot_type[:-2] in ["musld"]:
            ylim = (-4, 4)
        for pInd in range(Np):
            for vInd in range(Nv):
                lens[pInd, vInd] = psd_len[trode][vInd, pInd]
                if type2c:
                    c1str[pInd, vInd] = c1str_base.format(trode=trode,
                                                          pInd=pInd,
                                                          vInd=vInd)
                    c2str[pInd, vInd] = c2str_base.format(trode=trode,
                                                          pInd=pInd,
                                                          vInd=vInd)
                    c1barstr[pInd, vInd] = c1barstr_base.format(trode=trode,
                                                                pInd=pInd,
                                                                vInd=vInd)
                    c2barstr[pInd, vInd] = c2barstr_base.format(trode=trode,
                                                                pInd=pInd,
                                                                vInd=vInd)
                    datay1 = data[c1str[pInd, vInd]][t0ind]
                    datay2 = data[c2str[pInd, vInd]][t0ind]
                    datay3 = 0.5 * (datay1 + datay2)
                    lbl1, lbl2 = r"$\widetilde{c}_1$", r"$\widetilde{c}_2$"
                    lbl3 = r"$\overline{c}$"
                    if plot_type[:-2] in ["musld"]:
                        lbl1, lbl2 = r"$\mu_1/k_\mathrm{B}T$", r"$\mu_2/k_\mathrm{B}T$"
                        c1bar = data[c1barstr[pInd, vInd]][0][t0ind]
                        c2bar = data[c2barstr[pInd, vInd]][0][t0ind]
                        muRfunc = props_am.muRfuncs(
                            ndD_s["T"], ndD_e[trode]["indvPart"][vInd,
                                                                 pInd]).muRfunc
                        datay1, datay2 = muRfunc((datay1, datay2),
                                                 (c1bar, c2bar),
                                                 ndD_e[trode]["muR_ref"])[0]
                    numy = len(datay1)
                    datax = np.linspace(0, lens[pInd, vInd] * Lfac, numy)
                    line1, = ax[pInd, vInd].plot(datax, datay1, label=lbl1)
                    line2, = ax[pInd, vInd].plot(datax, datay2, label=lbl2)
                    if plt_cavg:
                        line3, = ax[pInd, vInd].plot(datax,
                                                     datay3,
                                                     '--',
                                                     label=lbl3)
                        lines3[pInd, vInd] = line3
                    lines1[pInd, vInd] = line1
                    lines2[pInd, vInd] = line2
                else:
                    cstr[pInd, vInd] = cstr_base.format(trode=trode,
                                                        pInd=pInd,
                                                        vInd=vInd)
                    cbarstr[pInd, vInd] = cbarstr_base.format(trode=trode,
                                                              pInd=pInd,
                                                              vInd=vInd)
                    datay = data[cstr[pInd, vInd]][t0ind]
                    if plot_type[:-2] in ["musld"]:
                        cbar = np.array(data[cbarstr[pInd, vInd]][0][t0ind])
                        muRfunc = props_am.muRfuncs(
                            ndD_s["T"], ndD_e[trode]["indvPart"][vInd,
                                                                 pInd]).muRfunc
                        datay = muRfunc(datay, cbar,
                                        ndD_e[trode]["muR_ref"])[0]
                    numy = len(datay)
                    datax = np.linspace(0, lens[pInd, vInd] * Lfac, numy)
                    line, = ax[pInd, vInd].plot(datax, datay)
                    lines[pInd, vInd] = line
                ax[pInd, vInd].set_ylim(ylim)
                ax[pInd, vInd].set_xlim((0, lens[pInd, vInd] * Lfac))
                if plt_legend:
                    ax[pInd, vInd].legend(loc="best")
                if plt_axlabels:
                    ax[pInd,
                       vInd].set_xlabel(r"$r$ [{Lunit}]".format(Lunit=Lunit))
                    if plot_type[0] == "c":
                        ax[pInd, vInd].set_ylabel(r"$\widetilde{{c}}$")
                    elif plot_type[:2] == "mu":
                        ax[pInd, vInd].set_ylabel(r"$\mu/k_\mathrm{B}T$")
                if timettl:
                    mpl.animation.Animation._blit_draw = _blit_draw
                    ttl = ax[pInd,
                             vInd].text(0.5,
                                        1.04,
                                        "t = {tval:3.3f} {ttlu}".format(
                                            tval=times[t0ind] * td * ttlscl,
                                            ttlu=ttlunit),
                                        verticalalignment="center",
                                        horizontalalignment="center",
                                        transform=ax[pInd, vInd].transAxes)
        if save_shot:
            fig.savefig("mpet_{pt}.pdf".format(pt=plot_type),
                        bbox_inches="tight")

        def init():
            toblit = []
            for pInd in range(Npart[trode]):
                for vInd in range(Nvol[trode]):
                    if type2c:
                        numy = len(data[c1str[pInd, vInd]][t0ind])
                        maskTmp = np.zeros(numy)
                        lines1[pInd,
                               vInd].set_ydata(np.ma.array(maskTmp, mask=True))
                        lines2[pInd,
                               vInd].set_ydata(np.ma.array(maskTmp, mask=True))
                        lines_local = np.vstack((lines1, lines2))
                        if plt_cavg:
                            lines3[pInd, vInd].set_ydata(
                                np.ma.array(maskTmp, mask=True))
                            lines_local = np.vstack((lines_local, lines3))
                    else:
                        numy = len(data[cstr[pInd, vInd]][t0ind])
                        maskTmp = np.zeros(numy)
                        lines[pInd,
                              vInd].set_ydata(np.ma.array(maskTmp, mask=True))
                        lines_local = lines.copy()
                    toblit.extend(lines_local.reshape(-1))
                    if timettl:
                        ttl.set_text("")
                        toblit.extend([ttl])
            return tuple(toblit)

        def animate(tind):
            toblit = []
            for pInd in range(Npart[trode]):
                for vInd in range(Nvol[trode]):
                    if type2c:
                        datay1 = data[c1str[pInd, vInd]][tind]
                        datay2 = data[c2str[pInd, vInd]][tind]
                        datay3 = 0.5 * (datay1 + datay2)
                        if plot_type[:-2] in ["musld"]:
                            c1bar = data[c1barstr[pInd, vInd]][0][tind]
                            c2bar = data[c2barstr[pInd, vInd]][0][tind]
                            muRfunc = props_am.muRfuncs(
                                ndD_s["T"],
                                ndD_e[trode]["indvPart"][vInd, pInd]).muRfunc
                            datay1, datay2 = muRfunc(
                                (datay1, datay2), (c1bar, c2bar),
                                ndD_e[trode]["muR_ref"])[0]
                        lines1[pInd, vInd].set_ydata(datay1)
                        lines2[pInd, vInd].set_ydata(datay2)
                        lines_local = np.vstack((lines1, lines2))
                        if plt_cavg:
                            lines3[pInd, vInd].set_ydata(datay3)
                            lines_local = np.vstack((lines_local, lines3))
                    else:
                        datay = data[cstr[pInd, vInd]][tind]
                        if plot_type[:-2] in ["musld"]:
                            cbar = data[cbarstr[pInd, vInd]][0][tind]
                            muRfunc = props_am.muRfuncs(
                                ndD_s["T"],
                                ndD_e[trode]["indvPart"][vInd, pInd]).muRfunc
                            datay = muRfunc(datay, cbar,
                                            ndD_e[trode]["muR_ref"])[0]
                        lines[pInd, vInd].set_ydata(datay)
                        lines_local = lines.copy()
                    toblit.extend(lines_local.reshape(-1))
                    if timettl:
                        ttl.set_text("t = {tval:3.3f} {ttlu}".format(
                            tval=times[tind] * td * ttlscl, ttlu=ttlunit))
                        toblit.extend([ttl])
            return tuple(toblit)

    # Plot average solid concentrations
    elif plot_type in ["cbar_c", "cbar_a", "cbar_full"]:
        if plot_type[-4:] == "full":
            trvec = ["a", "c"]
        elif plot_type[-1] == "a":
            trvec = ["a"]
        else:
            trvec = ["c"]
        dataCbar = {}
        for trode in trodes:
            dataCbar[trode] = np.zeros((numtimes, Nvol[trode], Npart[trode]))
            for tInd in range(numtimes):
                for vInd in range(Nvol[trode]):
                    for pInd in range(Npart[trode]):
                        dataStr = (pfx +
                                   "partTrode{t}vol{vInd}part{pInd}".format(
                                       t=trode, vInd=vInd, pInd=pInd) + sStr +
                                   "cbar")
                        dataCbar[trode][tInd, vInd,
                                        pInd] = (data[dataStr][0][tInd])
        if data_only:
            return dataCbar
        # Set up colors.
        # Define if you want smooth or discrete color changes
        # Option: "smooth" or "discrete"
        color_changes = "discrete"
        #        color_changes = "smooth"
        # Discrete color changes:
        if color_changes == "discrete":
            # Make a discrete colormap that goes from green to yellow
            # to red instantaneously
            cdict = {
                "red": [(0.0, 0.0, 0.0), (to_yellow, 0.0, 1.0),
                        (1.0, 1.0, 1.0)],
                "green": [(0.0, 0.502, 0.502), (to_yellow, 0.502, 1.0),
                          (to_red, 1.0, 0.0), (1.0, 0.0, 0.0)],
                "blue": [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0)]
            }
            cmap = mpl.colors.LinearSegmentedColormap("discrete", cdict)
        # Smooth colormap changes:
        if color_changes == "smooth":
            # generated with colormap.org
            cmaps = np.load("colormaps_custom.npz")
            cmap_data = cmaps["GnYlRd_3"]
            cmap = mpl.colors.ListedColormap(cmap_data / 255.)

        # Implement hack to be able to animate title
        mpl.animation.Animation._blit_draw = _blit_draw
        size_frac_min = 0.10
        fig, axs = plt.subplots(1, len(trvec), squeeze=False, figsize=figsize)
        ttlx = 0.5 if len(trvec) < 2 else 1.1
        ttl = axs[0, 0].text(ttlx,
                             1.05,
                             ttl_fmt.format(perc=0),
                             transform=axs[0, 0].transAxes,
                             verticalalignment="center",
                             horizontalalignment="center")
        collection = np.empty(len(trvec), dtype=object)
        for indx, trode in enumerate(trvec):
            ax = axs[0, indx]
            # Get particle sizes (and max size) (length-based)
            lens = psd_len[trode]
            len_max = np.max(lens)
            len_min = np.min(lens)
            ax.patch.set_facecolor('white')
            # Don't stretch axes to fit figure -- keep 1:1 x:y ratio.
            ax.set_aspect('equal', 'box')
            # Don't show axis ticks
            ax.xaxis.set_major_locator(plt.NullLocator())
            ax.yaxis.set_major_locator(plt.NullLocator())
            ax.set_xlim(0, 1.)
            ax.set_ylim(0, float(Npart[trode]) / Nvol[trode])
            # Label parts of the figure
            #            ylft = ax.text(-0.07, 0.5, "Separator",
            #                    transform=ax.transAxes, rotation=90,
            #                    verticalalignment="center",
            #                    horizontalalignment="center")
            #            yrht = ax.text(1.09, 0.5, "Current Collector",
            #                    transform=ax.transAxes, rotation=90,
            #                    verticalalignment="center",
            #                    horizontalalignment="center")
            #            xbtm = ax.text(.50, -0.05, "Electrode Depth -->",
            #                    transform=ax.transAxes, rotation=0,
            #                    verticalalignment="center",
            #                    horizontalalignment="center")
            # Geometric parameters for placing the rectangles on the axes
            spacing = 1.0 / Nvol[trode]
            size_fracs = 0.4 * np.ones((Nvol[trode], Npart[trode]))
            if len_max != len_min:
                size_fracs = (lens - len_min) / (len_max - len_min)
            sizes = (size_fracs *
                     (1 - size_frac_min) + size_frac_min) / Nvol[trode]
            # Create rectangle "patches" to add to figure axes.
            rects = np.empty((Nvol[trode], Npart[trode]), dtype=object)
            color = 'green'  # value is irrelevant -- it will be animated
            for (vInd, pInd), c in np.ndenumerate(sizes):
                size = sizes[vInd, pInd]
                center = np.array(
                    [spacing * (vInd + 0.5), spacing * (pInd + 0.5)])
                bottom_left = center - size / 2
                rects[vInd, pInd] = plt.Rectangle(bottom_left,
                                                  size,
                                                  size,
                                                  color=color)
            # Create a group of rectange "patches" from the rects array
            collection[indx] = mcollect.PatchCollection(rects.reshape(-1))
            # Put them on the axes
            ax.add_collection(collection[indx])
        # Have a "background" image of rectanges representing the
        # initial state of the system.

        def init():
            for indx, trode in enumerate(trvec):
                cbar_mat = dataCbar[trode][0, :, :]
                colors = cmap(cbar_mat.reshape(-1))
                collection[indx].set_color(colors)
                ttl.set_text('')
            out = [collection[i] for i in range(len(collection))]
            out.append(ttl)
            out = tuple(out)
            return out

        def animate(tind):
            for indx, trode in enumerate(trvec):
                cbar_mat = dataCbar[trode][tind, :, :]
                colors = cmap(cbar_mat.reshape(-1))
                collection[indx].set_color(colors)
            t_current = times[tind]
            tfrac = (t_current - tmin) / (tmax - tmin) * 100
            ttl.set_text(ttl_fmt.format(perc=tfrac))
            out = [collection[i] for i in range(len(collection))]
            out.append(ttl)
            out = tuple(out)
            return out

    # Plot cathode potential
    elif plot_type[0:5] in ["bulkp"]:
        trode = plot_type[-1]
        fplot = (True if plot_type[-3] == "f" else False)
        t0ind = (0 if not fplot else -1)
        mpl.animation.Animation._blit_draw = _blit_draw
        fig, ax = plt.subplots(figsize=figsize)
        ax.set_xlabel('Position in electrode [{unit}]'.format(unit=Lunit))
        ax.set_ylabel('Potential of cathode [nondim]')
        ttl = ax.text(0.5,
                      1.05,
                      ttl_fmt.format(perc=0),
                      transform=ax.transAxes,
                      verticalalignment="center",
                      horizontalalignment="center")
        bulkp = pfx + 'phi_bulk_{trode}'.format(trode=trode)
        datay = data[bulkp]
        ymin = np.min(datay) - 0.2
        ymax = np.max(datay) + 0.2
        if trode == "a":
            datax = cellsvec[:Nvol["a"]]
        elif trode == "c":
            datax = cellsvec[-Nvol["c"]:]
        if data_only:
            plt.close(fig)
            return datax, datay[t0ind]
        # returns tuble of line objects, thus comma
        line1, = ax.plot(datax, datay[t0ind])

        def init():
            line1.set_ydata(np.ma.array(datax, mask=True))
            ttl.set_text('')
            return line1, ttl

        def animate(tind):
            line1.set_ydata(datay[tind])
            t_current = times[tind]
            tfrac = (t_current - tmin) / (tmax - tmin) * 100
            ttl.set_text(ttl_fmt.format(perc=tfrac))
            return line1, ttl

    else:
        raise Exception("Unexpected plot type argument. See README.md.")

    ani = manim.FuncAnimation(fig,
                              animate,
                              frames=numtimes,
                              interval=50,
                              blit=True,
                              repeat=False,
                              init_func=init)
    if save_flag:
        fig.tight_layout()
        ani.save("mpet_{type}.mp4".format(type=plot_type),
                 fps=25,
                 bitrate=5500)

    return fig, ax, ani
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

fig, ax = plt.subplots()
sin_l, = ax.plot(np.sin(0))
cos_l, = ax.plot(np.cos(0))
ax.set_ylim(-1, 1)
ax.set_xlim(0, 5)
dx = 0.1


def update(i):
    # i is a counter for each frame.
    # We'll increment x by dx each frame.
    x = np.arange(0, i) * dx
    sin_l.set_data(x, np.sin(x))
    cos_l.set_data(x, np.cos(x))
    return sin_l, cos_l


ani = animation.FuncAnimation(fig, update, frames=51, interval=50)
plt.show()
 def show(self):
     plt.plot([], [], 'r-')
     self.ani = animation.FuncAnimation(self.figure,
                                        self.evolve,
                                        interval=self.animationInterval)
     plt.show()
Beispiel #21
0
        newpop.append(n1)
        newpop.append(n2)

    population = newpop


def update(t):
    fig.clear()

    ax1 = fig.add_subplot(2, 1, 1)
    ax1.plot(averageFitness)
    ax1.set_title('g = ' + str(t))
    ax1.plot(bestFitness)
    ax1.set_xlabel("generaiton")
    ax1.set_ylabel("average / best fitness")

    ax2 = fig.add_subplot(2, 1, 2)
    ax2.plot(sx, sy)
    ax2.plot(pp, pf, ".")
    ax2.set_xlabel("x")
    ax2.set_ylabel("fitness")

    fig.tight_layout()


ani = animation.FuncAnimation(fig,
                              main_loop,
                              np.arange(0, T),
                              interval=25,
                              repeat=False)
plt.show()
Beispiel #22
0
        i2 = -1

    xPBH1 = np.vstack([xPBH1, x[i1, :]])
    zp = xPBH1[:, (2, )].T
    #timetext.set_text("t = %0.3f kyr"%(time))

    pTrack.set_xdata(xPBH1[:, (0, )])
    pTrack.set_ydata(xPBH1[:, (1, )])
    #print xPBH1[:, (2,)]
    pTrack.set_3d_properties(zs=zp)
    #pPBH1.set_offsets(x[i1,:])
    #a,b,c = p2._offsets3d
    pPBH1._offsets3d = (x[i1, (0, )], x[i1, (1, )], x[i1, (2, )])
    #pPBH2.set_offsets(x[i2,:])
    pPBH2._offsets3d = (x[i2, (0, )], x[i2, (1, )], x[i2, (2, )])

    #p2.set_offsets(x2[:,:])
    dinds = np.abs(x2[:, 2]) < zh
    p2._offsets3d = (x2[dinds, 0], x2[dinds, 1], x2[dinds, 2])
    #circle1.center = (x[:,0], x[:,1])

    return pPBH1, pPBH2, p2, pTrack, tittext


anim = animation.FuncAnimation(fig, animate, frames=Nframes)
anim.save('../movies/2D_binary_' + runID + '.mp4',
          fps=70,
          bitrate=-1,
          codec='libx264',
          extra_args=['-pix_fmt', 'yuv420p'],
          dpi=300)
Beispiel #23
0
def main():

    ######################################
    ###  Parameter
    ######################################
    mod_param = model_param.Model_params("CALTECH256", "VGG16_CAM5b_S",
                                         'rmsProp', 1e-4, 5e-5, 5e-7)
    model = Forward_model(mod_param, 44)
    labels = model.mod_param.labels
    PEPPER_IP = "10.0.165.29"  # jmot.local
    PEPPER_IP = "10.0.161.43"  # jarc.local
    LOCAL_IP = "10.0.164.160"
    LOCAL_PORT = 8081
    LOCAL_SERVER = "http://" + LOCAL_IP + ":8081/"
    LOCAL_SERVER_FOLDER = '/home/cuda/work/cm_perso/py/image_server/'

    ######################################
    ### Load video stream of pepper
    ######################################
    vStream = VideoStream(PEPPER_IP)
    img = vStream.getFrame()

    # Load naoqi tablet service to display image
    from naoqi import ALProxy
    tabletService = ALProxy("ALTabletService", PEPPER_IP, 9559)
    tts = ALProxy("ALTextToSpeech", PEPPER_IP, 9559)
    led = ALProxy("ALLeds", PEPPER_IP, 9559)

    ######################################
    ### To visualize on pepper,
    ###  launch an HTTP server in :
    ###  /home/cuda/work/cm_perso/py/image_server
    ###  $ python2 -m SimpleHTTPServer 8081
    ######################################

    # build the bar's colors
    import colorsys
    N = len(model.labels)
    HSV_tuples = [(x * 1.0 / N, .8 if x % 2 else 1, .8 if x % 2 else 1)
                  for x in range(N)]
    RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
    colors = RGB_tuples

    ######################################
    ### Plotting time !!
    ######################################
    img, named_preds, vis = get_img_pred_and_vis(do_resize=False)
    summed_viz = summed_vis(model, vis)

    lbl_idx = []
    lbl_idx.append(labels.index("head-phones"))
    lbl_idx.append(labels.index("people"))
    lbl_idx.append(labels.index("soda-can"))
    lbl_idx.append(labels.index("cereal-box"))
    lbl_idx.append(labels.index("coffee-mug"))
    lbl_idx.append(labels.index("eyeglasses"))
    lbl_idx.append(labels.index("computer-keyboard"))

    thresholds = {
        'airplanes-101': 15.539495,
        'ak47': 11.614439,
        'american-flag': 10.979799,
        'backpack': 12.223079,
        'baseball-bat': 9.5437927,
        'baseball-glove': 13.739741,
        'basketball-hoop': 6.8361239,
        'bat': 9.3481636,
        'bathtub': 11.226589,
        'bear': 12.300051,
        'beer-mug': 10.193258,
        'billiards': 13.462406,
        'binoculars': 14.34924,
        'birdbath': 8.5118666,
        'blimp': 10.230799,
        'bonsai-101': 14.111417,
        'boom-box': 9.4953127,
        'bowling-ball': 12.180779,
        'bowling-pin': 13.188916,
        'boxing-glove': 12.254652,
        'brain-101': 10.274245,
        'breadmaker': 12.863352,
        'buddha-101': 9.4291439,
        'bulldozer': 12.71928,
        'butterfly': 12.233453,
        'cactus': 11.847659,
        'cake': 9.6894112,
        'calculator': 11.544846,
        'camel': 10.984636,
        'cannon': 11.45732,
        'canoe': 8.5938473,
        'car-side-101': 15.239647,
        'car-tire': 10.235177,
        'cartman': 13.4251,
        'cd': 14.570348,
        'centipede': 11.146159,
        'cereal-box': 9.5662346,
        'chandelier-101': 14.05705,
        'chess-board': 14.479905,
        'chimp': 11.409027,
        'chopsticks': 9.7986164,
        'clutter': 6.7525487,
        'cockroach': 11.884217,
        'coffee-mug': 9.8205605,
        'coffin': 7.9233661,
        'coin': 13.396132,
        'comet': 13.854059,
        'computer-keyboard': 9.3863621,
        'computer-monitor': 12.101433,
        'computer-mouse': 9.4048815,
        'conch': 10.171927,
        'cormorant': 13.560222,
        'covered-wagon': 10.693968,
        'cowboy-hat': 11.713959,
        'crab-101': 7.8341355,
        'desk-globe': 11.701681,
        'diamond-ring': 14.189276,
        'dice': 12.145127,
        'dog': 10.916739,
        'dolphin-101': 13.114321,
        'doorknob': 5.0762424,
        'drinking-straw': 11.298171099057921,
        'duck': 8.0495834,
        'dumb-bell': 10.45462,
        'eiffel-tower': 12.312577,
        'electric-guitar-101': 12.958621,
        'elephant-101': 14.492549,
        'elk': 13.485504,
        'ewer-101': 9.8520899,
        'eyeglasses': 12.613165,
        'faces-easy-101': 14.780043,
        'fern': 14.704705,
        'fighter-jet': 8.7353821,
        'fire-extinguisher': 9.8947344,
        'fire-hydrant': 11.806909,
        'fire-truck': 13.965515,
        'fireworks': 13.296287,
        'flashlight': 8.1808243,
        'floppy-disk': 7.1887569,
        'football-helmet': 10.615582,
        'french-horn': 13.687181,
        'fried-egg': 10.432892,
        'frisbee': 11.636504,
        'frog': 9.7874126,
        'frying-pan': 13.031361,
        'galaxy': 13.235175,
        'gas-pump': 9.2886629,
        'giraffe': 11.326241,
        'goat': 11.352355,
        'golden-gate-bridge': 10.316961,
        'goldfish': 9.4651136,
        'golf-ball': 13.796005,
        'goose': 10.911978,
        'gorilla': 14.111794,
        'grand-piano-101': 12.888706,
        'grapes': 15.015621,
        'grasshopper': 11.786924,
        'greyhound': 10.316483,
        'guitar-pick': 13.68029,
        'hamburger': 15.062843,
        'hammock': 9.5732231,
        'harmonica': 9.8693962,
        'harp': 11.529077,
        'harpsichord': 11.165341,
        'hawksbill-101': 11.578585,
        'head-phones': 13.229425,
        'helicopter-101': 10.342123,
        'hibiscus': 15.14535,
        'homer-simpson': 12.982221,
        'horse': 10.339157,
        'horseshoe-crab': 8.7140741,
        'hot-air-balloon': 11.959567,
        'hot-dog': 7.6435122,
        'hot-tub': 14.082646,
        'hourglass': 8.5736504,
        'house-fly': 10.245955,
        'human-skeleton': 11.28433,
        'hummingbird': 13.007446,
        'ibis-101': 13.071635,
        'ice-cream-cone': 8.9562511,
        'iguana': 10.795525,
        'ipod': 11.828806,
        'iris': 13.975347,
        'jesus-christ': 7.8586192,
        'joy-stick': 10.704171,
        'kangaroo-101': 10.39012,
        'kayak': 10.973958,
        'ketch-101': 14.624043,
        'killer-whale': 10.278771,
        'knife': 7.0219631,
        'ladder': 10.223049,
        'laptop-101': 14.154712,
        'lathe': 10.909991,
        'leopards-101': 13.462743,
        'license-plate': 9.1783524,
        'light-house': 13.667336,
        'lightbulb': 9.0387936,
        'lightning': 14.409019,
        'llama-101': 13.470165,
        'mailbox': 6.5361915,
        'mandolin': 7.0408216,
        'mars': 15.681169,
        'mattress': 13.038775,
        'megaphone': 9.5789099,
        'menorah-101': 11.231406,
        'microscope': 13.210646,
        'microwave': 12.780502,
        'minaret': 14.352889,
        'minotaur': 8.7425909,
        'motorbikes-101': 14.512385,
        'mountain-bike': 11.489552,
        'mushroom': 9.2215405,
        'mussels': 9.5242481,
        'necktie': 12.587179,
        'octopus': 10.618414,
        'ostrich': 13.737724,
        'owl': 12.664935,
        'palm-pilot': 10.367587,
        'palm-tree': 13.79882,
        'paper-shredder': 10.851973,
        'paperclip': 7.6281219,
        'pci-card': 13.879761,
        'penguin': 12.622005,
        'people': 10.127394,
        'pez-dispenser': 10.151289,
        'photocopier': 12.675723,
        'picnic-table': 11.054971,
        'playing-card': 8.0703611,
        'porcupine': 14.769379,
        'pram': 8.6249542,
        'praying-mantis': 7.9761715,
        'pyramid': 9.2024403,
        'raccoon': 13.569774,
        'radio-telescope': 9.3716202,
        'rainbow': 14.275431,
        'refrigerator': 10.21283,
        'revolver-101': 9.7003441,
        'rifle': 7.8262658,
        'rotary-phone': 8.7905035,
        'roulette-wheel': 13.088307,
        'saddle': 12.905226,
        'saturn': 13.530177,
        'school-bus': 14.30421,
        'scorpion-101': 11.310881,
        'screwdriver': 8.5278797,
        'segway': 9.8139648,
        'self-propelled-lawn-mower': 13.614111,
        'sextant': 10.938291,
        'sheet-music': 12.781863,
        'skateboard': 5.3709097,
        'skunk': 12.385101,
        'skyscraper': 10.209162,
        'smokestack': 8.4563723,
        'snail': 10.329622,
        'snake': 11.788112,
        'sneaker': 11.271756,
        'snowmobile': 12.525217,
        'soccer-ball': 13.321915,
        'socks': 12.545236,
        'soda-can': 5.3792729,
        'spaghetti': 14.648598,
        'speed-boat': 8.1863899,
        'spider': 10.452264,
        'spoon': 7.7456422,
        'stained-glass': 12.208684,
        'starfish-101': 9.5304241,
        'steering-wheel': 10.538023,
        'stirrups': 9.0607805,
        'sunflower-101': 15.126546,
        'superman': 10.417388,
        'sushi': 10.138167,
        'swan': 13.547839,
        'swiss-army-knife': 12.918182,
        'sword': 6.741322,
        'syringe': 11.86831,
        't-shirt': 12.696012,
        'tambourine': 11.732224,
        'teapot': 11.243834,
        'teddy-bear': 13.073026,
        'teepee': 13.556503,
        'telephone-box': 12.293881,
        'tennis-ball': 13.999656,
        'tennis-court': 13.988853,
        'tennis-racket': 11.597626,
        'tennis-shoes': 12.119856,
        'theodolite': 8.5096235,
        'toad': 14.345215,
        'toaster': 8.2721653,
        'tomato': 13.720393,
        'tombstone': 8.7411394,
        'top-hat': 10.413415,
        'touring-bike': 13.964041,
        'tower-pisa': 14.130401,
        'traffic-light': 9.1431026,
        'treadmill': 11.544156,
        'triceratops': 9.1150694,
        'tricycle': 7.9400773,
        'trilobite-101': 9.9814043,
        'tripod': 12.860129,
        'tuning-fork': 8.508173,
        'tweezer': 12.786347,
        'umbrella-101': 14.133526,
        'unicorn': 8.989871,
        'vcr': 13.953634,
        'video-projector': 13.71447,
        'washing-machine': 13.383274,
        'watch-101': 14.873101,
        'waterfall': 11.931628,
        'watermelon': 13.523896,
        'welding-mask': 9.4707451,
        'wheelbarrow': 6.9907722,
        'windmill': 8.115716,
        'wine-bottle': 11.967635,
        'xylophone': 10.102029,
        'yarmulke': 10.422739,
        'yo-yo': 8.1963339,
        'zebra': 12.6486
    }
    thresholds = {
        'airplanes-101': 5.5431083e+14,
        'ak47': 3.0300088e+16,
        'american-flag': 3.5716338e+16,
        'backpack': 1.9385098e+12,
        'baseball-bat': 1.5624532e+09,
        'baseball-glove': 1.6674185e+13,
        'basketball-hoop': 21648198.0,
        'bat': 5.3302285e+08,
        'bathtub': 4.081619e+13,
        'bear': 5.1944895e+13,
        'beer-mug': 1.2813283e+09,
        'billiards': 1.8982378e+19,
        'binoculars': 2.4670087e+11,
        'birdbath': 86495976.0,
        'blimp': 5.466241e+10,
        'bonsai-101': 1.2646443e+14,
        'boom-box': 3.2918062e+09,
        'bowling-ball': 2.4476167e+11,
        'bowling-pin': 3.577533e+16,
        'boxing-glove': 6.7875977e+13,
        'brain-101': 9.9880776e+09,
        'breadmaker': 3.2294382e+12,
        'buddha-101': 3.8930813e+10,
        'bulldozer': 6.2439028e+16,
        'butterfly': 1.0646077e+11,
        'cactus': 8.1894794e+09,
        'cake': 7.40256e+09,
        'calculator': 3.5660982e+11,
        'camel': 1.664745e+10,
        'cannon': 6.9733033e+09,
        'canoe': 50444132.0,
        'car-side-101': 3.7557727e+10,
        'car-tire': 3.0141978e+08,
        'cartman': 6.5723494e+13,
        'cd': 6.4437289e+10,
        'centipede': 1.2770371e+12,
        'cereal-box': 2.6240285e+08,
        'chandelier-101': 8.2653332e+13,
        'chess-board': 2.2851635e+14,
        'chimp': 7.410362e+11,
        'chopsticks': 2.4793016e+11,
        'clutter': 8339.2676,
        'cockroach': 5.4527033e+10,
        'coffee-mug': 1.480877e+08,
        'coffin': 5039319.5,
        'coin': 1.3312232e+11,
        'comet': 2.0706677e+10,
        'computer-keyboard': 1.0867948e+09,
        'computer-monitor': 7.1442136e+12,
        'computer-mouse': 47223632.0,
        'conch': 1.8807533e+08,
        'cormorant': 3.2918025e+15,
        'covered-wagon': 5.9376696e+12,
        'cowboy-hat': 2.4143793e+09,
        'crab-101': 4341659.0,
        'desk-globe': 9.4681735e+10,
        'diamond-ring': 1.9219957e+14,
        'dice': 1.4127444e+10,
        'dog': 4.6726865e+10,
        'dolphin-101': 5.9940569e+11,
        'doorknob': 13459.243,
        'drinking-straw': 1.4986623698626245e+19,
        'duck': 3049474.0,
        'dumb-bell': 4.0482092e+11,
        'eiffel-tower': 3.5857907e+19,
        'electric-guitar-101': 4.0460525e+16,
        'elephant-101': 1.2808333e+15,
        'elk': 1.1112351e+13,
        'ewer-101': 1.4056063e+11,
        'eyeglasses': 1.9051025e+11,
        'faces-easy-101': 2.2937489e+11,
        'fern': 7.1044002e+12,
        'fighter-jet': 7798978.0,
        'fire-extinguisher': 1.719988e+10,
        'fire-hydrant': 9.6152668e+14,
        'fire-truck': 3.3854999e+14,
        'fireworks': 6.6339655e+12,
        'flashlight': 1.5764622e+08,
        'floppy-disk': 139934.2,
        'football-helmet': 6.6389512e+10,
        'french-horn': 9.3023247e+15,
        'fried-egg': 4.9036191e+09,
        'frisbee': 1.0446183e+08,
        'frog': 6.0765036e+09,
        'frying-pan': 3.2934395e+16,
        'galaxy': 1.2823036e+11,
        'gas-pump': 4.143339e+09,
        'giraffe': 3.8628279e+12,
        'goat': 7.5328881e+11,
        'golden-gate-bridge': 7.8824473e+10,
        'goldfish': 1.0932602e+09,
        'golf-ball': 1.3780492e+20,
        'goose': 6.2447514e+12,
        'gorilla': 2.1993976e+12,
        'grand-piano-101': 2.8961075e+15,
        'grapes': 1.5072703e+13,
        'grasshopper': 1.8578018e+10,
        'greyhound': 1.8462416e+13,
        'guitar-pick': 5.1328466e+13,
        'hamburger': 4.2002609e+14,
        'hammock': 3.3486584e+09,
        'harmonica': 9.5709587e+08,
        'harp': 8.1178002e+13,
        'harpsichord': 3.7312467e+10,
        'hawksbill-101': 7.3944072e+10,
        'head-phones': 3.4009946e+13,
        'helicopter-101': 2.1896231e+10,
        'hibiscus': 1.8412439e+12,
        'homer-simpson': 1.5423778e+12,
        'horse': 5.6068927e+10,
        'horseshoe-crab': 4.2088189e+09,
        'hot-air-balloon': 3.2325625e+13,
        'hot-dog': 7944667.0,
        'hot-tub': 8.2769019e+14,
        'hourglass': 7.5616689e+11,
        'house-fly': 3.1041532e+10,
        'human-skeleton': 5.0458438e+08,
        'hummingbird': 1.7925873e+15,
        'ibis-101': 1.9916933e+17,
        'ice-cream-cone': 63787136.0,
        'iguana': 2.2303822e+10,
        'ipod': 1.207799e+13,
        'iris': 1.0276757e+13,
        'jesus-christ': 14475644.0,
        'joy-stick': 7.2560395e+12,
        'kangaroo-101': 4.879786e+10,
        'kayak': 1.1078073e+12,
        'ketch-101': 3.8059018e+12,
        'killer-whale': 2.6241966e+09,
        'knife': 19238.672,
        'ladder': 1.5208937e+09,
        'laptop-101': 1.1846513e+16,
        'lathe': 1.7692549e+12,
        'leopards-101': 1.6646305e+09,
        'license-plate': 1.1828102e+12,
        'light-house': 3.6549751e+21,
        'lightbulb': 19177000.0,
        'lightning': 1.4482883e+12,
        'llama-101': 6.7335113e+13,
        'mailbox': 2773471.5,
        'mandolin': 18860346.0,
        'mars': 1.6402625e+11,
        'mattress': 3.1016109e+15,
        'megaphone': 4.2023346e+10,
        'menorah-101': 3.3722458e+12,
        'microscope': 4.1738928e+13,
        'microwave': 8.5503303e+13,
        'minaret': 3.1610025e+18,
        'minotaur': 32122660.0,
        'motorbikes-101': 2.8167275e+14,
        'mountain-bike': 5.9001851e+09,
        'mushroom': 53559256.0,
        'mussels': 2.2473357e+08,
        'necktie': 3.1209993e+11,
        'octopus': 2.6431208e+08,
        'ostrich': 1.7842261e+15,
        'owl': 6.5421483e+13,
        'palm-pilot': 2.3683363e+12,
        'palm-tree': 7.7542704e+12,
        'paper-shredder': 1.3108989e+08,
        'paperclip': 1352188.0,
        'pci-card': 1.9177542e+14,
        'penguin': 3.0658302e+14,
        'people': 5.2147927e+09,
        'pez-dispenser': 6.3548403e+14,
        'photocopier': 1.0440469e+13,
        'picnic-table': 3.8073414e+10,
        'playing-card': 5538763.0,
        'porcupine': 6.9250853e+12,
        'pram': 18372230.0,
        'praying-mantis': 1.560399e+08,
        'pyramid': 4.8814873e+11,
        'raccoon': 1.655157e+17,
        'radio-telescope': 2.3465157e+10,
        'rainbow': 8.7877876e+14,
        'refrigerator': 44751656.0,
        'revolver-101': 1.8511545e+12,
        'rifle': 9.0105306e+08,
        'rotary-phone': 2.1230793e+09,
        'roulette-wheel': 3.5503577e+12,
        'saddle': 3.9173898e+11,
        'saturn': 9.6435749e+10,
        'school-bus': 2.8633875e+16,
        'scorpion-101': 2.0427739e+10,
        'screwdriver': 26136550.0,
        'segway': 1.8123455e+14,
        'self-propelled-lawn-mower': 2.1806294e+14,
        'sextant': 8.092094e+09,
        'sheet-music': 3.0781233e+10,
        'skateboard': 14456.855,
        'skunk': 1.5204825e+16,
        'skyscraper': 42357828.0,
        'smokestack': 3.6834967e+09,
        'snail': 3.002801e+08,
        'snake': 1.6795233e+10,
        'sneaker': 2.9544725e+12,
        'snowmobile': 1.7613053e+13,
        'soccer-ball': 2.3668703e+15,
        'socks': 1.2557998e+12,
        'soda-can': 4422.9951,
        'spaghetti': 9.0263502e+13,
        'speed-boat': 6.3242834e+09,
        'spider': 2.2383148e+09,
        'spoon': 17250952.0,
        'stained-glass': 4.3774906e+13,
        'starfish-101': 4.5136595e+08,
        'steering-wheel': 2.6580664e+09,
        'stirrups': 5.438729e+08,
        'sunflower-101': 2.0106238e+15,
        'superman': 1.3998532e+12,
        'sushi': 3.5312387e+09,
        'swan': 1.5102679e+14,
        'swiss-army-knife': 2.9733163e+13,
        'sword': 97893.102,
        'syringe': 2.4944873e+11,
        't-shirt': 8.4770243e+09,
        'tambourine': 1.0646093e+10,
        'teapot': 1.3279314e+10,
        'teddy-bear': 3.1996138e+12,
        'teepee': 4.4722962e+16,
        'telephone-box': 1.7343836e+13,
        'tennis-ball': 1.129395e+13,
        'tennis-court': 1.6999828e+15,
        'tennis-racket': 4.39301e+13,
        'tennis-shoes': 2.5194111e+10,
        'theodolite': 47372728.0,
        'toad': 8.3253107e+12,
        'toaster': 10031872.0,
        'tomato': 5.2412243e+12,
        'tombstone': 15937872.0,
        'top-hat': 4.3982733e+08,
        'touring-bike': 2.7450732e+11,
        'tower-pisa': 7.2208215e+13,
        'traffic-light': 6.6413796e+11,
        'treadmill': 7.972144e+12,
        'triceratops': 1.0741414e+09,
        'tricycle': 11951269.0,
        'trilobite-101': 1.2566726e+09,
        'tripod': 4.0014282e+16,
        'tuning-fork': 356258.0,
        'tweezer': 6.7144122e+11,
        'umbrella-101': 4.9185605e+13,
        'unicorn': 6.2804467e+08,
        'vcr': 1.2763661e+14,
        'video-projector': 3.2985965e+12,
        'washing-machine': 2.8531178e+13,
        'watch-101': 1.230518e+13,
        'waterfall': 2.739926e+11,
        'watermelon': 1.5243077e+11,
        'welding-mask': 2.7199916e+10,
        'wheelbarrow': 97438696.0,
        'windmill': 8.450663e+08,
        'wine-bottle': 6.4735841e+14,
        'xylophone': 2.0981789e+10,
        'yarmulke': 2.365763e+10,
        'yo-yo': 2.1747139e+08,
        'zebra': 4.6917522e+13
    }
    # for key in thresholds: thresholds[key] *= 1.5

    # First plot
    fig, axs = plt.subplots(2, (len(lbl_idx) + 1) / 2)
    axs = [a for b in axs for a in b]
    ims = []
    ims.append(axs[0].imshow(img, animated=True))
    for i in range(len(lbl_idx)):
        ims.append(axs[i + 1].imshow(summed_viz[0, :, :, lbl_idx[i]],
                                     vmin=0,
                                     vmax=thresholds.values()[lbl_idx[i]]))
        axs[i + 1].set_title(labels[lbl_idx[i]])

    # update function
    def updatefig(*args):
        img, named_preds, vis = get_img_pred_and_vis(do_resize=False)
        summed_viz = summed_vis(model, vis)

        # Update the axis
        ims[0].set_array(img)
        for i in range(len(lbl_idx)):
            data = np.exp(summed_viz[0, :, :, lbl_idx[i]])
            ims[i + 1].set_array(data)

        # print_vis_stat(summed_viz, lbl_idx)
        # print_sorted_preds(named_preds)
        print_over_threshold(summed_viz, thresholds, named_preds)

        return ims

    ani1 = animation.FuncAnimation(fig, updatefig, interval=10, blit=False)
    fig.show()
Beispiel #24
0
h = predict(theta, X)
print(np.sum(h==y) / len(y) * 100)

theta = history[0][0]
plot_x = np.array([min(X[:, 1]) - 2, max(X[:, 1]) + 2])


def cal_y(theta):
    plot_y = -1 / theta[2] * (theta[1]*plot_x + theta[0])
    return plot_y


line, = ax.plot(plot_x, cal_y(theta))

def animate(history):
    def _wrapper(i):
        theta, error = history[i]
        h = predict(theta, X)
        acc = np.sum(h==y) / len(y)
        line.set_ydata(cal_y(theta))
        sys.stdout.flush()
        sys.stdout.write('{:5d} / {:5d}, {:5.2%} | {:6.3f}, {:6.2%}\r'.format(
            i, len(history), i / len(history), error, acc))
        return line
    return _wrapper

anim = animation.FuncAnimation(fig, animate(history), np.arange(len(history)),
                               interval=10)
plt.show()
Beispiel #25
0
#---------------------------------------------------------------------------------------------------


# Again this is only ploting information
#---------------------------------------------------------------------------------------------------

# Trajectory of the vector in s-space
ax.plot(s[:,0],s[:,1],s[:,2], color = 'red')

# Initial frame
plot = [ax.quiver( 0, 0, 0, s[0,0], s[0,1], s[0,2],  linewidth = 3.0, color = "orange"),
        ax.quiver( 0, 0, 0, 0, 0, s[0,2],  linewidth = 3.0, color = "green")]

# Animation
animate = animation.FuncAnimation(fig, update_plot, nmax, fargs=(v, plot))

#---------------------------------------------------------------------------------------------------
# Saving. You can change the name of the file. 

# To generate a gif we need to install imagemagick. Then use the following line
animate.save('OBE.gif',writer='imagemagick')

# If we don't want to download imagemagick then we can just generate a mp4 file

#animate.save('OBE.mp4', writer = None)
plt.show()



Beispiel #26
0
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation

spaceresolution = 100
timeresolution = 60

fig, ax = plt.subplots()
x = np.linspace(0,1,spaceresolution)
line, = ax.plot(x, x*(1-x))

def draw(u):
    line.set_ydata(x*u*(1-x))
    return line,

plt.xlim(0, 1)
plt.ylim(0, 1)

plt.plot(x,x)
ani = animation.FuncAnimation(fig, draw, np.linspace(1,4,timeresolution), interval=10)
plt.show()
Beispiel #27
0
    def draw_it(self, **args):
        # user input functions to add
        self.g1 = args['g1']  # input function
        self.g2 = args['g2']
        # input function
        num_frames = 100
        if 'num_frames' in args:
            num_frames = args['num_frames']
        min_range = -3
        if 'min_range' in args:
            min_range = args['min_range']
        max_range = -3
        if 'max_range' in args:
            max_range = args['max_range']
        if 'title1' in args:
            title1 = args['title1']
        else:
            title1 = '$g_1$'
        if 'title2' in args:
            title2 = args['title2']
        else:
            title2 = '$g_2$'
        if 'title3' in args:
            title3 = args['title3']
        else:
            title3 = '$\\alpha\,g_1 + (1 - \\alpha)\,g_2$'

        # initialize figure
        fig = plt.figure(figsize=(15, 5))
        artist = fig
        ax1 = fig.add_subplot(131)
        ax2 = fig.add_subplot(132)
        ax3 = fig.add_subplot(133)

        # generate base function for plotting on each slide
        w_plot = np.linspace(min_range, max_range, 200)
        g1_plot = self.g1(w_plot)
        g2_plot = self.g2(w_plot)

        # set vertical limit markers
        g1_min = np.amin(g1_plot)
        g2_min = np.amin(g2_plot)
        g1_max = np.amax(g1_plot)
        g2_max = np.amax(g2_plot)
        g1_gap = 0.2 * (g1_max - g1_min)
        g2_gap = 0.2 * (g2_max - g2_min)

        g1_min = np.amin(g1_plot) - g1_gap
        g2_min = np.amin(g2_plot) - g2_gap
        g1_max = np.amax(g1_plot) + g1_gap
        g2_max = np.amax(g2_plot) + g2_gap

        # decide on number of slides
        alpha_vals = np.linspace(1, 0, num_frames)
        print('starting animation rendering...')

        # animation sub-function
        def animate(k):
            # clear panels for next slide
            ax1.cla()
            ax2.cla()
            ax3.cla()

            # print rendering update
            if np.mod(k + 1, 25) == 0:
                print('rendering animation frame ' + str(k + 1) + ' of ' +
                      str(num_frames))
            if k == num_frames - 1:
                print('animation rendering complete!')
                time.sleep(1.5)
                clear_output()

            # plot function 1
            ax1.plot(w_plot, g1_plot, color='k', zorder=1)
            ax1.set_title(title1, fontsize=15)

            # plot function 2
            ax2.plot(w_plot, g2_plot, color='k', zorder=1)
            ax2.set_title(title2, fontsize=15)

            # plot combination of both
            alpha = alpha_vals[k]
            g_combo = alpha * g1_plot + (1 - alpha) * g2_plot
            ax3.plot(w_plot, g_combo, color='k', zorder=1)
            ax3.set_title(title3, fontsize=15)

            # set vertical limits
            ax1.set_ylim([g1_min, g1_max])
            ax2.set_ylim([g2_min, g2_max])

            # set vertical limit markers
            gmin = np.amin(g_combo)
            gmax = np.amax(g_combo)
            g_gap = 0.2 * (gmax - gmin)
            gmin = gmin - g_gap
            gmax = gmax + g_gap
            ax3.set_ylim([gmin, gmax])

            return artist,

        anim = animation.FuncAnimation(fig,
                                       animate,
                                       frames=num_frames,
                                       interval=num_frames,
                                       blit=True)

        return (anim)
Beispiel #28
0
# Fifty lines of random 3-D lines
data = [nd]

# Creating fifty line objects.
# NOTE: Can't pass empty arrays into 3d version of plot()
lines = [ax.plot(dat[0, 0:1], dat[1, 0:1], dat[2, 0:1])[0] for dat in data]

# Setting the axes properties
ax.set_xlim3d([0, 2])
ax.set_xlabel('t')

ax.set_ylim3d([-0.001, 0.001])
ax.set_ylabel('X')

ax.set_zlim3d([-0.001, 0.001])
ax.set_zlabel('Y')

ax.set_title('3D Test')

# Creating the Animation object
line_ani = animation.FuncAnimation(fig,
                                   update_lines,
                                   int(nd.shape[1] / 100),
                                   fargs=(data, lines, ax),
                                   interval=1,
                                   blit=False)

plt.show()
pass
            min_amp = int(math.floor(amp_data.min()))
            max_amp = int(math.floor(amp_data.max()))

            ax2.hist(amp_data, bins=range(min_amp, max_amp + 1, 1), facecolor='blue', alpha=1,
                     edgecolor='black', linewidth=.5)
            ax2.set_xlabel('Amplitude/db', weight='bold', fontsize=12)
            ax2.set_ylabel('Count', weight='bold', fontsize=12)

            print(time.time() - start)

        except Exception as e:
            print(repr(e))


if __name__ == '__main__':
    """
    Assumptions
    Data is dumped at least after 5 seconds after inception
    """
    data_plotter = FogDataPlotter()
    # data_plotter.loaddata()

    fig, ((axx1, axx2), (axx3, axx4)) = plt.subplots(2, 2)
    fig.suptitle('    Fog View', fontsize=18, weight='bold')
    fig.text(.485, .5, '.', fontsize='200', color='g')
    fig.patch.set_facecolor((0.96, 0.968, 0.851))

    simulation = animation.FuncAnimation(fig, data_plotter.update_data, repeat=False, fargs=(axx1, axx2, axx3, axx4))
    # plt.tight_layout()
    # plt.show()
    right_side = np.dot(B_mat, s_t)
    s_tnext = np.linalg.solve(A_mat, right_side)
    s_t = s_tnext

    Z = np.array([[0. for i in range(Q + 1)] for j in range(N_half)])

    for i in range(N_half):
        for j in range(Q):
            if j == 0:
                Z[i][j] = s_t[i * Q + j]
                Z[i][Q] = s_t[i * Q + j]
            else:
                Z[i][j] = s_t[i * Q + j]

    cont = plt.pcolormesh(X, Y, Z, cmap='plasma', vmin=temp_min, vmax=temp_max)

    plt.title(r'$t$ = %i$\Delta t$' % (k))
    plt.suptitle(r'Temperature $U/U_{0}$')

    return cont


anim = animation.FuncAnimation(fig, animate, frames=20, blit=False)

# Un-commenting the following line will save the animation as a mp4 file.
#anim.save('ring_bc3.mp4', fps=15)

# Un-commenting the following line will show the animation of the solution being
# solved in real time.
plt.show()