def _make_Phase_Space_Video_For_X_Array(self, videoTitle,
                                         xOrbitSnapShotArr, xaxis, yaxis,
                                         alpha, fps, dpi):
     fig, axes = plt.subplots(2, 1)
     camera = celluloid.Camera(fig)
     labels, unitModifier = self._get_Axis_Labels_And_Unit_Modifiers(
         xaxis, yaxis)
     swarmAxisIndex = 0
     latticeAxisIndex = 1
     axes[swarmAxisIndex].set_xlabel(labels[0])
     axes[swarmAxisIndex].set_ylabel(labels[1])
     axes[swarmAxisIndex].text(0.1,
                               1.1,
                               'Phase space portraint',
                               transform=axes[swarmAxisIndex].transAxes)
     axes[latticeAxisIndex].set_xlabel('meters')
     axes[latticeAxisIndex].set_ylabel('meters')
     for xOrbit, i in zip(xOrbitSnapShotArr, range(len(xOrbitSnapShotArr))):
         snapShotPhaseSpaceCoords = SwarmSnapShot(
             self.swarm, xOrbit).get_Surviving_Particle_PhaseSpace_Coords()
         if len(snapShotPhaseSpaceCoords) == 0:
             break
         else:
             xCoordsArr, yCoordsArr = self._get_Plot_Data_From_SnapShot(
                 snapShotPhaseSpaceCoords, xaxis, yaxis)
             revs = int(xOrbit / self.lattice.totalLength)
             deltaX = xOrbit - revs * self.lattice.totalLength
             axes[swarmAxisIndex].text(
                 0.1,
                 1.01,
                 'Revolutions: ' + str(revs) +
                 ', Distance along revolution: ' +
                 str(np.round(deltaX, 2)) + 'm',
                 transform=axes[swarmAxisIndex].transAxes)
             axes[swarmAxisIndex].scatter(xCoordsArr * unitModifier[0],
                                          yCoordsArr * unitModifier[1],
                                          c='blue',
                                          alpha=alpha,
                                          edgecolors=None,
                                          linewidths=0.0)
             axes[swarmAxisIndex].grid()
             xSwarmLab, ySwarmLab = self.lattice.get_Lab_Coords_From_Orbit_Distance(
                 xOrbit)
             self.plot_Lattice_On_Axis(axes[latticeAxisIndex],
                                       [xSwarmLab, ySwarmLab])
             camera.snap()
     plt.tight_layout()
     animation = camera.animate()
     animation.save(str(videoTitle) + '.gif', fps=fps, dpi=dpi)
def animate(neurons, dts, num_neurons):
    # timesteps = 10
    timesteps = dts

    heatmap = np.zeros((timesteps, 3, 2, 10, 10))
    spikes = np.zeros((timesteps, 100))

    exc_labels = [
        "Spikes", "Null", "Resting Voltage (mV)", "Threshold Voltage (mV)",
        "Refractory Time (ms)", "Gain"
    ]
    offsets = [V_rest, V_th, par['tau_ref'], 0]

    fig, axs = plt.subplots(3, 2)
    camera = celluloid.Camera(fig)

    for timestep in tqdm(np.arange(1, timesteps), desc="Rendering"):  # dts
        spikes[timestep] = [
            neurons[0][neuron].spikes[timestep] / V_spike
            for neuron in np.arange(num_neurons)
        ]

        for row in np.arange(np.shape(axs)[0]):
            for col in np.arange(np.shape(axs)[1]):
                for i in np.arange(10):
                    for j in np.arange(10):
                        if row == 0 and col == 0:
                            heatmap[timestep][row][col][i][j] = spikes[
                                timestep][i * 10 + j]
                        elif row != 0:
                            heatmap[timestep][row][col][i][j] = neurons[0][
                                i * 10 + j].exc[row * 2 + col - 2,
                                                timestep] - offsets[row * 2 +
                                                                    col - 2]

                axs[row][col].imshow(heatmap[timestep][row][col],
                                     cmap='hot',
                                     interpolation='nearest')
                axs[row][col].set_title(exc_labels[row * 2 + col])
        fig.suptitle('Frame {}'.format(timestep))
        camera.snap()

    animation = camera.animate()
    animation.save('animations/animation {}.gif'.format(time.time()))
