Ejemplo n.º 1
0
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=16):
    dx = 2 * R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    def source_G(t):
        center = np.exp(-0.5 * (t - 5)**2) * 10
        gradient = (1 + np.tanh(t - 30)) * 0.0003
        return -np.exp(-0.5 * (x * x + y * y)) * center + (x + 8) * gradient

    source_functions = {
        'G': source_G,
    }

    flow = [0 * x, 0 * x]

    fluid_model_g = FluidModelG(
        x * 0,
        x * 0,
        x * 0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(
        fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6 * (-fluid_model_g.G + max_G) / (max_G - min_G),
                5 * (fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7 * (fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
def nucleation_3D(writer, args, R=20):
    raise NotImplementedError("Needs some work")
    params = {
        "A": 3.4,
        "B": 13.5,
        "k2": 1.0,
        "k-2": 0.1,
        "k5": 0.9,
        "D_G": 1.0,
        "D_X": 1.0,
        "D_Y": 1.95,
        "density_G": 1.0,
        "density_X": 0.0002,
        "density_Y": 0.043,
        "base-density": 9.0,
        "viscosity": 0.3,
        "speed-of-sound": 1.0,
    }

    dx = 2 * R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    z = y
    x, y, z = np.meshgrid(x, y, z, indexing='ij')

    def source_G(t):
        center = np.exp(-0.3 * (t - 6)**2) * 10
        return -np.exp(-0.5 * (x * x + y * y + z * z)) * center

    source_functions = {
        'G': source_G,
    }

    # We need some noise to break spherical symmetry
    noise_scale = 1e-4
    G = bl_noise(x.shape) * noise_scale
    X = bl_noise(x.shape) * noise_scale
    Y = bl_noise(x.shape) * noise_scale
    flow = [
        bl_noise(x.shape) * noise_scale,
        bl_noise(x.shape) * noise_scale,
        bl_noise(x.shape) * noise_scale
    ]

    fluid_model_g = FluidModelG(
        G,
        X,
        Y,
        flow,
        dx,
        dt=args.dt,
        params=params,
        source_functions=source_functions,
    )

    flow_particle_origins = []
    for _ in range(1000):
        flow_particle_origins.append([np.random.rand() * s for s in x.shape])

    flow_particles = tf.constant(flow_particle_origins, dtype='float64')
    flow_streaks = 0 * x[:, :, 0]

    print("Rendering 'Nucleation and Motion in G gradient in 3D'")
    print("Lattice constant dx = {}, time step dt = {}".format(
        fluid_model_g.dx, fluid_model_g.dt))
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        for _ in range(20):
            indices = tf.cast(flow_particles, 'int32')
            for index in indices.numpy():
                flow_streaks[index[0], index[1]] += 0.15 / args.oversampling
            dx = tf.gather_nd(fluid_model_g.u, indices)
            dy = tf.gather_nd(fluid_model_g.v, indices)
            dz = tf.gather_nd(fluid_model_g.w, indices)
            flow_particles = (flow_particles +
                              tf.stack([dx, dy, dz], axis=1) * 400) % x.shape
        if n % args.oversampling == 0:
            rgb = [
                tf.reduce_mean(
                    (7 * fluid_model_g.G)**2, axis=2) + flow_streaks,
                tf.reduce_mean((4 * fluid_model_g.Y)**2, axis=2),
                tf.reduce_mean((2 * fluid_model_g.X)**2, axis=2),
            ]
            frame = make_video_frame(rgb)
            writer.append_data(frame)
            flow_streaks *= 0
            flow_particles = tf.constant(flow_particle_origins,
                                         dtype='float64')
Ejemplo n.º 3
0
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=30):
    dx = 2 * R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    def source_G(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-0.5 * (t - 5)**2) * 10
        gradient = (1 + np.tanh(t - 30)) * 0.0003
        #x = np.linspace(-40, 40, 500)
        triangle = 10 * signal.sawtooth(40 * np.pi * 1 / 1400 * x + 0,
                                        0.5) + 10
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003
        #print("x = ", x)
        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient
        #u = x/5
        #return -(
        #    #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
        #    np.exp(-0.5*((x)**2 + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
        #) * center + (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!
        return -(
            #np.exp(-0.5*((x-D)**2+y*y)) * nucleator +
            #(u*u - 1) * potential
            #np.exp(-0.5*((x-15)**2+y*y)) * center  + (u*u - 1) * gradient #+ (x+8) * gradient
            #np.exp(-0.5*((x-15)**2 + y*y)) + np.exp(-0.5*((x+15)**2 + y*y)) * center  - (u*u + 5) * gradient
            np.exp(-0.5 *
                   ((x - 12)**2 + y * y)) + np.exp(-0.5 *
                                                   ((x + 12)**2 + y * y))
        ) * center + triangle * gradient  # BJD - note minus sign maybe in wrong w.r.t. (u*u - 1) --- 22.12.2020

    source_functions = {
        'G': source_G,
    }
    """
    def source_X(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-(1/18)*(t-10)**2)
        #gradient = (1+np.tanh(t-30)) * 0.0003
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003

        #print("x = ", x)

        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient

        return -(
            #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
            np.exp(-0.5*((x)**2 + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
        ) * center #+ (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!

    source_functions = {
        'X': source_X,
    }
    """
    flow = [0 * x, 0 * x]

    fluid_model_g = FluidModelG(
        x * 0,
        x * 0,
        x * 0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(
        fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6 * (-fluid_model_g.G + max_G) / (max_G - min_G),
                5 * (fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7 * (fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
Ejemplo n.º 4
0
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=16):
    c1 = 0 # BJD added this on 20.11.2020
    dx = 2*R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    def source_G(t):
        center = np.exp(-0.5*(t-5)**2) * 10
        gradient = (1+np.tanh(t-30)) * 0.0003
        #return -(
        #    np.exp(-0.5*((x-25)**2 + y*y)) + np.exp(-0.5*((x+25)**2 + y*y))
        #) * center + (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!

        #return (
        if x < 50:
            return -(
                np.exp(-0.5*((x-25)**2 + y*y)) # + np.exp(-0.5*((x+25)**2 + y*y))
            ) * center #+ (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!
        else :
            return -(
                np.exp(-0.5*((x-25)**2 + y*y)) + np.exp(-0.5*((x+25)**2 + y*y))
            ) * center + (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!
            
        #return -(
        #    np.exp( -0.5*( (x - 50)**2 + y*y ) ) +
        #    np.exp( -0.5*( (x + 50)**2 + y*y ) ) 
        #) * center + (x+8) * gradient # BJD altered for 2 seeds 29.11.2020
    """
    def source_G(t):
        amount = np.exp(-0.5*(t-5)**2)
        return (
            np.exp(-0.5*((x-D)**2+y*y)) * weights[0] +
            np.exp(-0.5*((x+D)**2+y*y)) * weights[1]
        ) * amount
    """
    source_functions = {
        'G': source_G,
    }

    flow = [0*x, 0*x]

    fluid_model_g = FluidModelG(
        x*0,
        x*0,
        x*0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    #c1 = 0
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6*(-fluid_model_g.G + max_G) / (max_G - min_G),
                5*(fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7*(fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
#========================BJD added 18.11.2020===================================================
            if n == 100:
                print("n = ", n)
                break
        #if n == 4:
        #    X_array = [
        #        0.7*(fluid_model_g.X - min_X) / (max_X - min_X),
        #    ] # BJD put this in 18.11.2020
        #    print("Array of X: ", X_array) # ***** BJD inserted this line 18.11.2020 *****
            c1 = c1 + 1
            print("H E L L O")
            y1 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array5/X.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            y2 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array5/Y.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            y3 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array5/G.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            row1 = y1[214]  # choose row 214 of 2D array = (426,240)
            row2 = y2[214]  # choose row 214 of 2D array = (426,240)
            row3 = y3[214]  # choose row 214 of 2D array = (426,240)
            
            #t = linspace(0, 2*math.pi, 400)
            #a = sin(t)
            #b = cos(t)
            #c = a + b

            print(row1)
            fig, pp = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
            #fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
            #ax.plot([0,1,2], [10,20,3])

            #pp.plot(t, a, 'r') # plotting t, a separately - BJD new plotting code 21.11.2020
            #pp.plot(t, b, 'b') # plotting t, b separately - BJD new plotting code 21.11.2020
            #pp.plot(t, c, 'g') # plotting t, c separately - BJD new plotting code 21.11.2020
            # https://stackoverflow.com/questions/22276066/how-to-plot-multiple-functions-on-the-same-figure-in-matplotlib
            
            pp.plot(row1, 'r') # plotting t, a separately - BJD new plotting code 21.11.2020
            pp.plot(row2, 'b') # plotting t, b separately - BJD new plotting code 21.11.2020
            pp.plot(row3, 'g') # plotting t, c separately - BJD new plotting code 21.11.2020

            #pp.plot(row1) # BJD previous working plot code 21.11.2020
            #pp.show()
            #plt.savefig('test2.png')
            #plt.savefig('test2.pdf')
            plt.title('X, Y, G potential vs 1D space - time = ' + str(c1))
            plt.xlabel("1D spacial units")
            plt.ylabel("X, Y, G pot. - concentration per unit vol")
            #fig.savefig('test2.png')   # save the figure to file
            plt.legend(["X", "Y", "G"]) # BJD legend added 21.11.2020

            fig.savefig('/home/brendan/software/tf2-model-g/plots/1D_video7/1D_video_XYG_' + str(c1) + '.png')
            plt.close(fig)    # close the figure window
            #plt.savefig('test2_' + str(c1) + '.png')
#===========================================================================
    #for i in xrange(10):
        #with io.open("file_" + str(i) + ".dat", 'w', encoding='utf-8') as f:
        #with io.open("file_" + str(c1) + ".txt", 'w', encoding='utf-8') as f:
            #f.write(str(func(c1))

    #for number in range(1, 11):
    #filename = 'a%d.txt' % number
    #data = read_data(filename)

    #for c1 in xrange(10):
    """
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=30):
    dx = 2*R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    def source_G(t):
        center = np.exp(-0.5*(t-5)**2) * 10
        gradient = (1+np.tanh(t-30)) * 0.0003
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003

        #print("x = ", x)

        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient
        """
        for item in array:
            if item >= 3:
                print("yes")
        else:
            print("no")
        """

        #"""
        #return (
        #for item in x:
        #    if item < 0:
        #if np.all(a == 0):
        #if np.all(x < 0):   # might work!
        # if x.all() < 0:
        #if np.where(x < 0):
        return -(
            #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y))
            np.exp(-0.5*((x)**2 + y*y)) #+ np.exp(-0.5*((x+8)**2 + y*y))
        ) * center + (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!
        #else:
        #    return -(
        #        np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y))
        #    ) * center + (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!
        #"""

    source_functions = {
        'G': source_G,
    }

    flow = [0*x, 0*x]

    fluid_model_g = FluidModelG(
        x*0,
        x*0,
        x*0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6*(-fluid_model_g.G + max_G) / (max_G - min_G),
                5*(fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7*(fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
Ejemplo n.º 6
0
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=30):
    c1 = 0  # BJD added this on 20.11.2020
    dx = 2 * R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    def source_G(t):
        center = np.exp(-0.5 * (t - 5)**2) * 10
        gradient = (1 + np.tanh(t - 30)) * 0.0003
        return -(np.exp(-0.5 * ((x - 25)**2 + y * y)) + np.exp(-0.5 * (
            (x + 25)**2 + y * y))) * center + (
                x + 8
            ) * gradient  # BJD 2.2.2020 --- try gradient for half of plot!!

    """
    def source_G(t):
        amount = np.exp(-0.5*(t-5)**2)
        return (
            np.exp(-0.5*((x-D)**2+y*y)) * weights[0] +
            np.exp(-0.5*((x+D)**2+y*y)) * weights[1]
        ) * amount
    """
    source_functions = {
        'G': source_G,
    }

    flow = [0 * x, 0 * x]

    fluid_model_g = FluidModelG(
        x * 0,
        x * 0,
        x * 0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(
        fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    #c1 = 0
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6 * (-fluid_model_g.G + max_G) / (max_G - min_G),
                5 * (fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7 * (fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
            #========================BJD added 18.11.2020===================================================
            if n == 150:
                print("n = ", n)
                break
        #if n == 4:
        #    X_array = [
        #        0.7*(fluid_model_g.X - min_X) / (max_X - min_X),
        #    ] # BJD put this in 18.11.2020
        #    print("Array of X: ", X_array) # ***** BJD inserted this line 18.11.2020 *****
            c1 = c1 + 1
            print("H E L L O")
            x1 = np.loadtxt(
                "/home/brendan/software/tf2-model-g/arrays/array9/X.txt"
            )  #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            x2 = np.loadtxt(
                "/home/brendan/software/tf2-model-g/arrays/array9/Y.txt"
            )  #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            x3 = np.loadtxt(
                "/home/brendan/software/tf2-model-g/arrays/array9/G.txt"
            )  #, delimiter=" :-) ", usecols=(120))  # (426, 240)

            #ndArray[ : , column_index]   # @ https://thispointer.com/python-numpy-select-rows-columns-by-index-from-a-2d-ndarray-multi-dimension/
            column1 = x1[:, 120]  # choose row 214 of 2D array = (426,240)
            column2 = x2[:, 120]  # choose row 214 of 2D array = (426,240)
            column3 = x3[:, 120]  # choose row 214 of 2D array = (426,240)

            #t = linspace(0, 2*math.pi, 400)
            #a = sin(t)
            #b = cos(t)
            #c = a + b

            print(column1)
            fig, pp = plt.subplots(nrows=1, ncols=1)  # create figure & 1 axis

            #axes = pp.add_axes([0.1,0.1,0.8,0.8])

            #-------------------
            #a= plt.figure()
            #axes= a.add_axes([0.1,0.1,0.8,0.8])
            # adding axes
            #x= np.arange(0,11)
            #axes.plot(x,x**3, marker='*')
            #axes.set_xlim([0,250])
            #axes.set_ylim([-3,2])
            #plt.show()
            #------------------
            #fig, ax = plt.subplots( nrows=1, ncols=1 )  # create figure & 1 axis
            #ax.plot([0,1,2], [10,20,3])

            #pp.plot(t, a, 'r') # plotting t, a separately - BJD new plotting code 21.11.2020
            #pp.plot(t, b, 'b') # plotting t, b separately - BJD new plotting code 21.11.2020
            #pp.plot(t, c, 'g') # plotting t, c separately - BJD new plotting code 21.11.2020
            # https://stackoverflow.com/questions/22276066/how-to-plot-multiple-functions-on-the-same-figure-in-matplotlib

            #row1 = range(-3, 2)
            #row2 = range(-3, 2)
            #row3 = range(-3, 2)
            #y = range(-3, 2)

            pp.plot(
                column1, 'r'
            )  # plotting t, a separately - BJD new plotting code 21.11.2020
            pp.plot(
                column2, 'b'
            )  # plotting t, b separately - BJD new plotting code 21.11.2020
            pp.plot(
                column3, 'g'
            )  # plotting t, c separately - BJD new plotting code 21.11.2020

            #axes.set_xlim([0,250])
            #axes.set_ylim([-3,2])
            #pp.set_xlim([0,250])
            pp.set_ylim(
                [-4, 4])  # ******* BJD this one works! 1.12.2020  ***********
            #pp.plot(row1) # BJD previous working plot code 21.11.2020
            #pp.show()
            #plt.savefig('test2.png')
            #plt.savefig('test2.pdf')
            plt.title('X, Y, G potential vs 1D space - time = ' + str(c1))
            plt.xlabel("1D spacial units")
            plt.ylabel("X, Y, G pot. - concentration per unit vol")
            #fig.savefig('test2.png')   # save the figure to file
            plt.legend(["X", "Y", "G"])  # BJD legend added 21.11.2020

            fig.savefig(
                '/home/brendan/software/tf2-model-g/plots/1D_video16/1D_video_XYG_'
                + str(c1) + '.png')
            plt.close(fig)  # close the figure window
Ejemplo n.º 7
0
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=50): # was R=30 BJD 4.1.2021
    dx = 2*R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')
    
    #def trapezoid_signal(x, width=2., slope=1., amp=1., offs=0):
    def trapezoid_signal(x, width=2., slope=1., amp=10., offs=1):
        #a = 10 * slope*width*signal.sawtooth(2 * np.pi * 1/10* x/width, width=0.5)/4.
        #a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width, width=0.5)/4.
        #a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width, width=0.5)/4.
        a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width - 1, width=0.5)/4.
        a[a>amp/2.] = amp/2.
        a[a<-amp/2.] = -amp/2.
        return a + amp/2. + offs

    #x = np.linspace(100, -100, 1000)
    #plt.plot(t,trapezoid_signal(x, width=2, slope=2, amp=1.), label="width=2, slope=2, amp=1")
    #plt.plot(x,trapezoid_signal(x, width=4, slope=1, amp=0.6), label="width=4, slope=1, amp=0.6")
    #plt.plot(x,trapezoid_signal(x, width=10, slope=5, amp=20), label="width=10, slope=3, amp=20")

    #plt.legend( loc=(0.25,1.015))
    #plt.show()


    def source_G(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-0.5*(t-5)**2) * 10
        gradient = (1+np.tanh(t-30)) * 0.0003
        #x = np.linspace(-40, 40, 500)
        #triangle = 10 * signal.sawtooth(40 * np.pi * 1/1400 * x + 0, 0.5) + 10
        #triangle = 10 * signal.sawtooth(2 * np.pi * 1/70 * x + 0.001, 0.5) + 10  # BJD: last used here 28.12.2020
        #trapezoid = trapezoid_signal(x, width=30, slope=10, amp=30)
        trapezoid = trapezoid_signal(x, width=40, slope=10, amp=50)
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003
        #print("x = ", x)
        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient
        #u = x/5
        #return -( 
        #    #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
        #    np.exp(-0.5*((x)**2 + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
        #) * center + (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!
        return -(
            #np.exp(-0.5*((x-D)**2+y*y)) * nucleator +
            #(u*u - 1) * potential
            #np.exp(-0.5*((x-15)**2+y*y)) * center  + (u*u - 1) * gradient #+ (x+8) * gradient 
            #np.exp(-0.5*((x-15)**2 + y*y)) + np.exp(-0.5*((x+15)**2 + y*y)) * center  - (u*u + 5) * gradient
            #np.exp(-0.5*((x-12)**2 + y*y)) + np.exp(-0.5*((x+12)**2 + y*y)) 
        #) * center + triangle * gradient # BJD - note minus sign maybe in wrong w.r.t. (u*u - 1) --- 22.12.2020
            np.exp(-0.5*((x-25)**2 + (y-15)**2)) + np.exp(-0.5*((x+50)**2 + (y+15)**2))
        ) * center + trapezoid * gradient # BJD - note minus sign maybe in wrong w.r.t. (u*u - 1) --- 22.12.2020

    source_functions = {
        'G': source_G,
    }

    """
    def source_X(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-(1/18)*(t-10)**2)
        #gradient = (1+np.tanh(t-30)) * 0.0003
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003

        #print("x = ", x)

        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient

        return -(
            #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
            np.exp(-0.5*((x)**2 + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
        ) * center #+ (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!

    source_functions = {
        'X': source_X,
    }
    """
    flow = [0*x, 0*x]

    fluid_model_g = FluidModelG(
        x*0,
        x*0,
        x*0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6*(-fluid_model_g.G + max_G) / (max_G - min_G),
                5*(fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7*(fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
def nucleation_and_motion_in_G_gradient_fluid_2D(writer,
                                                 args,
                                                 R=60
                                                 ):  # was R=30 BJD 4.1.2021
    #c1 = 0 # BJD added this on 20.11.2020
    dx = 2 * R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    #def trapezoid_signal(x, width=2., slope=1., amp=1., offs=0):
    def trapezoid_signal(x, width=2., slope=1., amp=10., offs=1):
        #a = 10 * slope*width*signal.sawtooth(2 * np.pi * 1/10* x/width, width=0.5)/4.
        #a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width, width=0.5)/4.
        #a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width, width=0.5)/4.
        a = slope * width * signal.sawtooth(
            2 * np.pi * 1 / 10 * x / width - 0.8, width=0.5) / 4.
        a[a > amp / 2.] = amp / 2.
        a[a < -amp / 2.] = -amp / 2.
        return a + amp / 2. + offs

    #...........................................
    """
    #def piecewise_function(x, list(map(f, x)), 'b-')
    def f(x):
        #b = x
        #list(map(lambda x: -2.*x if x<0. else x, -x))
        x[x < 0.] = -2.*x
        x[x > 0.] = -x
        #if x < 0:
            #return 0
        return x
        #elif :
        #else :
        #x[x > 0.] = -x
            #return t * t - 100
            #return -x
        #return -x

        #x = np.arange(-100, 100, 1)

        #plt.plot(t, map(f, t), 'b-')
        #plt.plot(x, list(map(f, x)), 'b-')  # for python3

    #plt.show()
    """

    def f(x):
        #return -3*x/10 #+ 20
        neg = x < 0
        neg2 = np.logical_and(
            x >= 0, x < 4.7
        )  #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        neg3 = x >= 4.7
        return neg * (-x / 5 + 1) + neg2 * (
            50 * signal.square(2 * np.pi / 10 * x)) + neg3 * 1

    def f2(x):
        #return -3*x/10 #+ 20
        neg4 = x < 0
        #neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        #neg3 = x >= 4.7
        neg5 = x >= 0
        #return neg * (-x/5 + 1) + neg2 * (50 * signal.square(2 * np.pi /10 * x)) + neg3 * 1
        return neg4 * (-x / 5 + 1) + neg5 * 1

    def f3(x):
        #return -3*x/10 #+ 20
        #neg = x < 0
        #neg6 = np.logical_and(y >= -10, y <= 10)
        #neg7 = np.logical_and(y < -10, y > 10)
        neg6 = np.logical_and(y >= -10, y <= 10)
        neg7 = np.logical_or(y < -10, y > 10)
        #neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        #neg3 = x >= 4.7
        #neg3 = x >= 0
        #return neg * (-x/5 + 1) + neg2 * (50 * signal.square(2 * np.pi /10 * x)) + neg3 * 1
        return neg6 * f2(x) + neg7 * f(x)

    #...........................................
    #x = np.linspace(100, -100, 1000)
    #plt.plot(t,trapezoid_signal(x, width=2, slope=2, amp=1.), label="width=2, slope=2, amp=1")
    #plt.plot(x,trapezoid_signal(x, width=4, slope=1, amp=0.6), label="width=4, slope=1, amp=0.6")
    #plt.plot(x,trapezoid_signal(x, width=10, slope=5, amp=20), label="width=10, slope=3, amp=20")

    #plt.legend( loc=(0.25,1.015))
    #plt.show()
    """
    def composite_triangle(x):
        #x = np.arange(1, 11)
        y = np.array([100, 10, 300, 20, 500, 60, 700, 80, 900, 100])

        return y
    """

    def source_G(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-0.5 * (t - 5)**2) * 10
        gradient = (1 + np.tanh(t - 30)) * 0.0003
        #potential = 0.015 * (np.tanh(t-25) + 1)
        #x = np.linspace(-40, 40, 500)
        #triangle = 10 * signal.sawtooth(40 * np.pi * 1/1400 * x + 0, 0.5) + 10
        #triangle = 10 * signal.sawtooth(2 * np.pi * 1/70 * x + 0.001, 0.5) + 10  # BJD: last used here 28.12.2020
        #trapezoid = trapezoid_signal(x, width=40, slope=5, amp=50)
        #piecewise = f(x)
        piecewise_choice = f3(x)
        #piecewise_1 = list(map(f, x))
        #trapezoid = trapezoid_signal(x, width=40, slope=10, amp=50)
        #composite = composite_triangle(x)
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003
        #print("x = ", x)
        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient
        #u = x/25
        #u = x/10
        return -(
            #    #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
            np.exp(-0.5 *
                   ((x + 50)**2 + y * y))  #+ np.exp(-0.5*((x)**2 + y*y))
        ) * center + piecewise_choice * gradient  # piecewise function test 5.2.2021
        #return -(
        #np.exp( -0.5*( (x+25)**2 + y*y ) )
        #    x * y * ( x**2 - y**2 ) / ( x**2 + y**2 )
        #) * center #+ (u*u + 1) * gradient #+ (x+8) * potential

        #np.exp(-0.5*((x-D)**2+y*y)) * nucleator +
        #(u*u - 1) * potential
        #np.exp(-0.5*((x-15)**2+y*y)) * center  + (u*u - 1) * gradient #+ (x+8) * gradient
        #np.exp(-0.5*((x-15)**2 + y*y)) + np.exp(-0.5*((x+15)**2 + y*y)) * center  - (u*u + 5) * gradient
        #np.exp(-0.5*((x-12)**2 + y*y)) + np.exp(-0.5*((x+12)**2 + y*y))
        #) * center + triangle * gradient # BJD - note minus sign maybe in wrong w.r.t. (u*u - 1) --- 22.12.2020
        #np.exp(-0.5*((x-15)**2 + (y-25)**2)) + np.exp(-0.5*((x-15)**2 + (y+25)**2)) +
        #np.exp(-0.5*((x+55)**2 + (y)**2))
        #) * center + trapezoid * gradient # 3 particles for de Broglie diffraction --- 5.2.2021
        """  
        u = x / R
        return (
            np.exp(-0.5*((x-D)**2+y*y)) * nucleator +
            (u*u - 1) * potential
        )
        """

    """
    def trapezoid_signal(x, width=2., slope=1., amp=10., offs=1):
        a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width - 1, width=0.5)/4.
        a[a>amp/2.] = amp/2.
        a[a<-amp/2.] = -amp/2.
        return a + amp/2. + offs


    def source_G(t):
        center = np.exp(-0.5*(t-5)**2) * 10
        gradient = (1+np.tanh(t-30)) * 0.0003
        trapezoid = trapezoid_signal(x, width=30, slope=10, amp=30)

        return -(
            np.exp(-0.5*((x-12)**2 + (y-5)**2)) + np.exp(-0.5*((x+32)**2 + (y+5)**2)) 
        ) * center + trapezoid * gradient   # 2 particles colliding one stationary
    """
    source_functions = {
        'G': source_G,
    }
    """
    def source_X(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-(1/18)*(t-10)**2)
        #gradient = (1+np.tanh(t-30)) * 0.0003
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003

        #print("x = ", x)

        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient

        return -(
            #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
            np.exp(-0.5*((x)**2 + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
        ) * center #+ (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!

    source_functions = {
        'X': source_X,
    }
    """
    flow = [0 * x, 0 * x]

    fluid_model_g = FluidModelG(
        x * 0,
        x * 0,
        x * 0,
        #x*0   # BJD 28.1.2021 --- added
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(
        fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6 * (-fluid_model_g.G + max_G) / (max_G - min_G),
                5 * (fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7 * (fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)

            #-------------------------BJD 28.1.2021----rough code at present-----------------------------------------
            """
            if n == 200:
                print("n = ", n)
                break
            #c1 = c1 + 1
            print("H E L L O")
            #y1 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array14/u.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            #y2 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array14/v.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)

            c1 = c1 + 1
            # Set up grid and test data
            #nx, ny = 256, 1024
            nx, ny = 240, 426
            #(426,240)
            x1 = range(nx)
            y1 = range(ny)

            #data = numpy.random.random((nx, ny))
            U = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array25/u.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            V = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array25/v.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            # BJD 28.1.2021: u and v are saved as arrays in fluid_model_g.py as fllows:
            # np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array18/u.txt", self.u)
            # np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array18/v.txt", self.v)

            #data = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array12/Y.txt")

            #hf = plt.figure(figsize=(10,10))
            #ha = hf.add_subplot(111, projection='3d')
            #ha = hf.add_subplot(111, projection='2d')

            X1, Y1 = np.meshgrid(x1, y1)  # `plot_surface` expects `x` and `y` data to be 2D
            #ha.plot_surface(X, Y, data)
            #ha.plot_surface(X, Y, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #                       linewidth=0, antialiased=False)
            #ha.plot_surface(X.T, Y.T, data)

            #surf = ha.plot_surface(X1, Y1, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #           linewidth=0, antialiased=False)
            #ha.set_zlim(-1, 3)
            #hf.colorbar(surf, shrink=0.5, aspect=10)
            #hf = plt.figure(figsize=(10,10))
            """
            """
            fig, hf = plt.subplots(figsize=(10,10))
            #ax3.set_title("pivot='tip'; scales with x view")
            hf.set_title("pivot='tip'; scales with x view" + str(c1))
            M = np.hypot(U, V)
            Q = hf.quiver(X1, Y1, U, V, M, units='x', pivot='tip', width=0.022,
               scale=1 / 0.15)
            qk = hf.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E',
                   coordinates='figure')
            hf.scatter(X1, Y1, color='0.5', s=1)
            """
            """
            fig, hf = plt.subplots(figsize=(10,10))
            hf.set_title("Model G fluid velocity vector field - every 5th arrow, time = " + str(c1))
            #Q = hf.quiver(X1[::10, ::10], Y1[::10, ::10], U[::10, ::10], V[::10, ::10],
               #pivot='mid', units='inches')
            #M = np.hypot(U, V)
            Q = hf.quiver(X1[::5, ::5], Y1[::5, ::5], U[::5, ::5], V[::5, ::5], units='width',
                pivot='mid', scale=0.1, headwidth=7)#pivot='mid', units='inches')#, scale=1)#, scale=5)
            #qk = hf.quiverkey(Q, 0.9, 0.9, 1, r'$\frac{distance}{time}$', labelpos='E',
                   #coordinates='figure')
            qk = hf.quiverkey(Q, 0.9, 0.9, 0.1, r'$\frac{distance}{time}$', labelpos='E',
                   coordinates='figure')#, color='b')
            hf.scatter(X1[::5, ::5], Y1[::5, ::5], color='r', s=5)


            #plt.show()

            #plt.title('Y potential in 2D space - time = ' + str(c1))
            #plt.xlabel("x spacial units")
            #plt.ylabel("y spacial units")
            #plt.zlabel("X, Y, G pot. - concentration per unit vol")
            #fig.savefig('test2.png')   # save the figure to file
            #plt.legend(["X", "Y", "G"]) # BJD legend added 21.11.2020
            #plt.show()

            plt.savefig('/home/brendan/software/tf2-model-g/plots/2D_video31/2D_video_velocity_' + str(c1) + '.png')
            #plt.close(hf)    # close the figure window

            #y3 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array10/G.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            #column1 = y1[120]  # choose column 120 of 2D array = (426,240)
            #column2 = y2[120]  # choose column 120 of 2D array = (426,240)
            #column3 = y3[120]  # choose column 120 of 2D array = (426,240)
            #row1 = y1[214]  # choose row 214 of 2D array = (426,240)
            #row2 = y2[214]  # choose row 214 of 2D array = (426,240)
            #row3 = y3[214]  # choose row 214 of 2D array = (426,240)

            #x, y = np.meshgrid(x, y, indexing='ij')
            #X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))
            #U = np.gradient(fluid_model_g.G,1)
            #V = np.gradient(fluid_model_g.G,2)
            #U = np.cos(X)
            #V = np.sin(Y)
            #np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array13/X.txt", np.gradient(fluid_model_g.G,1))
            # sphinx_gallery_thumbnail_number = 3
            """
            """
Ejemplo n.º 9
0
def nucleation_3D(animated=False, N=128, R=20):
    params = {
        "A": 3.4,
        "B": 13.5,
        "k2": 1.0,
        "k-2": 0.1,
        "k5": 0.9,
        "D_G": 1.0,
        "D_X": 1.0,
        "D_Y": 1.95,
        "density_G": 1.0,
        "density_X": 0.0002,
        "density_Y": 0.043,
        "base-density": 20.0,
        "viscosity": 0.4,
        "speed-of-sound": 1.0,
    }

    x = np.linspace(-R, R, N)
    dx = x[1] - x[0]
    x, y, z = np.meshgrid(x, x, x, indexing='ij')

    def source_G(t):
        center = np.exp(-0.5 * (t - 5)**2) * 10
        return -np.exp(-0.5 * (x * x + y * y + z * z)) * center

    source_functions = {
        'G': source_G,
    }

    # We need some noise to break spherical symmetry
    noise_scale = 1e-4
    G = bl_noise(x.shape) * noise_scale
    X = bl_noise(x.shape) * noise_scale
    Y = bl_noise(x.shape) * noise_scale
    flow = [
        bl_noise(x.shape) * noise_scale,
        bl_noise(x.shape) * noise_scale,
        bl_noise(x.shape) * noise_scale
    ]

    dt = 0.2 * dx
    fluid_model_g = FluidModelG(
        G,
        X,
        Y,
        flow,
        dx,
        dt=dt,
        params=params,
        source_functions=source_functions,
    )

    if animated:

        def get_data():
            G, X, Y, (u, v, w) = fluid_model_g.numpy()

            x_scale = 0.1
            y_scale = 0.1
            return (
                G[N // 2, N // 2],
                X[N // 2, N // 2] * x_scale,
                Y[N // 2, N // 2] * y_scale,
                u[N // 2, N // 2],
                v[N // 2, N // 2],
                w[N // 2, N // 2],
            )

        G, X, Y, u, v, w = get_data()
        plots = []
        plots.extend(pylab.plot(z[0, 0], G))
        plots.extend(pylab.plot(z[0, 0], X))
        plots.extend(pylab.plot(z[0, 0], Y))
        plots.extend(pylab.plot(z[0, 0], u))
        plots.extend(pylab.plot(z[0, 0], v))
        pylab.ylim(-0.1, 0.1)

        def update(frame):
            fluid_model_g.step()
            G, X, Y, u, v, w = get_data()
            print(fluid_model_g.t, abs(G).max(), abs(u).max())
            plots[0].set_ydata(G)
            plots[1].set_ydata(X)
            plots[2].set_ydata(Y)
            plots[3].set_ydata(u)
            plots[4].set_ydata(v)
            plots[4].set_ydata(w)
            return plots

        FuncAnimation(pylab.gcf(),
                      update,
                      frames=range(100),
                      init_func=lambda: plots,
                      blit=True,
                      repeat=True,
                      interval=20)
        pylab.show()
    else:
        from datetime import datetime
        from pathlib import Path
        start = datetime.now()

        num_steps = int(1.0 / dt)
        print("Starting simulation {} steps at a time".format(num_steps))

        path = Path("/tmp/model_g")
        path.mkdir(exist_ok=True)
        while True:
            for _ in range(num_steps):
                fluid_model_g.step()
            print("Saving a snapshot into {}".format(path))
            G, X, Y, (u, v, w) = fluid_model_g.numpy()
            np.save(path / 'G.npy', G)
            np.save(path / 'X.npy', X)
            np.save(path / 'Y.npy', Y)
            np.save(path / 'u.npy', u)
            np.save(path / 'v.npy', v)
            np.save(path / 'w.npy', w)
            print("Saved everything")

            wall_clock_time = (datetime.now() - start).total_seconds()
            print("t={}, wall clock time={} s, efficiency={}".format(
                fluid_model_g.t, wall_clock_time,
                fluid_model_g.t / wall_clock_time))
            print("max|G|={}, max|u|={}".format(abs(G).max(), abs(u).max()))
Ejemplo n.º 10
0
def nucleation_and_motion_in_G_gradient_2D(N=128, R=16):
    params = {
        "A": 3.42,
        "B": 13.5,
        "k2": 1.0,
        "k-2": 0.1,
        "k5": 0.9,
        "D_G": 1.0,
        "D_X": 1.0,
        "D_Y": 1.95,
        "density_G": 2.0,
        "density_X": 1.0,
        "density_Y": 1.5,
        "base-density": 35.0,
        "viscosity": 0.4,
        "speed-of-sound": 1.0,
    }

    x = np.linspace(-R, R, N)
    dx = x[1] - x[0]
    x, y = np.meshgrid(x, x, indexing='ij')

    def source_G(t):
        center = np.exp(-0.5 * (t - 5)**2) * 10
        gradient = (1 + np.tanh(t - 40)) * 0.0005
        return -np.exp(-0.5 * (x * x + y * y)) * center + (x + 8) * gradient

    source_functions = {
        'G': source_G,
    }

    flow = [0 * x, 0 * x]

    fluid_model_g = FluidModelG(
        x * 0,
        x * 0,
        x * 0,
        flow,
        dx,
        dt=0.25 * dx,
        params=params,
        source_functions=source_functions,
    )

    times = []
    locs = []

    def get_data():
        G, X, Y, (u, v) = fluid_model_g.numpy()

        loc = l2_location(X, x, y)
        times.append(fluid_model_g.t)
        locs.append(loc[0])
        print("t={}\tL2 location: {}".format(fluid_model_g.t, tuple(loc)))

        x_scale = 0.1
        y_scale = 0.1
        return (
            G[:, N // 2],
            X[:, N // 2] * x_scale,
            Y[:, N // 2] * y_scale,
            u[:, N // 2],
            v[:, N // 2],
        )

    G, X, Y, u, v = get_data()
    plots = []
    plots.extend(pylab.plot(x[:, 0], G))
    plots.extend(pylab.plot(x[:, 0], X))
    plots.extend(pylab.plot(x[:, 0], Y))
    plots.extend(pylab.plot(x[:, 0], u))
    plots.extend(pylab.plot(x[:, 0], v))
    pylab.ylim(-0.1, 0.1)

    def update(frame):
        for _ in range(20):
            fluid_model_g.step()
        G, X, Y, u, v = get_data()
        plots[0].set_ydata(G)
        plots[1].set_ydata(X)
        plots[2].set_ydata(Y)
        plots[3].set_ydata(u)
        plots[4].set_ydata(v)
        return plots

    FuncAnimation(pylab.gcf(),
                  update,
                  frames=range(100),
                  init_func=lambda: plots,
                  blit=True,
                  repeat=True,
                  interval=20)
    pylab.show()

    G, X, Y, (u, v) = fluid_model_g.numpy()
    pylab.imshow(X)
    pylab.show()

    pylab.plot(times, locs)
    pylab.show()
def nucleation_3D(writer, args, R=12):
    #    raise NotImplementedError("Needs some work")
    params = {
        "A": 3.4,
        "B": 13.5,
        "k2": 1.0,
        "k-2": 0.1,
        "k5": 0.9,
        "D_G": 1.0,
        "D_X": 1.0,
        "D_Y": 1.95,
        "density_G": 1.0,
        "density_X": 0.0002,
        "density_Y": 0.043,
        "base-density": 9.0,
        "viscosity": 0.3,
        "speed-of-sound": 1.0,
    }
    c1 = 0  # BJD added this on 22.4.2021
    dx = 2 * R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    z = y
    x, y, z = np.meshgrid(x, y, z, indexing='ij')

    def source_G(t):
        center = np.exp(-0.3 * (t - 6)**2) * 10
        return -np.exp(-0.5 * (x * x + y * y + z * z)) * center

    source_functions = {
        'G': source_G,
    }

    # We need some noise to break spherical symmetry
    noise_scale = 1e-4
    G = bl_noise(x.shape) * noise_scale
    X = bl_noise(x.shape) * noise_scale
    Y = bl_noise(x.shape) * noise_scale
    flow = [
        bl_noise(x.shape) * noise_scale,
        bl_noise(x.shape) * noise_scale,
        bl_noise(x.shape) * noise_scale
    ]

    fluid_model_g = FluidModelG(
        G,
        X,
        Y,
        flow,
        dx,
        dt=args.dt,
        params=params,
        source_functions=source_functions,
    )

    flow_particle_origins = []
    for _ in range(1000):
        flow_particle_origins.append([np.random.rand() * s for s in x.shape])

    flow_particles = tf.constant(flow_particle_origins, dtype='float64')
    flow_streaks = 0 * x[:, :, 0]

    print("Rendering 'Nucleation and Motion in G gradient in 3D'")
    print("Lattice constant dx = {}, time step dt = {}".format(
        fluid_model_g.dx, fluid_model_g.dt))
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        for _ in range(20):
            indices = tf.cast(flow_particles, 'int32')
            for index in indices.numpy():
                flow_streaks[index[0], index[1]] += 0.15 / args.oversampling
            dx = tf.gather_nd(fluid_model_g.u, indices)
            dy = tf.gather_nd(fluid_model_g.v, indices)
            dz = tf.gather_nd(fluid_model_g.w, indices)
            flow_particles = (flow_particles +
                              tf.stack([dx, dy, dz], axis=1) * 400) % x.shape
        if n % args.oversampling == 0:
            rgb = [
                tf.reduce_mean(
                    (7 * fluid_model_g.G)**2, axis=2) + flow_streaks,
                tf.reduce_mean((4 * fluid_model_g.Y)**2, axis=2),
                tf.reduce_mean((2 * fluid_model_g.X)**2, axis=2),
            ]
            frame = make_video_frame(rgb)
            writer.append_data(frame)
            flow_streaks *= 0
            flow_particles = tf.constant(flow_particle_origins,
                                         dtype='float64')
            #=====================BJD 20.4.2021==========================================
            #-------------------------BJD 22.4.2021----rough code at present-----------------------------------------
            if n == 200:
                print("n = ", n)
                break
            #c1 = c1 + 1
            print("H E L L O")
            #y1 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array14/u.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            #y2 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array14/v.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)

            c1 = c1 + 1
            # Set up grid and test data
            #nx, ny = 256, 1024
            nx, ny, nz = 240, 426, 426
            #nx, ny = 426, 240  # changed round to check!
            #(426,240)
            x1 = range(nx)
            y1 = range(ny)
            z1 = range(nz)
            #data = numpy.random.random((nx, ny))
            U = np.loadtxt(
                "/home/brendan/software/tf2-model-g/arrays/quiver3D_array31/u.txt"
            )  #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            V = np.loadtxt(
                "/home/brendan/software/tf2-model-g/arrays/quiver3D_array31/v.txt"
            )  #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            W = np.loadtxt(
                "/home/brendan/software/tf2-model-g/arrays/quiver3D_array31/w.txt"
            )  #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            # BJD 28.1.2021: u and v are saved as arrays in fluid_model_g.py as fllows:
            # np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array18/u.txt", self.u)
            # np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array18/v.txt", self.v)

            #data = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array12/Y.txt")

            #hf = plt.figure(figsize=(10,10))
            #ha = hf.add_subplot(111, projection='3d')
            #ha = hf.add_subplot(111, projection='2d')

            X1, Y1, Z1 = np.meshgrid(
                x1, y1, z1)  # `plot_surface` expects `x` and `y` data to be 2D
            #x, y, z = np.meshgrid(np.arange(-0.8, 1, 0.2),
            #          np.arange(-0.8, 1, 0.2),
            #          np.arange(-0.8, 1, 0.8))
            #ha.plot_surface(X, Y, data)
            #ha.plot_surface(X, Y, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #                       linewidth=0, antialiased=False)
            #ha.plot_surface(X.T, Y.T, data)

            #surf = ha.plot_surface(X1, Y1, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #           linewidth=0, antialiased=False)
            #ha.set_zlim(-1, 3)
            #hf.colorbar(surf, shrink=0.5, aspect=10)
            #hf = plt.figure(figsize=(10,10))
            """
            
            fig, hf = plt.subplots(figsize=(10,10))
            #ax3.set_title("pivot='tip'; scales with x view")
            hf.set_title("pivot='tip'; scales with x view" + str(c1))
            M = np.hypot(U, V)
            Q = hf.quiver(X1, Y1, U, V, M, units='x', pivot='tip', width=0.022,
               scale=1 / 0.15)
            qk = hf.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E',
                   coordinates='figure')
            hf.scatter(X1, Y1, color='0.5', s=1)

            # Below, from Color_Quiver_Plot.py 17.4.2021 - BJD 
            color = np.sqrt(((dx-n)/2)*2 + ((dy-n)/2)*2)  
  
            ax2.quiver(X, Y, dx, dy, color) 
            ax2.xaxis.set_ticks([]) 
            ax2.yaxis.set_ticks([]) 
            ax2.set_aspect('equal') 
            ax2.set_title('gradient') 
            plt.tight_layout() 
            plt.show()

            #also arrow head 17.4.2021 BJD:
            Q = hf.quiver(X1[::10, ::10], Y1[::10, ::10], U[::10, ::10], V[::10, ::10], units='width',
                pivot='mid', scale=0.005)#pivot='mid', units='inches')#, scale=1)#, scale=5)
            """
            #fig, hf = plt.subplots(figsize=(10,10))
            fig = plt.figure(figsize=(10, 10))
            ax = fig.gca(projection='3d')
            ax.set_title(
                "pivot='mid'; every 10th arrow; units='velocity vector' time="
                + str(c1))
            #Q = ax.quiver(X1[::10, ::10], Y1[::10, ::10], Z1[::10, ::10], U[::10, ::10],
            #    V[::10, ::10], W[::10, ::10], pivot='mid', units='inches')
            Q = ax.quiver(X1[::10, ::10, ::10],
                          Y1[::10, ::10, ::10],
                          Z1[::10, ::10, ::10],
                          U[::10, ::10, ::10],
                          V[::10, ::10, ::10],
                          W[::10, ::10, ::10],
                          pivot='mid',
                          units='inches')

            #hf.set_title("pivot='mid'; every 10th arrow; units='velocity vector' time=" + str(c1))
            #Q = hf.quiver(X1[::10, ::10], Y1[::10, ::10], U[::10, ::10], V[::10, ::10], pivot='mid',
            #units='inches')

            #q = ax.quiver(x, y, z, u, v, w, length=0.1, cmap='Reds', lw=2)
            #q.set_array(np.random.rand(np.prod(x.shape)))
            Q.set_array(np.random.rand(np.prod(
                x.shape)))  # may need this? BJD 22.4.2021
            #plt.show()
            #qk = ax.quiverkey(Q, 0.9, 0.9, 5, r'$1 \frac{m}{s}$', labelpos='E',
            #coordinates='figure')
            #Q = hf.quiver(X1[::10, ::10], Y1[::10, ::10], U[::10, ::10], V[::10, ::10], units='width',
            #pivot='mid', scale=0.1, headwidth=7)
            #ax1.quiver(X, Y, u, v, color, alpha = 0.8) # from Color_Quiver_Plot.py
            #qk = hf.quiverkey(Q, 0.9, 0.9, 5, r'$1 \frac{m}{s}$', labelpos='E',
            #coordinates='figure')
            #hf.scatter(X1[::10, ::10], Y1[::10, ::10], color='r', s=5)
            #hf.scatter(X1[::10, ::10], Y1[::10, ::10], color='c', alpha = 0.8)
            #hf.scatter(X1[::10, ::10], Y1[::10, ::10], color='c', s=0)
            #ax.scatter(X1[::10, ::10], Y1[::10, ::10], Z1[::10, ::10], color='c', s=0)
            ax.scatter(X1[::10, ::10, ::10],
                       Y1[::10, ::10, ::10],
                       Z1[::10, ::10, ::10],
                       color='c',
                       s=0)
            plt.tight_layout()
            plt.savefig(
                '/home/brendan/software/tf2-model-g/plots/3D_video37/3D_video_velocity_'
                + str(c1) + '.png')
Ejemplo n.º 12
0
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=16):
    c1 = 0 # BJD added this on 20.11.2020
    dx = 2*R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')
    """
    def source_G(t):
        center = np.exp(-0.5*(t-5)**2) * 10
        gradient = (1+np.tanh(t-30)) * 0.0003
        return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient # BJD original 29.11.2020
        #return -(
        #    np.exp( -0.5*( (x - 50)**2 + y*y ) ) +
        #    np.exp( -0.5*( (x + 50)**2 + y*y ) ) 
        #) * center + (x+8) * gradient # BJD altered for 2 seeds 29.11.2020
    
    def source_G(t):
        amount = np.exp(-0.5*(t-5)**2)
        return (
            np.exp(-0.5*((x-D)**2+y*y)) * weights[0] +
            np.exp(-0.5*((x+D)**2+y*y)) * weights[1]
        ) * amount
    
    source_functions = {
        'G': source_G,
    }
    """
    def source_X(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-(1/18)*(t-10)**2)
        gradient = (1+np.tanh(t-30)) * 0.0003
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003

        #print("x = ", x)

        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient

        return -(
            #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
            np.exp(-0.5*((x)**2 + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
        ) * center + (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!

    source_functions = {
        'X': source_X,
    }

    flow = [0*x, 0*x]

    fluid_model_g = FluidModelG(
        x*0,
        x*0,
        x*0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    #c1 = 0
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6*(-fluid_model_g.G + max_G) / (max_G - min_G),
                5*(fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7*(fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
#========================BJD added 18.11.2020===================================================
            if n == 200:
                print("n = ", n)
                break

            c1 = c1 + 1
            # Set up grid and test data
            #nx, ny = 256, 1024
            nx, ny = 240, 426
            #(426,240)
            x1 = range(nx)
            y1 = range(ny)

            #data = numpy.random.random((nx, ny))
            data = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array12/Y.txt")

            hf = plt.figure(figsize=(10,10))
            ha = hf.add_subplot(111, projection='3d')

            X1, Y1 = np.meshgrid(x1, y1)  # `plot_surface` expects `x` and `y` data to be 2D
            #ha.plot_surface(X, Y, data)
            #ha.plot_surface(X, Y, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #                       linewidth=0, antialiased=False)
            #ha.plot_surface(X.T, Y.T, data)

            surf = ha.plot_surface(X1, Y1, data, rstride=1, cstride=1, cmap=cm.coolwarm,
                       linewidth=0, antialiased=False)
            ha.set_zlim(-1, 3)
            hf.colorbar(surf, shrink=0.5, aspect=10)

            plt.title('Y potential in 2D space - time = ' + str(c1))
            plt.xlabel("x spacial units")
            plt.ylabel("y spacial units")
            #plt.zlabel("X, Y, G pot. - concentration per unit vol")
            #fig.savefig('test2.png')   # save the figure to file
            #plt.legend(["X", "Y", "G"]) # BJD legend added 21.11.2020
            #plt.show()

            hf.savefig('/home/brendan/software/tf2-model-g/plots/3D_video19/3D_video_XYG_' + str(c1) + '.png')
            plt.close(hf)    # close the figure window
        """
Ejemplo n.º 13
0
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=8): # was R=60, 30 and 15 -BJD 14.1.2021
    c1 = 0 # BJD added this on 20.11.2020
    dx = 2*R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    #def trapezoid_signal(x, width=2., slope=1., amp=1., offs=0):
    def trapezoid_signal(x, width=2., slope=1., amp=10., offs=1):
        #a = 10 * slope*width*signal.sawtooth(2 * np.pi * 1/10* x/width, width=0.5)/4.
        #a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width, width=0.5)/4.
        #a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width, width=0.5)/4.
        a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width - 1, width=0.5)/4.
        a[a>amp/2.] = amp/2.
        a[a<-amp/2.] = -amp/2.
        return a + amp/2. + offs

    def f(x):
        #return -3*x/10 #+ 20
        neg = x < 0
        neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        neg3 = x >= 4.7
        return neg * (-x/5 + 1) + neg2 * (50 * signal.square(2 * np.pi /10 * x)) + neg3 * 1

    def f2(x):
        #return -3*x/10 #+ 20
        neg4 = x < 0
        #neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        #neg3 = x >= 4.7
        neg5 = x >= 0
        #return neg * (-x/5 + 1) + neg2 * (50 * signal.square(2 * np.pi /10 * x)) + neg3 * 1
        return neg4 * (-x/5 + 1) + neg5 * 1

    def f3(x):
        #return -3*x/10 #+ 20
        #neg = x < 0
        #neg6 = np.logical_and(y >= -10, y <= 10)
        #neg7 = np.logical_and(y < -10, y > 10)
        neg6 = np.logical_and(y >= -5, y <= 5)
        neg7 = np.logical_or(y < -5, y > 5)
        #neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        #neg3 = x >= 4.7
        #neg3 = x >= 0
        #return neg * (-x/5 + 1) + neg2 * (50 * signal.square(2 * np.pi /10 * x)) + neg3 * 1
        return neg6 * f2(x) + neg7 * f(x)
    #...........................................

    def source_G(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-0.5*(t-5)**2) * 10
        gradient = (1+np.tanh(t-30)) * 0.0003
        #potential = 0.015 * (np.tanh(t-25) + 1)
        #x = np.linspace(-40, 40, 500)
        #triangle = 10 * signal.sawtooth(40 * np.pi * 1/1400 * x + 0, 0.5) + 10
        #triangle = 10 * signal.sawtooth(2 * np.pi * 1/70 * x + 0.001, 0.5) + 10  # BJD: last used here 28.12.2020
        #trapezoid = trapezoid_signal(x, width=40, slope=5, amp=50)
        #piecewise = f(x)
        piecewise_choice = f3(x)
        #piecewise_1 = list(map(f, x))
        #trapezoid = trapezoid_signal(x, width=40, slope=10, amp=50)
        #composite = composite_triangle(x)
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003
        #print("x = ", x)
        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient
        #u = x/25
        #u = x/10
        return -(
            np.exp(-0.5*( (x)**2 + y*y) ) #+ np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
            #np.exp(-0.5*((x+50)**2 + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
        ) * center # + piecewise_choice * gradient   # piecewise function --- G gap in G wall 13.3.2021
#......................................................

    source_functions = {
        'G': source_G,
    }

    flow = [0*x, 0*x]

    fluid_model_g = FluidModelG(
        x*0,
        x*0,
        x*0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6*(-fluid_model_g.G + max_G) / (max_G - min_G),
                5*(fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7*(fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
#-------------------------BJD 28.1.2021----rough code at present-----------------------------------------        
            if n == 600:
                print("n = ", n)
                break
            #c1 = c1 + 1
            #print("H E L L O")
            #y1 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array14/u.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            #y2 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array14/v.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)

            c1 = c1 + 1
            # Set up grid and test data
            #nx, ny = 256, 1024
            #nx, ny = 240, 426
            #nx, ny = 426, 240  # changed round to check!
            nx, ny = 240, 426
            #(426,240)
            x1 = range(nx)
            y1 = range(ny)

            #data = numpy.random.random((nx, ny))
            U = np.loadtxt("/home/brendan/runs/tf2-model-g_1/tf2-model-g/arrays/quiver_array30/u.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            V = np.loadtxt("/home/brendan/runs/tf2-model-g_1/tf2-model-g/arrays/quiver_array30/v.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            # BJD 28.1.2021: u and v are saved as arrays in fluid_model_g.py as fllows:
            # np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array18/u.txt", self.u)
            # np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array18/v.txt", self.v)

            #data = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array12/Y.txt")

            #hf = plt.figure(figsize=(10,10))
            #ha = hf.add_subplot(111, projection='3d')
            #ha = hf.add_subplot(111, projection='2d')

            X1, Y1 = np.meshgrid(x1, y1)  # `plot_surface` expects `x` and `y` data to be 2D
            #ha.plot_surface(X, Y, data)
            #ha.plot_surface(X, Y, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #                       linewidth=0, antialiased=False)
            #ha.plot_surface(X.T, Y.T, data)

            #surf = ha.plot_surface(X1, Y1, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #           linewidth=0, antialiased=False)
            #ha.set_zlim(-1, 3)
            #hf.colorbar(surf, shrink=0.5, aspect=10)
            #hf = plt.figure(figsize=(10,10))
            """
            fig, hf = plt.subplots(figsize=(10,10))
            #ax3.set_title("pivot='tip'; scales with x view")
            hf.set_title("pivot='tip'; scales with x view" + str(c1))
            M = np.hypot(U, V)
            Q = hf.quiver(X1, Y1, U, V, M, units='x', pivot='tip', width=0.022,
               scale=1 / 0.15)
            qk = hf.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E',
                   coordinates='figure')
            hf.scatter(X1, Y1, color='0.5', s=1)
            """
            fig, hf = plt.subplots(figsize=(10,10))
            hf.set_title("pivot='mid'; every 1th arrow; units='velocity vector'" + str(c1))
            Q = hf.quiver(X1[::5, ::5], Y1[::5, ::5], U[::5, ::5], V[::5, ::5],
               pivot='mid', units='inches')
            qk = hf.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E',
                   coordinates='figure')
            hf.scatter(X1[::5, ::5], Y1[::5, ::5], color='r', s=5)

            plt.savefig('/home/brendan/runs/tf2-model-g_1/tf2-model-g/plots/2D_video36/2D_video_velocity_' + str(c1) + '.png')
def nucleation_and_motion_in_G_gradient_fluid_2D(writer,
                                                 args,
                                                 R=16
                                                 ):  # was R=30 BJD 4.1.2021
    c1 = 0  # BJD added this on 20.11.2020
    dx = 2 * R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    #def trapezoid_signal(x, width=2., slope=1., amp=1., offs=0):
    def trapezoid_signal(x, width=2., slope=1., amp=10., offs=1):
        #a = 10 * slope*width*signal.sawtooth(2 * np.pi * 1/10* x/width, width=0.5)/4.
        #a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width, width=0.5)/4.
        #a = slope * width * signal.sawtooth(2 * np.pi * 1/10 * x/width, width=0.5)/4.
        a = slope * width * signal.sawtooth(
            2 * np.pi * 1 / 10 * x / width - 0.8, width=0.5) / 4.
        a[a > amp / 2.] = amp / 2.
        a[a < -amp / 2.] = -amp / 2.
        return a + amp / 2. + offs

    def f(x):
        #return -3*x/10 #+ 20
        neg = x < 0
        #neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        neg2 = np.logical_and(x >= 0, x < 29.5)
        #neg3 = x >= 4.7
        neg3 = x >= 29.5
        return neg * (-3 * x / 10 + 1) + neg2 * (
            20 * signal.square(2 * np.pi / 60 * x)) + neg3 * 1
        #return neg * 1 + neg2 * (10 * signal.square(2 * np.pi /10 * x)) + neg3 * 1

    def f2(x):
        #return -3*x/10 #+ 20
        neg4 = x < 0
        #neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        #neg3 = x >= 4.7
        neg5 = x >= 0
        #return neg * (-x/5 + 1) + neg2 * (50 * signal.square(2 * np.pi /10 * x)) + neg3 * 1
        return neg4 * (-x / 5 + 1) + neg5 * 1

    def f3(x):
        #return -3*x/10 #+ 20
        #neg = x < 0
        #neg6 = np.logical_and(y >= -10, y <= 10)
        #neg7 = np.logical_and(y < -10, y > 10)
        neg6 = np.logical_and(y >= -10, y <= 10)
        neg7 = np.logical_or(y < -10, y > 10)
        #neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        #neg3 = x >= 4.7
        #neg3 = x >= 0
        #return neg * (-x/5 + 1) + neg2 * (50 * signal.square(2 * np.pi /10 * x)) + neg3 * 1
        return neg6 * f2(x) + neg7 * f(x)

    def f4(x):
        neg8 = x <= 0
        #return neg8 * (-x/5 + 1)
        return neg8 * (-3 * x / 10 + 1)

    def f5(x):
        neg9 = x > 0
        #return neg9 * (x/5 + 1)
        return neg9 * (3 * x / 10 + 1)

    def f6(x):
        neg10 = y >= 0
        neg11 = y < 0
        #neg10 = np.logical_and(y >= -10, y <= 10)
        #neg11 = np.logical_or(y < -10, y > 10)
        #neg2 = np.logical_and(x >= 0, x < 4.7) #c[a & b] x >= 0 and x < 20  c[a & b]  np.logical_and(x > -2, x < 2)
        #neg3 = x >= 4.7
        #neg3 = x >= 0
        #return neg * (-x/5 + 1) + neg2 * (50 * signal.square(2 * np.pi /10 * x)) + neg3 * 1
        return neg10 * f4(x) + neg11 * f5(x)

    #...........................................

    def source_G(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-0.5 * (t - 5)**2) * 10
        #gradient = (1+np.tanh(t-30)) * 0.0003
        gradient2 = 0.0006
        #potential = 0.015 * (np.tanh(t-25) + 1)
        #x = np.linspace(-40, 40, 500)
        #triangle = 10 * signal.sawtooth(40 * np.pi * 1/1400 * x + 0, 0.5) + 10
        #triangle = 10 * signal.sawtooth(2 * np.pi * 1/70 * x + 0.001, 0.5) + 10  # BJD: last used here 28.12.2020
        #trapezoid = trapezoid_signal(x, width=40, slope=5, amp=50)
        #piecewise = f6(x)
        #piecewise_choice = f3(x)
        piecewise = f6(x)
        #trapezoid = trapezoid_signal(x, width=40, slope=10, amp=50)
        #composite = composite_triangle(x)
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003
        #print("x = ", x)
        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient
        #u = x/25
        #u = x/10
        return -(
            #    #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
            np.exp(-0.5 * ((x)**2 + y * y))  #+ np.exp(-0.5*((x)**2 + y*y))
        ) * center + piecewise * gradient2  # piecewise function test 5.2.2021
        #return -(
        #np.exp( -0.5*( (x+25)**2 + y*y ) )
        #    x * y * ( x**2 - y**2 ) / ( x**2 + y**2 )
        #) * center #+ (u*u + 1) * gradient #+ (x+8) * potential

        #np.exp(-0.5*((x-D)**2+y*y)) * nucleator +
        #(u*u - 1) * potential
        #np.exp(-0.5*((x-15)**2+y*y)) * center  + (u*u - 1) * gradient #+ (x+8) * gradient
        #np.exp(-0.5*((x-15)**2 + y*y)) + np.exp(-0.5*((x+15)**2 + y*y)) * center  - (u*u + 5) * gradient
        #np.exp(-0.5*((x-12)**2 + y*y)) + np.exp(-0.5*((x+12)**2 + y*y))
        #) * center + triangle * gradient # BJD - note minus sign maybe in wrong w.r.t. (u*u - 1) --- 22.12.2020
        #np.exp(-0.5*((x-15)**2 + (y-25)**2)) + np.exp(-0.5*((x-15)**2 + (y+25)**2)) +
        #np.exp(-0.5*((x+55)**2 + (y)**2))
        #) * center + trapezoid * gradient # 3 particles for de Broglie diffraction --- 5.2.2021
#......................................................

    source_functions = {
        'G': source_G,
    }
    """
    def source_X(t):
        #center = np.exp(-0.5*(t-5)**2) * 10
        center = np.exp(-(1/18)*(t-10)**2)
        #gradient = (1+np.tanh(t-30)) * 0.0003
        #gradient = ( (t/3) - 8 ) * 0.0003 # (1+np.tanh(t-30)) * 0.0003

        #print("x = ", x)

        #return -np.exp(-0.5*(x*x+y*y))* center + (x+8) * gradient

        return -(
            #np.exp(-0.5*((x-8)**2 + y*y)) + np.exp(-0.5*((x+8)**2 + y*y)) # 2 particles 16 units apart
            np.exp(-0.5*((x)**2 + y*y)) #+ np.exp(-0.5*((x)**2 + y*y))
        ) * center #+ (x+8) * gradient   # BJD 2.2.2020 --- try gradient for half of plot!!

    source_functions = {
        'X': source_X,
    }
    """
    flow = [0 * x, 0 * x]

    fluid_model_g = FluidModelG(
        x * 0,
        x * 0,
        x * 0,
        #x*0   # BJD 28.1.2021 --- added
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(
        fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6 * (-fluid_model_g.G + max_G) / (max_G - min_G),
                5 * (fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7 * (fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)

            #-------------------------BJD 28.1.2021----rough code at present-----------------------------------------

            if n == 400:
                print("n = ", n)
                break
            #c1 = c1 + 1
            print("H E L L O")
            #y1 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array14/u.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            #y2 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array14/v.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)

            c1 = c1 + 1
            # Set up grid and test data
            #nx, ny = 256, 1024
            nx, ny = 240, 426  # original 10.10.2021
            #nx, ny = 426, 240 # BJD changed here 10.10.2021
            #ny, nx = 240, 426  # BJD changed here 10.10.2021
            #(426,240)
            x1 = range(nx)
            y1 = range(ny)
            #x1 = range(ny) #BJD changed here 10.10.2021
            #y1 = range(nx) #BJD changed here 10.10.2021

            #data = numpy.random.random((nx, ny))
            # swapped U and V around - BJD 3.9.2021
            U = np.loadtxt(
                "/home/brendan/software/tf2-model-g/arrays/quiver_array38/v.txt"
            )  #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            V = np.loadtxt(
                "/home/brendan/software/tf2-model-g/arrays/quiver_array38/u.txt"
            )  #, delimiter=" :-) ", usecols=(120))  # (426, 240)

            # swapped U and V around - BJD 2.9.2021
            #U = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array37/del_X_dy.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            #V = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/quiver_array37/del_X_dx.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)

            # BJD 28.1.2021: u and v are saved as arrays in fluid_model_g.py as fllows:
            # np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array18/u.txt", self.u)
            # np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array18/v.txt", self.v)

            N = np.sqrt(
                U**2 +
                V**2)  # there may be a faster numpy "normalize" function
            U1, V1 = U / N, V / N

            #F = 0.001 # normalisation factor
            F = 0.004

            U1 *= F
            V1 *= F

            #data = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array12/Y.txt")

            #hf = plt.figure(figsize=(10,10))
            #ha = hf.add_subplot(111, projection='3d')
            #ha = hf.add_subplot(111, projection='2d')

            X1, Y1 = np.meshgrid(
                x1, y1)  # `plot_surface` expects `x` and `y` data to be 2D
            #ha.plot_surface(X, Y, data)
            #ha.plot_surface(X, Y, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #                       linewidth=0, antialiased=False)
            #ha.plot_surface(X.T, Y.T, data)

            #surf = ha.plot_surface(X1, Y1, data, rstride=1, cstride=1, cmap=cm.coolwarm,
            #           linewidth=0, antialiased=False)
            #ha.set_zlim(-1, 3)
            #hf.colorbar(surf, shrink=0.5, aspect=10)
            #hf = plt.figure(figsize=(10,10))
            """
            fig, hf = plt.subplots(figsize=(10,10))
            #ax3.set_title("pivot='tip'; scales with x view")
            hf.set_title("pivot='tip'; scales with x view" + str(c1))
            M = np.hypot(U, V)
            Q = hf.quiver(X1, Y1, U, V, M, units='x', pivot='tip', width=0.022,
               scale=1 / 0.15)
            qk = hf.quiverkey(Q, 0.9, 0.9, 1, r'$1 \frac{m}{s}$', labelpos='E',
                   coordinates='figure')
            hf.scatter(X1, Y1, color='0.5', s=1)
            """

            #fig, hf = plt.subplots(figsize=(10,10)) #original 10.10.2021
            #fig, hf = plt.subplots(figsize=(10, 5.63), dpi=80) # BJD changed here 10.10.2021
            fig, hf = plt.subplots(
                figsize=(5.63, 10))  #, dpi=80) # BJD changed here 10.10.2021
            # 5.633802816901408, 10 inches
            #figure(figsize=(8, 6), dpi=80)
            #hf.set_title("Model G fluid - diffusive flux vector of X - every 10th arrow, time = " + str(c1))
            hf.set_title(
                "Model G fluid - velocity vector field - every 10th arrow, time = "
                + str(c1))
            #Q = hf.quiver(X1[::10, ::10], Y1[::10, ::10], U[::10, ::10], V[::10, ::10],
            #pivot='mid', units='inches')
            #M = np.hypot(U, V)
            #Q = hf.quiver(X1[::7, ::7], Y1[::7, ::7], U1[::7, ::7], V1[::7, ::7], units='width',
            Q = hf.quiver(
                X1[::10, ::10],
                Y1[::10, ::10],
                U1[::10, ::10],
                V1[::10, ::10],
                units='width',
                pivot='mid',
                scale=0.1,
                headwidth=5
            )  #pivot='mid', units='inches')#, scale=1)#, scale=5)
            #qk = hf.quiverkey(Q, 0.9, 0.9, 1, r'$\frac{distance}{time}$', labelpos='E',
            #coordinates='figure')
            #qk = hf.quiverkey(Q, 0.9, 0.9, 0.1, r'$2d \ vector \ plot$', labelpos='E',
            qk = hf.quiverkey(Q,
                              0.9,
                              0.9,
                              0.1,
                              r'$distance/time$',
                              labelpos='E',
                              coordinates='figure')  #, color='b')
            hf.scatter(X1[::10, ::10], Y1[::10, ::10], color='c', s=0)
            #hf.scatter(Y1[::10, ::10], X1[::10, ::10], color='c', s=0) # BJD changed Y1 and X1 around - 10.10.2021

            #plt.show()

            #plt.title('Y potential in 2D space - time = ' + str(c1))
            #plt.xlabel("x spacial units")
            #plt.ylabel("y spacial units")
            #plt.zlabel("X, Y, G pot. - concentration per unit vol")
            #fig.savefig('test2.png')   # save the figure to file
            #plt.legend(["X", "Y", "G"]) # BJD legend added 21.11.2020
            #plt.show()

            plt.savefig(
                '/home/brendan/software/tf2-model-g/plots/2D_video56/2D_video_velocity_'
                + str(c1) + '.png')
            #plt.close(hf)    # close the figure window

            #y3 = np.loadtxt("/home/brendan/software/tf2-model-g/arrays/array10/G.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            #column1 = y1[120]  # choose column 120 of 2D array = (426,240)
            #column2 = y2[120]  # choose column 120 of 2D array = (426,240)
            #column3 = y3[120]  # choose column 120 of 2D array = (426,240)
            #row1 = y1[214]  # choose row 214 of 2D array = (426,240)
            #row2 = y2[214]  # choose row 214 of 2D array = (426,240)
            #row3 = y3[214]  # choose row 214 of 2D array = (426,240)

            #x, y = np.meshgrid(x, y, indexing='ij')
            #X, Y = np.meshgrid(np.arange(0, 2 * np.pi, .2), np.arange(0, 2 * np.pi, .2))
            #U = np.gradient(fluid_model_g.G,1)
            #V = np.gradient(fluid_model_g.G,2)
            #U = np.cos(X)
            #V = np.sin(Y)
            #np.savetxt("/home/brendan/software/tf2-model-g/arrays/quiver_array13/X.txt", np.gradient(fluid_model_g.G,1))
            # sphinx_gallery_thumbnail_number = 3
            """
Ejemplo n.º 15
0
def nucleation_and_motion_in_G_gradient_fluid_2D(writer, args, R=16):
    dx = 2 * R / args.height
    x = (np.arange(args.width) - args.width // 2) * dx
    y = (np.arange(args.height) - args.height // 2) * dx
    x, y = np.meshgrid(x, y, indexing='ij')

    def source_G(t):
        center = np.exp(-0.5 * (t - 5)**2) * 10
        gradient = (1 + np.tanh(t - 30)) * 0.0003
        return -np.exp(-0.5 * (x * x + y * y)) * center + (x + 8) * gradient

    source_functions = {
        'G': source_G,
    }

    flow = [0 * x, 0 * x]

    fluid_model_g = FluidModelG(
        x * 0,
        x * 0,
        x * 0,
        flow,
        dx,
        dt=args.dt,
        params=args.model_params,
        source_functions=source_functions,
    )

    print("Rendering 'Nucleation and Motion in G gradient in 2D'")
    print("Lattice constant dx = {}, time step dt = {}".format(
        fluid_model_g.dx, fluid_model_g.dt))
    min_G = -4.672736908320116
    max_G = 0.028719261862332906
    min_X = -3.8935243721220334
    max_X = 1.2854028081816122
    min_Y = -0.7454193158963579
    max_Y = 4.20524950766914
    #c1 = 0
    for n in progressbar.progressbar(range(args.num_frames)):
        fluid_model_g.step()
        if n % args.oversampling == 0:
            rgb = [
                6 * (-fluid_model_g.G + max_G) / (max_G - min_G),
                5 * (fluid_model_g.Y - min_Y) / (max_Y - min_Y),
                0.7 * (fluid_model_g.X - min_X) / (max_X - min_X),
            ]
            zero_line = 1 - tf.exp(-600 * fluid_model_g.Y**2)
            frame = make_video_frame([c * zero_line for c in rgb])
            writer.append_data(frame)
            #===========================================================================
            #if n == 4:
            #    X_array = [
            #        0.7*(fluid_model_g.X - min_X) / (max_X - min_X),
            #    ] # BJD put this in 18.11.2020
            #    print("Array of X: ", X_array) # ***** BJD inserted this line 18.11.2020 *****
            """
            print("H E L L O")
            y1 = np.loadtxt("test.txt") #, delimiter=" :-) ", usecols=(120))  # (426, 240)
            row1 = y1[120]
            
            print(row1)
            pp.plot(row1)
            pp.show()
            """


#==============================BJD 18.11.2020=============================================
#for i in xrange(10):
#with io.open("file_" + str(i) + ".dat", 'w', encoding='utf-8') as f:
#with io.open("file_" + str(c1) + ".txt", 'w', encoding='utf-8') as f:
#f.write(str(func(c1))

#for number in range(1, 11):
#filename = 'a%d.txt' % number
#data = read_data(filename)

#for c1 in xrange(10):
    for c1 in 10:
        print("H E L L O")
        y1 = np.loadtxt(
            "file_" + str(c1) + ".txt",
            'r')  #, delimiter=" :-) ", usecols=(120))  # (426, 240)
        row1 = y1[120]

        print(row1)
        pp.plot(row1)
        pp.show()