Пример #1
0
def save_mo_data(data_list, path, t, new_size):
    open_path = path + '/avg.hdf5'
    f = h5py.File(open_path, 'w')
    size = compute_new_size(new_size, focus)
    dset = f.create_dataset("avg_data", (len(data_list), size, size))
    d = 'modifying ' + t + ' data'
    pt = progress_timer(description=d, n_iter=len(data_list))
    for i in range(len(data_list)):
        dset[i, ...] = modify(data_list[i], total_grid_size, new_size)
        pt.update()
    f.close()
    pt.finish()
Пример #2
0
def save_data(data_list, path, t):
    open_path = path + '/ori.hdf5'
    f = h5py.File(open_path, 'w')
    dset = f.create_dataset("ori_data",
                            (len(data_list), total_grid_size, total_grid_size))
    d = 'saving ' + t + ' data'
    pt = progress_timer(description=d, n_iter=len(data_list))
    for i in range(len(data_list)):
        dset[i, ...] = data_list[i]
        pt.update()
    f.close()
    pt.finish()
Пример #3
0
def gen(input, output, max_atm_length, num_exm):
    # define which character is an atom
    atoms = ['C', 'F', 'H', 'N', 'O', 'c', 'n', 'o']
    # save atom number of the word at the same time
    dict = {'words': [], 'atm-num': []}
    # load in words
    path = input + '.txt'
    with open(path, 'rb') as f:
        for word in f:
            word = word.decode('utf-8').replace("\n", "")
            dict['words'].append(word)
            atm_num = 0
            counter = Counter(word)
            for atom in atoms:
                atm_num += counter[atom]
            dict['atm-num'].append(atm_num)
    # find the maximum atom number
    max_atm_num = max(dict['atm-num'])
    # separate the words into several bins according to atom number
    bins = {}
    for i in range(max_atm_num):
        bins[i + 1] = []
    for i in range(len(dict['words'])):
        bins[dict['atm-num'][i]].append(dict['words'][i])
    # maximum word number of one atom size of word
    max_num = []
    for i in range(max_atm_num):
        max_num.append(max_atm_length // (i + 1))
    # begin to generate sentences
    sents = []
    pt = progress_timer(description='generating examples', n_iter=num_exm)
    while len(sents) < num_exm:
        mole_num = [np.random.randint(max_num[i]) for i in range(len(max_num))]
        total_atm_num = 0
        for j in range(max_atm_num):
            total_atm_num += (j + 1) * mole_num[j]
        if total_atm_num > max_atm_length:
            continue
        else:
            sent = []
            for j in range(max_atm_num):
                for k in range(mole_num[j]):
                    sent.append(random.sample(bins[j + 1], 1)[0])
            random.shuffle(sent)
            str_sent = ' '.join(sent)
            sents.append(str_sent)
            pt.update()
    pt.finish()
    # save sentences
    text = '\n'.join(sents)
    path = output + '.txt'
    with open(path, 'ab+') as f:
        f.write(text.encode('utf-8'))
Пример #4
0
def nse(Re=1000,
        temam=False,
        bfs=False,
        level=1,
        velocity_degree=2,
        eps=0.0002,
        dt=0.001,
        auto=False,
        plotcircles=0,
        gammagiv=1):

    mesh_root = 'stenosis_f0.6'
    if level == 2:
        mesh_root += '_fine'

    mesh = Mesh(mesh_root + '.xml')
    boundaries = MeshFunction('size_t', mesh, mesh_root + '_facet_region.xml')
    ds = Measure('ds', domain=mesh, subdomain_data=boundaries)
    stabmethod = 'No stabilization'

    VE = VectorElement('P', mesh.ufl_cell(), velocity_degree)
    PE = FiniteElement('P', mesh.ufl_cell(), 1)
    W = FunctionSpace(mesh, VE * PE)

    u, p = TrialFunctions(W)
    v, q = TestFunctions(W)
    w = Function(W)
    u0, p0 = w.split()

    ####

    theta = Constant(1)
    k = Constant(1 / dt)
    mu = Constant(0.035)
    rho = Constant(1.2)
    eps = Constant(eps)

    U = (3 / 2) * 0.5 * Re * float(mu) / float(rho)

    print('\n Re = {}, U = {}\n'.format(Re, U))

    u_ = theta * u + (1 - theta) * u0
    theta_p = theta
    p_ = theta_p * p + (1 - theta_p) * p0

    laplace = mu * inner(grad(u_), grad(v)) * dx

    F = (k * rho * dot(u - u0, v) * dx + laplace - p_ * div(v) * dx +
         q * div(u) * dx + rho * dot(grad(u_) * u0, v) * dx)

    # F = (
    #     k*rho*dot(u - u0, v)*dx
    #     + mu*inner(grad(u_), grad(v))*dx
    #     - p_*div(v)*dx + q*div(u)*dx
    #     + rho*dot(grad(u_)*u0, v)*dx
    # )

    n = FacetNormal(mesh)
    h = CellDiameter(mesh)

    # eps = Constant(dt * float(mu) / (0.1 ** 2 * float(rho)))

    if temam:
        F += 0.5 * rho * div(u0) * dot(u_, v) * dx

    beta = Constant(1)  #TODO add initial values, probably 1
    gamma = Constant(gammagiv)

    backflow_func = 0.5 * rho * HF.abs_n(dot(u0, n)) * dot(u_, v) * ds(
        2)  #0.5 * rho * HF.abs_n(div(u0)) * dot(u_, v) * dx

    param = 'No param'

    G = 0
    ### Added here beta parameter to the stabilization terms which we can control
    if bfs == 1:
        param = 'beta'
        stabmethod = 'velocity-penalization'
        G = 0.5 * rho * beta * dot(u0, n) * dot(u_, v) * ds(2)
        F -= G
    elif bfs == 2:
        param = 'beta'
        stabmethod = 'velocity-penalization negative part'
        G = 0.5 * rho * beta * HF.abs_n(dot(u0, n)) * dot(u_, v) * ds(2)
        F -= G
    elif bfs == 3:
        param = 'gamma'
        stabmethod = 'tangential penalization'
        Ctgt = h**2
        G = gamma * Ctgt * 0.5 * rho * HF.abs_n(dot(u0, n)) * (
            Dx(u[0], 1) * Dx(v[0], 1) + Dx(u[1], 1) * Dx(v[1], 1)) * ds(2)
    elif bfs == 4:
        param = 'gamma'
        stabmethod = 'tangential penalization - 2016 paper'
        Ctgt = h**2
        print(type(u0))
        max1 = assemble(HF.abs_n(u0) * ds(2))
        max2 = np.array(max1.array())
        max3 = abs(max2)
        maxi = max3.max()
        G = -1 * gamma * maxi * 0.5 * rho * Ctgt * (
            Dx(u[0], 1) * Dx(v[0], 1) + Dx(u[1], 1) * Dx(v[1], 1)) * ds(2)
        F -= G
    elif velocity_degree == 1 and float(eps):
        F += eps / mu * h**2 * inner(grad(p_), grad(q)) * dx

    # if temam:
    #     F += 0.5*rho*div(u0)*dot(u_, v)*dx
    #
    # if bfs == 1:
    #     F -= 0.5*rho*dot(u0, n)*dot(u_, v)*ds(2)
    # elif bfs == 2:
    #     F -= 0.5*rho*HF.abs_n(dot(u0, n))*dot(u_, v)*ds(2)
    # elif bfs == 3:
    #     Ctgt = h**2
    #     F -= Ctgt*0.5*rho*HF.abs_n(dot(u0, n))*(
    #         Dx(u[0], 1)*Dx(v[0], 1) + Dx(u[1], 1)*Dx(v[1], 1))*ds(2)
    #
    # elif velocity_degree == 1 and float(eps):
    #     F += eps/mu*h**2*inner(grad(p_), grad(q))*dx
    numerical = 0.5 * rho * k * dot(u_ - u0, u_ - u0) * dx
    stabilisationTest = backflow_func - G  #+ laplace + numerical

    a = lhs(F)
    L = rhs(F)

    inflow = Expression(('sin(a*t*DOLFIN_PI)*U*(1 - pow(x[1], 2))', '0.'),
                        U=U,
                        t=0.,
                        a=2.5,
                        degree=2)
    # inflow = Expression(('U*(1 - pow(x[1], 2))', '0.'),
    #                     U=U, t=0., degree=2)
    bcs = [
        DirichletBC(W.sub(0), Constant((0, 0)), boundaries, 4),
        DirichletBC(W.sub(0), inflow, boundaries, 1),
        DirichletBC(W.sub(0).sub(1), Constant(0), boundaries, 3),
    ]

    A = assemble(a)

    if auto:
        runtype = "auto"
    elif param == 'beta':
        runtype = round(assemble(beta * ds(2)), 3)
    elif param == 'gamma':
        runtype = round(assemble(gamma * ds(2)))

    suf = 'bfs{}_tem{}_Re{}_'.format(int(bfs), int(temam),
                                     Re) + param + '_' + '{}_'.format(runtype)
    if velocity_degree == 1:
        suf = 'p1_' + suf
    suf = 'l{}_'.format(level) + suf

    xdmf_u = XDMFFile('results/u_' + suf + '.xdmf')
    xdmf_p = XDMFFile('results/p_' + suf + '.xdmf')
    xdmf_tau = XDMFFile('tau_sd_' + suf + '.xdmf')
    # xdmf_u.parameters['rewrite_function_mesh'] = False
    # xdmf_p.parameters['rewrite_function_mesh'] = False
    # xdmf_tau.parameters['rewrite_function_mesh'] = False

    u0.rename('u', 'u')
    p0.rename('p', 'p')

    w0 = Function(W)
    # r0, s0 = w0.split()
    #
    # w1 = Function(W)
    # r1, s1 = w1.split()

    # FINAL TIME
    T = 0.4

    # PLOTTING VECTORS
    # viscEnergyVec = np.zeros(((int)(T / dt), 1))
    # ToteviscEnergyVec = np.zeros(((int)(T / dt), 1))
    # incEnergyVec = np.zeros(((int)(T / dt), 1))
    # incEnergyVec2 = np.zeros(((int)(T / dt), 1))
    # numEnergyVec = np.zeros(((int)(T / dt), 1))
    # stabEnergyVec = np.zeros(((int)(T / dt), 1))
    # avgeig = np.zeros(((int)(T / dt), 1))
    #     print(type(F))

    pt = prog.progress_timer(description='Time Iterations', n_iter=40)
    # MAIN SOLVING LOOP
    eigvec = np.array([0, 0])
    for t in np.arange(dt, T + dt, dt):

        # print('t = {}'.format(round(t, 2)))

        #### May not be necessary ####
        w0.assign(w)
        r0, s0 = w0.split()

        inflow.t = t
        assemble(a, tensor=A)
        b = assemble(L)
        [bc.apply(A, b) for bc in bcs]
        solve(A, w.vector(), b)

        #### May not be necessary ####

        ###

        # w1.assign(w)
        # r1, s1 = w1.split()
        #
        # r1.vector().set_local(u0.vector().get_local() * (u0.vector().get_local() < 0))
        #
        # # ite +=1
        # # if ite==5:
        # #    plt.plot(r1.vector().get_local())
        # #    plt.plot(u0.vector().get_local())
        #
        # # print('|u|:', norm(u0))
        # # print('|p|:', norm(p0))
        # # print('div(u):', assemble(div(u0)*dx))
        #
        # ### This was trying to view U0 as a numpy array but didnt show anything meaningful ####
        # # for i in u0.vector().get_local():
        # #     print(i)
        # # print(u0.vector().get_local())
        #
        # # BACKFLOW KINETIC ENERGY CHANGE
        # BKE = assemble((rho / 2) * HF.abs_n(dot(r0, n)) * dot(u0, u0) * ds(2))

        # BACKFLOW VISCOUS ENERGY CHANGE
        # BVE = assemble(mu * inner(grad(r1),grad(r1)) * ds(2))
        # TVE = assemble(mu * inner(grad(u0),grad(u0))  * ds(2))
        # TVE = assemble(mu * inner(grad(u0), grad(u0)) * dx)

        #         print( (HF.abs_n(u0) != 0) )
        # BVEs = assemble(mu * np.abs(div(u0)) * div(r1) * ds(2))

        # TODO rework the backflowarea function so that it is one when there is backflow and 0 otherwise

        # ADDING TO VECTORS
        # viscEnergyVec[(int)(t / dt) - 1] = BVE
        # ToteviscEnergyVec[(int)(t / dt) - 1] = TVE
        #
        # incEnergyVec[(int)(t / dt) - 1] = BKE
        #
        # numEnergyVec[(int)(t / dt) - 1] = assemble((dot(u0 - r0, u0 - r0)) * ds(2))
        # print(numEnergyVec[(int)(t / dt) - 1])

        if bfs == 3 and auto:
            numericalfunc = 0  #0.5 * rho * dot(u0 - r0, u0 - r0) * dx
            backflow_mat = assemble(lhs(backflow_func))
            backflow_vec = np.array(backflow_mat.array())
            #
            gamma.assign(1)
            while True:
                ### Building matrix and applying eigenvalues
                stabTensor = assemble(lhs(stabilisationTest + numericalfunc))
                # for bc in bcs: bc.apply(stabTensor)
                stabMatrix = np.array(stabTensor.array())
                # stabMatrix += np.eye(stabMatrix.shape[0])
                stabMatrix_backflow = stabMatrix * (backflow_vec != 0)
                stabMatrix_backflow_Nozero = stabMatrix_backflow[~(
                    stabMatrix_backflow == 0).all(1)]

                # stabMatrix_sparse = sp.sparse.bsr_matrix(stabMatrix) # Sparse Version

                ### Creating reduced backflow matrix
                reduced_stabMatrix = np.transpose(
                    stabMatrix_backflow_Nozero.transpose()
                    [~(stabMatrix_backflow_Nozero.transpose() == 0).all(1)])
                eigenvals_reduced_stabMatrix = LA.eigvals(reduced_stabMatrix)
                if plotcircles == 1:

                    circles = HF.GregsCircles(reduced_stabMatrix)
                    fig = HF.plotCircles(circles, round(t, 2), stabmethod,
                                         param, runtype)

                    if plotcircles == 2:
                        stabMatrix_sparse = sp.sparse.bsr_matrix(
                            stabMatrix)  # Sparse Version
                        small_eigenvals_stabMatrix = ssl.eigs(
                            stabMatrix_sparse,
                            5,
                            sigma=-10,
                            which='LM',
                            return_eigenvectors=False)
                        for EV in small_eigenvals_stabMatrix:
                            plt.plot(EV.real, EV.imag, 'wo')

                    for eigval in eigenvals_reduced_stabMatrix:
                        plt.plot(eigval.real, eigval.imag, 'r+')
                    fig.savefig('circles/' + str(round(t * 100)) + 'gersh.png')
                    plt.close(fig)

                if eigenvals_reduced_stabMatrix.size == 0:
                    del stabTensor, stabMatrix, reduced_stabMatrix, eigenvals_reduced_stabMatrix
                    break
                if eigenvals_reduced_stabMatrix.min() >= 0:
                    del stabTensor, stabMatrix, reduced_stabMatrix, eigenvals_reduced_stabMatrix
                    break
                else:
                    del stabTensor, stabMatrix, reduced_stabMatrix, eigenvals_reduced_stabMatrix
                    gamma.assign(assemble(gamma * ds(2)) * 2)

            # print(round(assemble(gamma * ds(2))))
        elif (bfs == 1 or bfs == 2) and auto:
            numericalfunc = 0  #0.5 * rho * dot(u0 - r0, u0 - r0) * dx
            #     # numericalEn = assemble(numericalfunc)
            #     # print(numericalEn)
            #
            backflow_mat = assemble(lhs(backflow_func))
            backflow_vec = np.array(backflow_mat.array())
            #
            beta.assign(1)
            betaold = 1
            betanew = 1
            while True:
                ### Building matrix and applying eigenvalues
                stabTensor = assemble(lhs(stabilisationTest + numericalfunc))
                # for bc in bcs: bc.apply(stabTensor)
                stabMatrix = np.array(stabTensor.array())
                # stabMatrix += np.eye(stabMatrix.shape[0])
                stabMatrix_backflow = stabMatrix * (backflow_vec != 0)
                stabMatrix_backflow_Nozero = stabMatrix_backflow[~(
                    stabMatrix_backflow == 0).all(1)]

                ### Creating reduced backflow matrix
                reduced_stabMatrix = np.transpose(
                    stabMatrix_backflow_Nozero.transpose()
                    [~(stabMatrix_backflow_Nozero.transpose() == 0).all(1)])
                eigenvals_reduced_stabMatrix = LA.eigvals(reduced_stabMatrix)
                if plotcircles == 1:

                    circles = HF.GregsCircles(reduced_stabMatrix)
                    fig = HF.plotCircles(circles, round(t, 2), stabmethod,
                                         param, runtype)

                    if plotcircles == 2:
                        stabMatrix_sparse = sp.sparse.bsr_matrix(
                            stabMatrix)  # Sparse Version
                        small_eigenvals_stabMatrix = ssl.eigs(
                            stabMatrix_sparse,
                            5,
                            sigma=-10,
                            which='LM',
                            return_eigenvectors=False)
                        for EV in small_eigenvals_stabMatrix:
                            plt.plot(EV.real, EV.imag, 'wo')

                    for eigval in eigenvals_reduced_stabMatrix:
                        plt.plot(eigval.real, eigval.imag, 'r+')
                    fig.savefig('circles/' + str(round(t * 100)) + 'gersh.png')
                    plt.close(fig)

                if eigenvals_reduced_stabMatrix.size == 0:
                    del stabTensor, stabMatrix, reduced_stabMatrix, eigenvals_reduced_stabMatrix
                    break
                if eigenvals_reduced_stabMatrix.min() < 0 or betanew < 0.2:
                    del stabTensor, stabMatrix, reduced_stabMatrix, eigenvals_reduced_stabMatrix
                    beta.assign(betaold)
                    break
                else:
                    betaold = betanew
                    betanew -= 0.05
                    beta.assign(betanew)
                    del stabTensor, stabMatrix, reduced_stabMatrix, eigenvals_reduced_stabMatrix
        if plotcircles > 0 and not auto:
            numericalfunc = 0  #0.5 * rho * dot(u0 - r0, u0 - r0) * dx
            backflow_mat = assemble(lhs(backflow_func))
            backflow_vec = np.array(backflow_mat.array())

            stabTensor = assemble(lhs(stabilisationTest + numericalfunc))
            # for bc in bcs: bc.apply(stabTensor)
            stabMatrix = np.array(stabTensor.array())
            stabMatrix_backflow = stabMatrix * (backflow_vec != 0)
            stabMatrix_backflow_Nozero = stabMatrix_backflow[~(
                stabMatrix_backflow == 0).all(1)]
            reduced_stabMatrix = np.transpose(
                stabMatrix_backflow_Nozero.transpose()
                [~(stabMatrix_backflow_Nozero.transpose() == 0).all(1)])
            eigenvals_reduced_stabMatrix = LA.eigvals(reduced_stabMatrix)
            circles = HF.GregsCircles(reduced_stabMatrix)
            fig = HF.plotCircles(circles, round(t, 2), stabmethod, param,
                                 runtype)
            if plotcircles == 2 and eigenvals_reduced_stabMatrix.size > 0:
                stabMatrix_sparse = sp.sparse.bsr_matrix(
                    stabMatrix)  # Sparse Version
                # print(stabMatrix_sparse)
                small_eigenvals_stabMatrix = ssl.eigs(
                    stabMatrix_sparse,
                    5,
                    sigma=-10,
                    which='LM',
                    return_eigenvectors=False,
                    v0=np.ones(stabMatrix_sparse.shape[0]))
                if t > 0.245 and t < 0.255:
                    eigvec = np.array([
                        small_eigenvals_stabMatrix.min(),
                        small_eigenvals_stabMatrix.max()
                    ])
                printlab = True
                for EV in small_eigenvals_stabMatrix:
                    if printlab:
                        plt.plot(EV.real,
                                 EV.imag,
                                 'ko',
                                 label='Eigenvalues of full Matrix')
                        printlab = False
                    else:
                        plt.plot(EV.real, EV.imag, 'ko', label='_nolegend_')
                print(small_eigenvals_stabMatrix.min())
                del small_eigenvals_stabMatrix, stabMatrix_sparse
            printlab = True
            for eigval in eigenvals_reduced_stabMatrix:
                if printlab:
                    plt.plot(eigval.real,
                             eigval.imag,
                             'r+',
                             label='Eigenvalues of reduced Matrix')
                    printlab = False
                else:
                    plt.plot(eigval.real,
                             eigval.imag,
                             'r+',
                             label='_nolegend_')

            if eigenvals_reduced_stabMatrix.size > 0:
                plt.legend()
            fig.savefig('circles/' + str(round(t * 100)) + 'gersh.png')
            del stabTensor, stabMatrix, reduced_stabMatrix, eigenvals_reduced_stabMatrix
            plt.close(fig)
            # print(round(assemble(beta * ds(2)), 5))

        # print("stabilisationTest matrix is: " + HF.diag_dom(stabMatrix))
        #
        #
        # print("Reduced Matrix is: " + HF.diag_dom(reduced_stabMatrix))

        ### Print out the values for the energy changes at the current time step
        # print('Viscous energy change:', viscEnergyVec[(int)(t/dt) - 1])
        # print('Incoming energy change:', incEnergyVec[(int)(t/dt) - 1])
        # print('Numerical energy:', numEnergyVec[(int)(t/dt) - 1])

        xdmf_u.write(u0, t)
        xdmf_p.write(p0, t)
        pt.update()
    pt.finish()
    return eigvec

    # plt.figure()
    # # plt.plot(viscEnergyVec, 'b', label="Viscous")
    # # plt.plot(ToteviscEnergyVec, 'forestgreen', label="tot Viscous")
    # plt.plot(incEnergyVec, 'red', label="Incoming")
    # # plt.plot(numEnergyVec, 'yellow', label="Numerical")
    # # plt.plot(stabEnergyVec, 'orange', label='Stabilization')
    # plt.plot(ToteviscEnergyVec + numEnergyVec, 'deepskyblue', label='Total corrective energy')
    # plt.legend(loc='upper left')
    # plt.title('Energy changes of ' + stabmethod)
    # plt.show()

    del xdmf_u, xdmf_p
Пример #5
0
def gen_data(num_exm, total_grid_size=256, max_mole_dist=32, max_mole_size=30):
    """
    generate data
    :param num_exm: number of exmaples
    :param total_grid_size: size of studying area
    :param max_mole_size: maximum size of molecules
    """
    # initialize timer
    pt = progress_timer(description='creating examples', n_iter=num_exm)
    # set up a dict to memorize the data
    data = {'grid': [], 'total': [], 'ising': [], 'elec': []}
    # compute maximum molecule number
    max_mole_num = ((total_grid_size // max_mole_dist) / 2)**2
    for z in range(num_exm):
        # initialize grid
        grid = np.zeros(shape=[total_grid_size, total_grid_size])
        total_energy = 0
        total_ising_energy = 0
        total_electric_energy = 0
        centers = []
        charges = []
        mole_num = np.random.randint(2, max_mole_num)
        while len(centers) < mole_num:
            coor = [
                np.random.randint(total_grid_size),
                np.random.randint(total_grid_size)
            ]
            real_coor = True
            for pre_coor in centers:
                if (abs(pre_coor[0] - coor[0]) < max_mole_dist) & (
                        abs(pre_coor[1] - coor[1]) < max_mole_dist):
                    real_coor = False
                    break
            if not real_coor:
                continue
            x_range_l = np.random.randint(max_mole_size / 2)
            if x_range_l > coor[0]:
                x_range_l = coor[0]
            y_range_d = np.random.randint(max_mole_size / 2)
            if y_range_d > coor[1]:
                y_range_d = coor[1]
            x_range_r = np.random.randint(max_mole_size / 2)
            if x_range_r > total_grid_size - coor[0] - 1:
                x_range_r = total_grid_size - coor[0] - 1
            y_range_u = np.random.randint(max_mole_size / 2)
            if y_range_u > total_grid_size - coor[1] - 1:
                y_range_u = total_grid_size - coor[1] - 1
            mole = np.round(
                np.random.uniform(size=[
                    x_range_l + x_range_r + 1, y_range_d + y_range_u + 1
                ]))
            mole = mole * 2 - 1
            for m in range(x_range_l + x_range_r + 1):
                for n in range(y_range_d + y_range_u + 1):
                    grid.itemset(
                        (coor[0] - x_range_l + m, coor[1] - y_range_d + n),
                        mole[m][n])
            ising_energy = H(mole)
            total_ising_energy += ising_energy
            charge = np.sum(mole)
            center = [(2 * coor[0] - x_range_l + x_range_r) / 2,
                      (2 * coor[1] - y_range_d + y_range_u) / 2]
            for i in range(len(centers)):
                dist = np.sqrt(
                    np.square(centers[i][0] - center[0]) +
                    np.square(centers[i][1] - center[1]))
                total_electric_energy += 10 * charge * charges[i] / dist
            charges.append(charge)
            centers.append(center)
        total_energy = total_electric_energy + total_ising_energy
        data['grid'].append(grid)
        data['total'].append(total_energy)
        data['ising'].append(total_ising_energy)
        data['elec'].append(total_electric_energy)
        p_str = "generating done " + str(z)
        pt.update()
    pt.finish()
    return data
Пример #6
0
def nse(Re=1000, temam=False, bfs=False, level=1, velocity_degree=2, eps=0.0002, dt=0.001, plotcircles=0, gammagiv=1, betagiv=1):

    mesh_root = 'stenosis_f0.6'
    if level == 2:
        mesh_root += '_fine'

    mesh = Mesh(mesh_root + '.xml')
    boundaries = MeshFunction('size_t', mesh, mesh_root + '_facet_region.xml')
    ds = Measure('ds', domain=mesh, subdomain_data=boundaries)
    stabmethod = 'No stabilization'

    VE = VectorElement('P', mesh.ufl_cell(), velocity_degree)
    PE = FiniteElement('P', mesh.ufl_cell(), 1)
    W = FunctionSpace(mesh, VE * PE)

    u, p = TrialFunctions(W)
    v, q = TestFunctions(W)
    w = Function(W)
    u0, p0 = w.split()


    ####

    theta = Constant(1)
    k = Constant(1 / dt)
    mu = Constant(0.035)
    rho = Constant(1.2)
    eps = Constant(eps)





    U = (3 / 2) * 0.5 * Re * float(mu) / float(rho)

    print('\n Re = {}, U = {}\n'.format(Re, U))

    u_ = theta * u + (1 - theta) * u0
    theta_p = theta
    p_ = theta_p * p + (1 - theta_p) * p0

    laplace = mu * inner(grad(u_), grad(v)) * dx #Defined separately so it may be used later

    F = (
            k * rho * dot(u - u0, v) * dx
            + laplace
            - p_ * div(v) * dx + q * div(u) * dx
            + rho * dot(grad(u_) * u0, v) * dx
    )

    n = FacetNormal(mesh)
    h = CellDiameter(mesh)

    # eps = Constant(dt * float(mu) / (0.1 ** 2 * float(rho)))

    if temam:
        F += 0.5 * rho * div(u0) * dot(u_, v) * dx

    beta = Constant(betagiv)    #Defines the initial beta from the given value
    gamma = Constant(gammagiv) #Defines the initial gamma from the given value

    backflow_func = 0.5 * rho * HF.abs_n(dot(u0, n)) * dot(u_, v) * ds(2) 

    param = 'No param'

    G = 0 #This variable will contain the backflow stabilisation term
    ### Added here beta parameter to the stabilization terms which we can control
    if bfs == 1:
        param = 'beta' #Setting the string for the parameter being changed
        stabmethod = 'velocity-penalization'  #Setting the string for the stabilisation method being changed
        G = 0.5 * rho * beta * dot(u0, n) * dot(u_, v) * ds(2)
        F -= G
    elif bfs == 2:
        param = 'beta'
        stabmethod = 'velocity-penalization negative part'
        G = 0.5 * rho * beta * HF.abs_n(dot(u0, n)) * dot(u_, v) * ds(2)
        F -= G
    elif bfs == 3:
        param = 'gamma'
        stabmethod = 'tangential penalization'
        Ctgt = h ** 2
        G = gamma * Ctgt * 0.5 * rho * HF.abs_n(dot(u0, n)) * (
                Dx(u[0], 1) * Dx(v[0], 1) + Dx(u[1], 1) * Dx(v[1], 1)) * ds(2)
    elif bfs == 4:
        param = 'gamma'
        stabmethod = 'tangential penalization - 2016 paper'
        Ctgt = h ** 2

        maxiv = HF.maxUneg(W, mesh, u0) #Finding the max|u dot n|_ 
        maxi = Constant(maxiv)

        G = -1 * gamma * maxi * 0.5 * rho * Ctgt * (Dx(u[0], 1) * Dx(v[0], 1) + Dx(u[1], 1) * Dx(v[1], 1)) * ds(2)
        F -= G
    elif velocity_degree == 1 and float(eps):
        F += eps / mu * h ** 2 * inner(grad(p_), grad(q)) * dx

    stabilisationTest = backflow_func - G #This term will be the one worked with during the automation, it could have added terms
                                          #Such as the laplace or other stabilising terms.

    a = lhs(F)
    L = rhs(F)

    inflow = Expression(('sin(a*t*DOLFIN_PI)*U*(1 - pow(x[1], 2))', '0.'),
                        U=U, t=0., a=2.5, degree=2)
    # inflow = Expression(('U*(1 - pow(x[1], 2))', '0.'),
    #                     U=U, t=0., degree=2)
    bcs = [
        DirichletBC(W.sub(0), Constant((0, 0)), boundaries, 4),
        DirichletBC(W.sub(0), inflow, boundaries, 1),
        DirichletBC(W.sub(0).sub(1), Constant(0), boundaries, 3),
    ]

    A = assemble(a)

    #Below is needed for good plots
    if auto:
        runtype = "auto"
    elif param == 'beta':
        runtype = round(assemble(beta * ds(2)), 3)
    elif param == 'gamma':
        runtype = round(assemble(gamma * ds(2)))
    elif param == 'No param':
        runtype = "No param"

    #The below is for formatting that names of the output files to be used in paraview
    suf = 'bfs{}_tem{}_Re{}_'.format(int(bfs), int(temam), Re) + param + '_' + '{}_'.format(runtype)
    if velocity_degree == 1:
        suf = 'p1_' + suf
    suf = 'l{}_'.format(level) + suf

    xdmf_u = XDMFFile('results/u_' + suf + '.xdmf')
    xdmf_p = XDMFFile('results/p_' + suf + '.xdmf')
    xdmf_tau = XDMFFile('tau_sd_' + suf + '.xdmf')
    # xdmf_u.parameters['rewrite_function_mesh'] = False
    # xdmf_p.parameters['rewrite_function_mesh'] = False
    # xdmf_tau.parameters['rewrite_function_mesh'] = False

    u0.rename('u', 'u')
    p0.rename('p', 'p')

    # FINAL TIME
    T = 0.4

    pt = prog.progress_timer(description='Time Iterations', n_iter=40) #Used to have a progress bar
    # MAIN SOLVING LOOP
    eigvec = []#Used when finding eigenvalues with varying values of the parameters, i.e. when needing to run multiple times

    for t in np.arange(dt, T + dt, dt):
        
        ## Using Fenics to find the current solution
        inflow.t = t
        assemble(a, tensor=A)
        b = assemble(L)
        [bc.apply(A, b) for bc in bcs]
        solve(A, w.vector(), b)

        ## Creating all the plots
        if plotcircles > 0:
            if bfs == 4: # Update the max|u dot n|_
                maxiv = HF.maxUneg(W, mesh, u0)
                maxi.assign(maxiv)

            ## Creating matrix with just backflow term
            backflow_mat = assemble(lhs(backflow_func))
            backflow_vec = np.array(backflow_mat.array())

            ## Create backflow with stabilisation matrix
            stabTensor = assemble(lhs(stabilisationTest))
            # for bc in bcs: bc.apply(stabTensor) %% If including the Laplace term then need to apply BC's
            stabMatrix = np.array(stabTensor.array())

            ## Creating reduced Stabilisation Matrix
            if backflow_vec.any():
                maxidx2 = np.array([np.nonzero(backflow_vec)[0].max(), np.nonzero(backflow_vec)[1].max()]).max()
                minidx2 = np.array([np.nonzero(backflow_vec)[0].min(), np.nonzero(backflow_vec)[1].min()]).min()
                reduced_stabMatrix = stabMatrix[minidx2:maxidx2 + 1, minidx2:maxidx2 + 1]
            else:
                reduced_stabMatrix = np.resize(np.array([]), [1, 1])

            ## Finding eigenvalues of reduced matrix and making the Gershgorin circles
            eigenvals_reduced_stabMatrix = LA.eigvals(reduced_stabMatrix)
            circles = HF.GregsCircles(reduced_stabMatrix)
            fig = HF.plotCircles(circles, round(t, 2), stabmethod, param, runtype)

            ## If want the minimum eigenvalues of the entire matrix and plot them
            if plotcircles == 2 and eigenvals_reduced_stabMatrix.size > 0 and stabMatrix.any():
                stabMatrix_sparse = sp.sparse.bsr_matrix(stabMatrix)  # Sparse Version
                small_eigenvals_stabMatrix = ssl.eigs(stabMatrix_sparse, 5, sigma=-10, which='LM', return_eigenvectors=False, v0=np.ones(stabMatrix_sparse.shape[0]))
                printlab = True
                for EV in small_eigenvals_stabMatrix:
                    if printlab:
                        plt.plot(EV.real, EV.imag, 'ko', label='Eigenvalues of full Matrix')
                        printlab = False
                    else:
                        plt.plot(EV.real, EV.imag, 'ko', label='_nolegend_')
                del stabMatrix_sparse, small_eigenvals_stabMatrix
            
            ## Plotting the eigenvalues of the reduced matrix
            printlab = True
            for eigval in eigenvals_reduced_stabMatrix:
                if printlab:
                    plt.plot(eigval.real, eigval.imag, 'r+', label='Eigenvalues of reduced Matrix')
                    printlab = False
                else:
                    plt.plot(eigval.real, eigval.imag, 'r+', label='_nolegend_')
            if eigenvals_reduced_stabMatrix.size > 0:
                plt.legend()
            fig.savefig('circles/' + str(round(t * 100)) + 'gersh.png')
            del stabTensor, stabMatrix, reduced_stabMatrix, eigenvals_reduced_stabMatrix, backflow_mat, backflow_vec
            plt.close(fig)


        xdmf_u.write(u0, t)
        xdmf_p.write(p0, t)
        pt.update()
    pt.finish()
    return eigvec

    del xdmf_u, xdmf_p