Beispiel #3
0
thetaseq = [np.array(weights).reshape(2, 1) for i in range(len(seq))]

print(means_em)
print(means)
print(error(means_em, means, weights))
print(weights)
print(
    ot.emd2_1d(means_em[:, 0], means[:, 0], thetaseq[-1].reshape(-1),
               weights.reshape(-1)))

animate = False

if animate:

    fig = plt.figure()
    camera = celluloid.Camera(fig)
    cm = "viridis"

    #intital setup
    proba_mode = (weights_list[0][0] /
                  (weights_list[0][0] + weights_list[0][1]))
    plt.scatter(x=samples[:, 0],
                y=samples[:, 1],
                c=proba_mode,
                cmap=cm,
                alpha=0.2)
    plt.scatter(x=means[0][0], y=means[0][1], c="black", s=200 * weights[0])
    plt.scatter(x=means[1][0], y=means[1][1], c="black", s=200 * weights[1])
    plt.scatter(seq[0][0][0],
                seq[0][0][1],
                c="red",
Beispiel #4
0
    def make_movie(self,
                   field_name,
                   dt=None,
                   cmin=-1.,
                   cmax=1.,
                   ncolors=10,
                   name="movie.mp4",
                   **kwargs):
        '''
Make a movie

Input:
------
times      : list, series of evolution times
all_fields : dict, maps spectre-names of coords to lists of the same
                   coordinate as a function of evolution time
field_name : str, name of field to plot
dt         : time step
kwargs     : keyword arguments that are passed to `ArtistAnimation`

Output:
-------
result : tuple, (camera object, animation object) that can be used to
                display or save movie animation

        '''
        times = self.times
        all_fields = self.fields

        # Data for frames
        x_of_t, y_of_t = self.coords_from_spectre_data()
        z_of_t = self.fields_from_spectre_data([field_name])

        # Prepare figure and initialize Camera
        fig = plt.figure(figsize=(12, 6))
        ax = fig.add_axes([0.1, 0.1, 0.7, 0.8])
        ax2 = fig.add_axes([0.8, 0.1, 0.03, 0.8])
        camera = celluloid.Camera(fig)

        # Prepare a colorbar
        cmap = matplotlib.cm.jet
        cmaplist = [cmap(i) for i in range(cmap.N)]
        cmap = matplotlib.colors.LinearSegmentedColormap.from_list(
            'CustomCmap', cmaplist, cmap.N)

        cbar_bounds = np.linspace(cmin, cmax, ncolors + 1)
        norm = matplotlib.colors.BoundaryNorm(cbar_bounds, cmap.N)

        # Make all frames
        for idx in range(len(times)):
            if idx % 5 == 0:
                logging.info(" ... making frame {0:d}".format(idx + 1))

            t = times[idx]
            x, y, z = x_of_t[idx, :], y_of_t[idx, :], z_of_t[idx, :]

            # Draw a frame: FIXME: Use `contourf`
            sc = ax.scatter(x,
                            y,
                            c=z,
                            s=50,
                            alpha=0.97,
                            marker="s",
                            cmap=cmap,
                            norm=norm,
                            edgecolors='none',
                            vmin=cmin,
                            vmax=cmax)
            tx = ax.text(min(x),
                         max(y) + 0.05 * (max(y) - min(y)),
                         'Time: {0:06.03f}'.format(t))

            if idx >= 0:
                cb = matplotlib.colorbar.ColorbarBase(ax2,
                                                      cmap=cmap,
                                                      norm=norm,
                                                      spacing='proportional',
                                                      ticks=cbar_bounds,
                                                      boundaries=cbar_bounds,
                                                      format='%3.1f')
                ax2.set_ylabel(field_name)
                cb.set_clim(cmin, cmax)

            camera.snap()

        # Animate
        anim = camera.animate(**kwargs)
        anim.save(name)
Beispiel #5
0
    def xest_implement_1d_myosin(self):
        #Parameters
        total_time = 10.0
        number_of_time_steps = 1000
        #         delta_t = fenics.Constant(total_time/number_of_time_steps)
        delta_t = total_time / number_of_time_steps
        nx = 1000
        domain_size = 1.0
        b = fenics.Constant(6.0)
        k = fenics.Constant(0.5)
        z_1 = fenics.Constant(-10.5)  #always negative
        #         z_1 = fenics.Constant(0.0) #always negative
        z_2 = 0.1  # always positive
        xi_0 = fenics.Constant(1.0)  #always positive
        xi_1 = fenics.Constant(1.0)  #always positive
        xi_2 = 0.001  #always positive
        xi_3 = 0.0001  #always negative
        d = fenics.Constant(0.15)
        alpha = fenics.Constant(1.0)
        c = fenics.Constant(0.1)

        # Sub domain for Periodic boundary condition
        class PeriodicBoundary(fenics.SubDomain):
            # Left boundary is "target domain" G
            def inside(self, x, on_boundary):
                return bool(-fenics.DOLFIN_EPS < x[0] < fenics.DOLFIN_EPS
                            and on_boundary)

            def map(self, x, y):
                y[0] = x[0] - 1

        periodic_boundary_condition = PeriodicBoundary()

        #Set up finite elements
        mesh = fenics.IntervalMesh(nx, 0.0, 1.0)
        vector_element = fenics.FiniteElement('P', fenics.interval, 1)
        single_element = fenics.FiniteElement('P', fenics.interval, 1)
        mixed_element = fenics.MixedElement(vector_element, single_element)
        V = fenics.FunctionSpace(
            mesh,
            mixed_element,
            constrained_domain=periodic_boundary_condition)
        #         V = fenics.FunctionSpace(mesh, mixed_element)
        v, r = fenics.TestFunctions(V)
        full_trial_function = fenics.Function(V)
        u, rho = fenics.split(full_trial_function)
        full_trial_function_n = fenics.Function(V)
        u_n, rho_n = fenics.split(full_trial_function_n)
        u_initial = fenics.Constant(0.0)
        #         rho_initial = fenics.Expression('1.0*sin(pi*x[0])*sin(pi*x[0])+1.0/k0', degree=2,k0 = k)
        rho_initial = fenics.Expression('1/k0', degree=2, k0=k)
        u_n = fenics.interpolate(u_initial, V.sub(0).collapse())
        rho_n = fenics.interpolate(rho_initial, V.sub(1).collapse())
        #         perturbation = np.zeros(rho_n.vector().size())
        #         perturbation[:int(perturbation.shape[0]/2)] = 1.0
        rho_n.vector().set_local(
            np.array(rho_n.vector()) + 1.0 *
            (0.5 - np.random.random(rho_n.vector().size())))
        #         u_n.vector().set_local(np.array(u_n.vector())+4.0*(0.5-np.random.random(u_n.vector().size())))
        fenics.assign(full_trial_function_n, [u_n, rho_n])
        u_n, rho_n = fenics.split(full_trial_function_n)

        F = (u * v * fenics.dx - u_n * v * fenics.dx + delta_t *
             (b + (z_1 * rho) /
              (1 + z_2 * rho) * c * xi_1) * u.dx(0) * v.dx(0) * fenics.dx -
             delta_t * (z_1 * rho) / (1 + z_2 * rho) * c * c * xi_2 / 2.0 *
             u.dx(0) * u.dx(0) * v.dx(0) * fenics.dx + delta_t * (z_1 * rho) /
             (1 + z_2 * rho) * c * c * c * xi_3 / 6.0 * u.dx(0) * u.dx(0) *
             u.dx(0) * v.dx(0) * fenics.dx - delta_t * z_1 * rho /
             (1 + z_2 * rho) * xi_0 * v.dx(0) * fenics.dx +
             u.dx(0) * v.dx(0) * fenics.dx - u_n.dx(0) * v.dx(0) * fenics.dx +
             rho * r * fenics.dx - rho_n * r * fenics.dx -
             rho * u * r.dx(0) * fenics.dx + rho * u_n * r.dx(0) * fenics.dx +
             delta_t * d * rho.dx(0) * r.dx(0) * fenics.dx +
             delta_t * k * fenics.exp(alpha * u.dx(0)) * rho * r * fenics.dx -
             delta_t * r * fenics.dx + delta_t * c * u.dx(0) * r * fenics.dx)

        vtkfile_rho = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_2d',
                         'solution_rho.pvd'))
        vtkfile_u = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_2d',
                         'solution_u.pvd'))

        #         rho_0 = fenics.Expression(((('0.0'),('0.0'),('0.0')),('sin(x[0])')), degree=1 )
        #         full_trial_function_n = fenics.project(rho_0, V)
        #         print('initial u and rho')
        #         print(u_n.vector())
        #         print(rho_n.vector())

        time = 0.0
        not_initialised = True
        plt.figure()
        for time_index in range(number_of_time_steps):
            # Update current time
            time += delta_t
            # Compute solution
            fenics.solve(F == 0, full_trial_function)
            # Save to file and plot solution
            vis_u, vis_rho = full_trial_function.split()
            plt.subplot(311)
            fenics.plot(vis_u, color='blue')
            plt.ylim(-0.5, 0.5)
            plt.subplot(312)
            fenics.plot(-vis_u.dx(0), color='blue')
            plt.ylim(-2, 2)
            plt.title('actin density change')
            plt.subplot(313)
            fenics.plot(vis_rho, color='blue')
            plt.title('myosin density')
            plt.ylim(0, 7)
            plt.tight_layout()
            if not_initialised:
                animation_camera = celluloid.Camera(plt.gcf())
                not_initialised = False
            animation_camera.snap()
            print('time is')
            print(time)
            #             plt.savefig(os.path.join(os.path.dirname(__file__),'output','this_output_at_time_' + '{:04d}'.format(time_index) + '.png'))
            #             print('this u and rho')
            #             print(np.array(vis_u.vector()))
            #             print(np.array(vis_rho.vector()))
            #             vtkfile_rho << (vis_rho, time)
            #             vtkfile_u << (vis_u, time)
            full_trial_function_n.assign(full_trial_function)

        animation = animation_camera.animate()
        animation.save(
            os.path.join(os.path.dirname(__file__), 'output', 'myosin_1D.mp4'))
Beispiel #6
0
    def xest_first_tutorial(self):
        T = 2.0  # final time
        num_steps = 10  # number of time steps
        dt = T / num_steps  # time step size
        alpha = 3  # parameter alpha
        beta = 1.2  # parameter beta
        # Create mesh and define function space
        nx = ny = 8
        mesh = fenics.UnitSquareMesh(nx, ny)
        V = fenics.FunctionSpace(mesh, 'P', 1)
        # Define boundary condition
        u_D = fenics.Expression('1 + x[0]*x[0] + alpha*x[1]*x[1] + beta*t',
                                degree=2,
                                alpha=alpha,
                                beta=beta,
                                t=0)

        def boundary(x, on_boundary):
            return on_boundary

        bc = fenics.DirichletBC(V, u_D, boundary)
        # Define initial value
        u_n = fenics.interpolate(u_D, V)  #u_n = project(u_D, V)
        # Define variational problem
        u = fenics.TrialFunction(V)
        v = fenics.TestFunction(V)
        f = fenics.Constant(beta - 2 - 2 * alpha)
        F = u * v * fenics.dx + dt * fenics.dot(fenics.grad(u), fenics.grad(
            v)) * fenics.dx - (u_n + dt * f) * v * fenics.dx
        a, L = fenics.lhs(F), fenics.rhs(F)
        # Time-stepping
        u = fenics.Function(V)
        t = 0
        vtkfile = fenics.File(
            os.path.join(os.path.dirname(__file__), 'output',
                         'heat_constructed_solution', 'solution.pvd'))
        not_initialised = True
        for n in range(num_steps):
            # Update current time
            t += dt
            u_D.t = t
            # Compute solution
            fenics.solve(a == L, u, bc)
            # Plot the solution
            vtkfile << (u, t)
            fenics.plot(u)
            if not_initialised:
                animation_camera = celluloid.Camera(plt.gcf())
                not_initialised = False
            animation_camera.snap()
            # Compute error at vertices
            u_e = fenics.interpolate(u_D, V)
            error = np.abs(u_e.vector().get_local() -
                           u.vector().get_local()).max()
            print('t = %.2f: error = %.3g' % (t, error))
            # Update previous solution
            u_n.assign(u)
            # Hold plot

        animation = animation_camera.animate()
        animation.save(
            os.path.join(os.path.dirname(__file__), 'output',
                         'heat_equation.mp4'))
Beispiel #7
0
 def __init__(self, W):
     plt.ioff()
     fig, self.axs = plt.subplots(1, W, figsize=(W * 9, 8))
     self.camera = celluloid.Camera(fig)
     if W == 1:
         self.axs = [self.axs]