示例#1
0
def test_hamiltonian_solver_stress_eigval_sep(a_sep):
    BIGDIM = 100
    nroot = 3
    guess = list(np.random.randn(BIGDIM, nroot).T)
    test_engine = HSProblemSimulate(BIGDIM, a_sep=a_sep, b_sep=a_sep / 10)
    test_vals, test_rvecs, test_lvecs, _ = hamiltonian_solver(
        engine=test_engine,
        guess=guess,
        nroot=nroot,
        # Don't let the ss grow to size of real thing
        max_vecs_per_root=20,
        # Don't assault stdout with logging
        verbose=0,
        maxiter=1000)

    assert test_vals is not None, "The solver failed to converge"

    # compute the reference values, Use the partially reduced non-hermitian form of the problem, solve for RH-eigenvectors
    ref_H = np.dot(test_engine.A - test_engine.B, test_engine.A + test_engine.B)
    ref_vals, ref_rvecs = np.linalg.eig(ref_H)
    # Associated eigenvalues are the squares of the 2N dimensional problem
    ref_vals = np.sqrt(ref_vals)
    # sort the values/vectors
    sort_idx = ref_vals.argsort()
    ref_vals = ref_vals[sort_idx]
    ref_rvecs = ref_rvecs[:, sort_idx]

    # truncate to number of roots found
    ref_vals = ref_vals[:nroot]
    ref_rvecs = ref_rvecs[:, :nroot]

    # compare values
    compare_arrays(ref_vals, test_vals, 5, "Hamiltonian Eigenvalues")
示例#2
0
def test_restricted_RPA_triplet_c1():
    "Build out the full CIS/TDA hamiltonian (A) col by col with the product engine"
    h2o = psi4.geometry("""
    O
    H 1 0.96
    H 1 0.96 2 104.5
    symmetry c1
    """)
    psi4.set_options({"scf_type": "pk", 'save_jk': True})
    e, wfn = psi4.energy("hf/cc-pvdz", molecule=h2o, return_wfn=True)
    A_ref, B_ref = build_RHF_AB_C1_triplet(wfn)
    ni, na, _, _ = A_ref.shape
    nia = ni * na
    A_ref = A_ref.reshape((nia, nia))
    B_ref = B_ref.reshape((nia, nia))
    P_ref = A_ref + B_ref
    M_ref = A_ref - B_ref
    # Build engine
    eng = TDRSCFEngine(wfn, ptype='rpa', triplet=True)
    # our "guess"" vectors
    ID = [psi4.core.Matrix.from_array(v.reshape((ni, na))) for v in tuple(np.eye(nia).T)]
    Px, Mx = eng.compute_products(ID)[:-1]
    P_test = np.column_stack([x.to_array().flatten() for x in Px])
    assert compare_arrays(P_ref, P_test, 8, "RHF (A+B)x C1 products")
    M_test = np.column_stack([x.to_array().flatten() for x in Mx])
    assert compare_arrays(M_ref, M_test, 8, "RHF (A-B)x C1 products")
示例#3
0
def test_davidson_solver_stress_eigval_sep(sep):
    """Solver can miss "skip" a root if they are close in the range we are looking at"""
    BIGDIM = 100
    nroot = 3
    guess = list(np.random.randn(BIGDIM, nroot).T)
    test_engine = DSProblemSimulate(BIGDIM, sep=sep)
    test_vals, test_vectors, _ = davidson_solver(
        engine=test_engine,
        guess=guess,
        nroot=nroot,
        #Don't let the ss grow to size of real thing
        max_vecs_per_root=20,
        # Don't assault stdout with logging
        verbose=0,
        maxiter=1000)

    assert test_vals is not None, "Solver Failed to converge"
    ref_vals, ref_vectors = np.linalg.eigh(test_engine.A)
    idx = ref_vals.argsort()[:nroot]
    ref_vals = ref_vals[idx]
    ref_vectors = ref_vectors[:, idx]

    compare_arrays(ref_vals, test_vals, 6, "Davidson eigenvalues")
    # NOTE: The returned eigenvectors are a list of (whatever the engine used is using for a vector)
    # So in this case, we need to put the columns together into a matrix to compare directly to the np.LA.eigh result
    compare_arrays(ref_vectors, np.column_stack(test_vectors), 8,
                   "Davidson eigenvectors")
示例#4
0
def test_davidson_solver_numpy():
    BIGDIM = 100
    nroot = 3
    guess = list(np.random.randn(BIGDIM, nroot).T)
    test_engine = DSProblemSimulate(BIGDIM)
    ret = davidson_solver(
        engine=test_engine,
        guess=guess,
        nroot=nroot,
        #Don't let the ss grow to size of real thing
        max_ss_size=20,
        # Don't assault stdout with logging
        verbose=0,
        maxiter=100)

    test_vals = ret["eigvals"]
    assert test_vals is not None, "Solver Failed to converge"

    ref_vals, ref_vectors = np.linalg.eigh(test_engine.A)
    idx = ref_vals.argsort()[:nroot]
    ref_vals = ref_vals[idx]
    ref_vectors = ref_vectors[:, idx]

    compare_arrays(ref_vals, test_vals, 6, "Davidson eigenvalues")
    # NOTE: The returned eigenvectors are a list of tuples of (whatever the engine used is using for a vector)
    # So in this case, we need to put the columns together into a matrix to compare directly to the np.LA.eigh result
    test_vectors = [x[0] for x in ret["eigvecs"]]
    compare_arrays(ref_vectors, np.column_stack(test_vectors), 8,
                   "Davidson eigenvectors")
示例#5
0
def test_hamiltonian_solver_stress_eigval_sep(a_sep):
    BIGDIM = 100
    nroot = 3
    guess = list(np.random.randn(BIGDIM, nroot).T)
    test_engine = HSProblemSimulate(BIGDIM, a_sep=a_sep, b_sep=a_sep / 10)
    test_vals, test_rvecs, test_lvecs, _ = hamiltonian_solver(
        engine=test_engine,
        guess=guess,
        nroot=nroot,
        # Don't let the ss grow to size of real thing
        max_vecs_per_root=20,
        # Don't assault stdout with logging
        verbose=0,
        maxiter=1000)

    assert test_vals is not None, "The solver failed to converge"

    # compute the reference values, Use the partially reduced non-hermitian form of the problem, solve for RH-eigenvectors
    ref_H = np.dot(test_engine.A - test_engine.B,
                   test_engine.A + test_engine.B)
    ref_vals, ref_rvecs = np.linalg.eig(ref_H)
    # Associated eigenvalues are the squares of the 2N dimensional problem
    ref_vals = np.sqrt(ref_vals)
    # sort the values/vectors
    sort_idx = ref_vals.argsort()
    ref_vals = ref_vals[sort_idx]
    ref_rvecs = ref_rvecs[:, sort_idx]

    # truncate to number of roots found
    ref_vals = ref_vals[:nroot]
    ref_rvecs = ref_rvecs[:, :nroot]

    # compare values
    compare_arrays(ref_vals, test_vals, 5, "Hamiltonian Eigenvalues")
示例#6
0
def test_restricted_RPA_triplet_c1():
    "Build out the full CIS/TDA hamiltonian (A) col by col with the product engine"
    h2o = psi4.geometry("""
    O
    H 1 0.96
    H 1 0.96 2 104.5
    symmetry c1
    """)
    psi4.set_options({"scf_type": "pk", 'save_jk': True})
    e, wfn = psi4.energy("hf/cc-pvdz", molecule=h2o, return_wfn=True)
    A_ref, B_ref = build_RHF_AB_C1_triplet(wfn)
    ni, na, _, _ = A_ref.shape
    nia = ni * na
    A_ref = A_ref.reshape((nia, nia))
    B_ref = B_ref.reshape((nia, nia))
    P_ref = A_ref + B_ref
    M_ref = A_ref - B_ref
    # Build engine
    eng = TDRSCFEngine(wfn, ptype='rpa', triplet=True)
    # our "guess"" vectors
    ID = [
        psi4.core.Matrix.from_array(v.reshape((ni, na)))
        for v in tuple(np.eye(nia).T)
    ]
    Px, Mx = eng.compute_products(ID)[:-1]
    P_test = np.column_stack([x.to_array().flatten() for x in Px])
    assert compare_arrays(P_ref, P_test, 8, "RHF (A+B)x C1 products")
    M_test = np.column_stack([x.to_array().flatten() for x in Mx])
    assert compare_arrays(M_ref, M_test, 8, "RHF (A-B)x C1 products")
示例#7
0
def test_davidson_solver_numpy():
    BIGDIM = 100
    nroot = 3
    guess = list(np.random.randn(BIGDIM, nroot).T)
    test_engine = DSProblemSimulate(BIGDIM)
    test_vals, test_vectors, _ = davidson_solver(
        engine=test_engine,
        guess=guess,
        nroot=nroot,
        #Don't let the ss grow to size of real thing
        max_vecs_per_root=20,
        # Don't assault stdout with logging
        verbose=0,
        maxiter=100)

    assert test_vals is not None, "Solver Failed to converge"

    ref_vals, ref_vectors = np.linalg.eigh(test_engine.A)
    idx = ref_vals.argsort()[:nroot]
    ref_vals = ref_vals[idx]
    ref_vectors = ref_vectors[:, idx]

    compare_arrays(ref_vals, test_vals, 6, "Davidson eigenvalues")
    # NOTE: The returned eigenvectors are a list of (whatever the engine used is using for a vector)
    # So in this case, we need to put the columns together into a matrix to compare directly to the np.LA.eigh result
    compare_arrays(ref_vectors, np.column_stack(test_vectors), 8, "Davidson eigenvectors")
示例#8
0
def test_RU_TDA_C1():
    h2o = psi4.geometry("""0 1
    O          0.000000    0.000000    0.135446
    H         -0.000000    0.866812   -0.541782
    H         -0.000000   -0.866812   -0.541782
    symmetry c1
    no_reorient
    no_com
    """)
    psi4.set_options({"scf_type": "pk", 'save_jk': True})
    e, wfn = psi4.energy("hf/sto-3g", molecule=h2o, return_wfn=True)
    A_ref, _ = build_UHF_AB_C1(wfn)
    ni, na, _, _ = A_ref['IAJB'].shape
    nia = ni * na
    A_sing_ref = A_ref['IAJB'] + A_ref['IAjb']
    A_sing_ref = A_sing_ref.reshape(nia, nia)
    A_trip_ref = A_ref['IAJB'] - A_ref['IAjb']
    A_trip_ref = A_trip_ref.reshape(nia, nia)
    sing_vals, _ = np.linalg.eigh(A_sing_ref)
    trip_vals, _ = np.linalg.eigh(A_trip_ref)

    trip_eng = TDRSCFEngine(wfn, ptype='tda', triplet=True)
    sing_eng = TDRSCFEngine(wfn, ptype='tda', triplet=False)
    ID = [
        psi4.core.Matrix.from_array(v.reshape((ni, na)))
        for v in tuple(np.eye(nia).T)
    ]
    psi4.core.print_out("\nA sing:\n" + str(A_sing_ref) + "\n\n")
    psi4.core.print_out("\nA trip:\n" + str(A_trip_ref) + "\n\n")
    A_trip_test = np.column_stack(
        [x.to_array().flatten() for x in trip_eng.compute_products(ID)[0]])
    assert compare_arrays(A_trip_ref, A_trip_test, 8, "Triplet Ax C1 products")
    A_sing_test = np.column_stack(
        [x.to_array().flatten() for x in sing_eng.compute_products(ID)[0]])
    assert compare_arrays(A_sing_ref, A_sing_test, 8, "Singlet Ax C1 products")

    sing_vals_2, _ = np.linalg.eigh(A_sing_test)
    trip_vals_2, _ = np.linalg.eigh(A_trip_test)

    psi4.core.print_out("\n\n SINGLET EIGENVALUES\n")
    for x, y in zip(sing_vals, sing_vals_2):
        psi4.core.print_out("{:10.6f}  {:10.6f}\n".format(x, y))
        # assert compare_values(x, y, 4, "Singlet ROOT")
    psi4.core.print_out("\n\n Triplet EIGENVALUES\n")
    for x, y in zip(trip_vals, trip_vals_2):
        psi4.core.print_out("{:10.6f}  {:10.6f}\n".format(x, y))
        # assert compare_values(x, y, 4, "Triplet Root")

    for x, y in zip(sing_vals, sing_vals_2):
        assert compare_values(x, y, 4, "Singlet ROOT")
    for x, y in zip(trip_vals, trip_vals_2):
        assert compare_values(x, y, 4, "Triplet Root")
示例#9
0
def test_unrestricted_TDA_C1():
    ch2 = psi4.geometry("""
    0 3
    c
    h 1 1.0
    h 1 1.0 2 125.0
    symmetry c1
    """)
    psi4.set_options({"scf_type": "pk", 'reference': 'UHF', 'save_jk': True})
    e, wfn = psi4.energy("hf/cc-pvdz", molecule=ch2, return_wfn=True)
    A_ref, B_ref = build_UHF_AB_C1(wfn)
    nI, nA, _, _ = A_ref['IAJB'].shape
    nIA = nI * nA
    ni, na, _, _ = A_ref['iajb'].shape
    nia = ni * na

    eng = TDUSCFEngine(wfn, ptype='tda')
    X_jb = [
        psi4.core.Matrix.from_array(v.reshape((ni, na)))
        for v in tuple(np.eye(nia).T)
    ]
    zero_jb = [psi4.core.Matrix(ni, na) for x in range(nIA)]
    X_JB = [
        psi4.core.Matrix.from_array(v.reshape((nI, nA)))
        for v in tuple(np.eye(nIA).T)
    ]
    zero_JB = [psi4.core.Matrix(nI, nA) for x in range(nia)]
    # Guess Identity:
    #     X_I0          X_0I          =      X_I0      X_0I
    # [ I{nOV x nOV} | 0{nOV x nov}]  = [ X{KC,JB} | 0{KC, jb}]
    # [ 0{nov x nOV} | I{nov x nov}]    [ 0{kc,JB} | X{kc, jb}]

    # Products:
    # [ A{IA, KC}  A{IA, kc}] [ I{KC, JB} |  0{KC,jb}] = [A x X_I0] = [ A_IAJB, A_iaJB]
    # [ A{ia, KC}  A{ia, kc}] [ O{kc, JB} |  X{kc,jb}]   [A x X_0I] = [ A_IAjb, A_iajb]
    X_I0 = [[x, zero] for x, zero in zip(X_JB, zero_jb)]
    X_0I = [[zero, x] for zero, x in zip(zero_JB, X_jb)]
    Ax_I0 = eng.compute_products(X_I0)[0]
    Ax_0I = eng.compute_products(X_0I)[0]
    A_IAJB_test = np.column_stack([x[0].to_array().flatten() for x in Ax_I0])
    assert compare_arrays(A_ref['IAJB'].reshape(nIA, nIA), A_IAJB_test, 8,
                          "A_IAJB")
    A_iaJB_test = np.column_stack([x[1].to_array().flatten() for x in Ax_I0])
    assert compare_arrays(A_ref['iaJB'].reshape(nia, nIA), A_iaJB_test, 8,
                          "A_iaJB")
    A_IAjb_test = np.column_stack([x[0].to_array().flatten() for x in Ax_0I])
    assert compare_arrays(A_ref['IAjb'].reshape(nIA, nia), A_IAjb_test, 8,
                          "A_IAjb")
    A_iajb_test = np.column_stack([x[1].to_array().flatten() for x in Ax_0I])
    assert compare_arrays(A_ref['iajb'].reshape(nia, nia), A_iajb_test, 8,
                          "A_iajb")
示例#10
0
def test_unrestricted_RPA_C1():
    ch2 = psi4.geometry("""
    0 3
    c
    h 1 1.0
    h 1 1.0 2 125.0
    symmetry c1
    """)
    psi4.set_options({"scf_type": "pk", 'reference': 'UHF', 'save_jk': True})
    e, wfn = psi4.energy("hf/cc-pvdz", molecule=ch2, return_wfn=True)
    A_ref, B_ref = build_UHF_AB_C1(wfn)
    nI, nA, _, _ = A_ref['IAJB'].shape
    nIA = nI * nA
    ni, na, _, _ = A_ref['iajb'].shape
    nia = ni * na

    P_ref = {k: A_ref[k] + B_ref[k] for k in A_ref.keys()}
    M_ref = {k: A_ref[k] - B_ref[k] for k in A_ref.keys()}

    eng = TDUSCFEngine(wfn, ptype='rpa')
    X_jb = [psi4.core.Matrix.from_array(v.reshape((ni, na))) for v in tuple(np.eye(nia).T)]
    zero_jb = [psi4.core.Matrix(ni, na) for x in range(nIA)]
    X_JB = [psi4.core.Matrix.from_array(v.reshape((nI, nA))) for v in tuple(np.eye(nIA).T)]
    zero_JB = [psi4.core.Matrix(nI, nA) for x in range(nia)]
    # Guess Identity:
    #     X_I0          X_0I          =      X_I0      X_0I
    # [ I{nOV x nOV} | 0{nOV x nov}]  = [ X{KC,JB} | 0{KC, jb}]
    # [ 0{nov x nOV} | I{nov x nov}]    [ 0{kc,JB} | X{kc, jb}]

    # Products:
    # [ A+/-B{IA, KC}  A+/-B{IA, kc}] [ I{KC, JB} |  0{KC,jb}] = [A+/-B x X_I0] = [ (A+/-B)_IAJB, (A+/-B)_iaJB]
    # [ A+/-B{ia, KC}  A+/-B{ia, kc}] [ O{kc, JB} |  X{kc,jb}]   [A+/-B x X_0I] = [ (A+/-B)_IAjb, (A+/-B)_iajb]
    X_I0 = [[x, zero] for x, zero in zip(X_JB, zero_jb)]
    X_0I = [[zero, x] for zero, x in zip(zero_JB, X_jb)]
    Px_I0, Mx_I0 = eng.compute_products(X_I0)[:-1]
    Px_0I, Mx_0I = eng.compute_products(X_0I)[:-1]

    P_IAJB_test = np.column_stack([x[0].to_array().flatten() for x in Px_I0])
    assert compare_arrays(P_ref['IAJB'].reshape(nIA, nIA), P_IAJB_test, 8, "A_IAJB")

    M_IAJB_test = np.column_stack([x[0].to_array().flatten() for x in Mx_I0])
    assert compare_arrays(M_ref['IAJB'].reshape(nIA, nIA), M_IAJB_test, 8, "A_IAJB")

    P_iaJB_test = np.column_stack([x[1].to_array().flatten() for x in Px_I0])
    assert compare_arrays(P_ref['iaJB'].reshape(nia, nIA), P_iaJB_test, 8, "P_iaJB")

    M_iaJB_test = np.column_stack([x[1].to_array().flatten() for x in Mx_I0])
    assert compare_arrays(M_ref['iaJB'].reshape(nia, nIA), M_iaJB_test, 8, "M_iaJB")

    P_IAjb_test = np.column_stack([x[0].to_array().flatten() for x in Px_0I])
    assert compare_arrays(P_ref['IAjb'].reshape(nIA, nia), P_IAjb_test, 8, "P_IAjb")

    M_IAjb_test = np.column_stack([x[0].to_array().flatten() for x in Mx_0I])
    assert compare_arrays(M_ref['IAjb'].reshape(nIA, nia), M_IAjb_test, 8, "M_IAjb")

    P_iajb_test = np.column_stack([x[1].to_array().flatten() for x in Px_0I])
    assert compare_arrays(P_ref['iajb'].reshape(nia, nia), P_iajb_test, 8, "P_iajb")

    M_iajb_test = np.column_stack([x[1].to_array().flatten() for x in Mx_0I])
    assert compare_arrays(M_ref['iajb'].reshape(nia, nia), M_iajb_test, 8, "M_iajb")
示例#11
0
def run_selection_sort():
    rand_arr = utils.generate_random_array(100)
    copy = list(rand_arr)

    rand_arr.sort()
    approx_iterations = selection_sort(copy)
    assert_true(utils.compare_arrays(rand_arr, copy), True, 'Selection Sort')
示例#12
0
def test_restricted_TDA_singlet_df():
    "Build out the full CIS/TDA hamiltonian (A) col by col with the product engine"
    h2o = psi4.geometry("""
    O
    H 1 0.96
    H 1 0.96 2 104.5
    """)
    psi4.set_options({"scf_type": "df", 'save_jk': True})
    e, wfn = psi4.energy("hf/cc-pvdz", molecule=h2o, return_wfn=True)
    A_blocks, B_blocks = build_RHF_AB_singlet_df(wfn)
    eng = TDRSCFEngine(wfn, ptype='tda', triplet=False)
    vir_dim = wfn.nmopi() - wfn.doccpi()
    for hia, A_block in enumerate(A_blocks):
        ID = []
        # Construct a matrix for each (O, V) pair with hia symmetry.
        for hi in range(wfn.nirrep()):
            for i in range(wfn.Ca_subset("SO", "OCC").coldim()[hi]):
                for a in range(wfn.Ca_subset("SO", "VIR").coldim()[hi ^ hia]):
                    matrix = psi4.core.Matrix("Test Matrix", wfn.doccpi(),
                                              vir_dim, hia)
                    matrix.set(hi, i, a, 1)
                    ID.append(matrix)
        x = eng.compute_products(ID)[0][0]
        # Assemble the A values as a single (ia, jb) matrix, all possible ia and jb of symmetry hia.
        A_test = np.column_stack([
            np.concatenate([y.flatten() for y in x.to_array()])
            for x in eng.compute_products(ID)[0]
        ])
        assert compare_arrays(A_block, A_test, 8, "DF-RHF Ax C2v products")
示例#13
0
def run_insertion_sort():
    rand_arr = utils.generate_random_array(101)
    rand_copy = list(rand_arr)
    rand_arr.sort()
    insertion_sort(rand_copy)
    assert_true(utils.compare_arrays(rand_arr, rand_copy), True,
                'Insertion Sort')
示例#14
0
def run_selection_sort():
    rand_arr = utils.generate_random_array(100)
    copy = list(rand_arr)

    rand_arr.sort()
    approx_iterations = selection_sort(copy)
    assert_true(utils.compare_arrays(rand_arr, copy), True, 'Selection Sort')
示例#15
0
def test_RU_TDA_C1():
    h2o = psi4.geometry("""0 1
    O          0.000000    0.000000    0.135446
    H         -0.000000    0.866812   -0.541782
    H         -0.000000   -0.866812   -0.541782
    symmetry c1
    no_reorient
    no_com
    """)
    psi4.set_options({"scf_type": "pk", 'save_jk': True})
    e, wfn = psi4.energy("hf/sto-3g", molecule=h2o, return_wfn=True)
    A_ref, _ = build_UHF_AB_C1(wfn)
    ni, na, _, _ = A_ref['IAJB'].shape
    nia = ni * na
    A_sing_ref = A_ref['IAJB'] + A_ref['IAjb']
    A_sing_ref = A_sing_ref.reshape(nia, nia)
    A_trip_ref = A_ref['IAJB'] - A_ref['IAjb']
    A_trip_ref = A_trip_ref.reshape(nia, nia)
    sing_vals, _ = np.linalg.eigh(A_sing_ref)
    trip_vals, _ = np.linalg.eigh(A_trip_ref)

    trip_eng = TDRSCFEngine(wfn, ptype='tda', triplet=True)
    sing_eng = TDRSCFEngine(wfn, ptype='tda', triplet=False)
    ID = [psi4.core.Matrix.from_array(v.reshape((ni, na))) for v in tuple(np.eye(nia).T)]
    psi4.core.print_out("\nA sing:\n" + str(A_sing_ref) + "\n\n")
    psi4.core.print_out("\nA trip:\n" + str(A_trip_ref) + "\n\n")
    A_trip_test = np.column_stack([x.to_array().flatten() for x in trip_eng.compute_products(ID)[0]])
    assert compare_arrays(A_trip_ref, A_trip_test, 8, "Triplet Ax C1 products")
    A_sing_test = np.column_stack([x.to_array().flatten() for x in sing_eng.compute_products(ID)[0]])
    assert compare_arrays(A_sing_ref, A_sing_test, 8, "Singlet Ax C1 products")

    sing_vals_2, _ = np.linalg.eigh(A_sing_test)
    trip_vals_2, _ = np.linalg.eigh(A_trip_test)

    psi4.core.print_out("\n\n SINGLET EIGENVALUES\n")
    for x, y in zip(sing_vals, sing_vals_2):
        psi4.core.print_out("{:10.6f}  {:10.6f}\n".format(x, y))
        # assert compare_values(x, y, 4, "Singlet ROOT")
    psi4.core.print_out("\n\n Triplet EIGENVALUES\n")
    for x, y in zip(trip_vals, trip_vals_2):
        psi4.core.print_out("{:10.6f}  {:10.6f}\n".format(x, y))
        # assert compare_values(x, y, 4, "Triplet Root")

    for x, y in zip(sing_vals, sing_vals_2):
        assert compare_values(x, y, 4, "Singlet ROOT")
    for x, y in zip(trip_vals, trip_vals_2):
        assert compare_values(x, y, 4, "Triplet Root")
示例#16
0
def test_doublets(adl, adr, Ga, bdl, bdr, Gb, at, bt):
    a = build_random_mat(adl, adr, Ga)
    b = build_random_mat(bdl, bdr, Gb)
    res = doublet(a, b, at, bt)
    expected = generate_result(a, b, at, bt)
    assert res.symmetry() == a.symmetry() ^ b.symmetry(), "Symm mismatch {} x {} != {}".format(
        a.symmetry(), b.symemtry(), res.symmetry())
    res_blocks = res.to_array()
    if isinstance(res_blocks, np.ndarray):
        res_blocks = [res_blocks]
    block_checks = []
    for blk_idx in range(res.nirrep()):
        assert compare_arrays(expected[blk_idx], res_blocks[blk_idx], 8, "Block[{}]".format(blk_idx))
示例#17
0
def test_doublets(adl, adr, Ga, bdl, bdr, Gb, at, bt):
    a = build_random_mat(adl, adr, Ga)
    b = build_random_mat(bdl, bdr, Gb)
    res = doublet(a, b, at, bt)
    expected = generate_result(a, b, at, bt)
    assert res.symmetry() == a.symmetry() ^ b.symmetry(
    ), f"Symm mismatch {a.symmetry()} x {b.symmetry()} != {res.symmetry()}"
    res_blocks = res.to_array()
    if isinstance(res_blocks, np.ndarray):
        res_blocks = [res_blocks]
    block_checks = []
    for blk_idx in range(res.nirrep()):
        assert compare_arrays(expected[blk_idx], res_blocks[blk_idx], 8,
                              f"Block[{blk_idx}]")
示例#18
0
def test_hamiltonian_solver():
    BIGDIM = 100
    nroot = 3
    guess = list(np.eye(BIGDIM)[:, :nroot * 2].T)
    test_engine = HSProblemSimulate(BIGDIM)
    ret = hamiltonian_solver(
        engine=test_engine,
        guess=guess,
        nroot=nroot,
        # Don't let the ss grow to size of real thing
        max_ss_size=20,
        # Don't assault stdout with logging
        verbose=0,
        maxiter=100)

    test_vals = ret["eigvals"]
    assert test_vals is not None, "The solver failed to converge"

    # compute the reference values, Use the partially reduced non-hermitian form of the problem, solve for RH-eigenvectors
    ref_H = np.dot(test_engine.A - test_engine.B,
                   test_engine.A + test_engine.B)
    ref_vals, ref_rvecs = np.linalg.eig(ref_H)
    # Associated eigenvalues are the squares of the 2N dimensional problem
    ref_vals = np.sqrt(ref_vals)
    # sort the values/vectors
    sort_idx = ref_vals.argsort()
    ref_vals = ref_vals[sort_idx]
    ref_rvecs = ref_rvecs[:, sort_idx]

    # truncate to number of roots found
    ref_vals = ref_vals[:nroot]
    ref_rvecs = ref_rvecs[:, :nroot]

    # compare values
    compare_arrays(ref_vals, test_vals, 5, "Hamiltonian Eigenvalues")

    # compare roots
    # NOTE: The returned eigenvectors are a list of (whatever the engine used is using for a vector)
    # So in this case, we need to put the columns together into a matrix to compare directly to the np.LA.eig result
    test_rvecs = [x[0] for x in ret["eigvecs"]]
    compare_arrays(ref_rvecs, np.column_stack(test_rvecs), 6,
                   "Hamiltonian Right Eigenvectors")

    #Can't compute LH eigenvectors with numpy but we have the RH, and the matrix
    # solver computed Vl^T * H
    test_lvecs = [x[1] for x in ret["eigvecs"]]
    vl_T_H = np.column_stack(
        [np.dot(test_lvecs[i], ref_H) for i in range(nroot)])
    # value * right_vector (should not matter which one since we just checked them equal)
    w_Vr = np.column_stack(
        [test_rvecs[i] * test_vals[i] for i in range(nroot)])
    #compare
    compare_arrays(vl_T_H, w_Vr, 6, "Hamiltonian Left Eigenvectors")
示例#19
0
def test_hamiltonian_solver():
    BIGDIM = 100
    nroot = 3
    guess = list(np.eye(BIGDIM)[:, :nroot * 2].T)
    test_engine = HSProblemSimulate(BIGDIM)
    test_vals, test_rvecs, test_lvecs, _ = hamiltonian_solver(
        engine=test_engine,
        guess=guess,
        nroot=nroot,
        # Don't let the ss grow to size of real thing
        max_vecs_per_root=20,
        # Don't assault stdout with logging
        verbose=0,
        maxiter=100)

    assert test_vals is not None, "The solver failed to converge"

    # compute the reference values, Use the partially reduced non-hermitian form of the problem, solve for RH-eigenvectors
    ref_H = np.dot(test_engine.A - test_engine.B, test_engine.A + test_engine.B)
    ref_vals, ref_rvecs = np.linalg.eig(ref_H)
    # Associated eigenvalues are the squares of the 2N dimensional problem
    ref_vals = np.sqrt(ref_vals)
    # sort the values/vectors
    sort_idx = ref_vals.argsort()
    ref_vals = ref_vals[sort_idx]
    ref_rvecs = ref_rvecs[:, sort_idx]

    # truncate to number of roots found
    ref_vals = ref_vals[:nroot]
    ref_rvecs = ref_rvecs[:, :nroot]

    # compare values
    compare_arrays(ref_vals, test_vals, 5, "Hamiltonian Eigenvalues")

    # compare roots
    # NOTE: The returned eigenvectors are a list of (whatever the engine used is using for a vector)
    # So in this case, we need to put the columns together into a matrix to compare directly to the np.LA.eig result
    compare_arrays(ref_rvecs, np.column_stack(test_rvecs), 6, "Hamiltonian Right Eigenvectors")

    #Can't compute LH eigenvectors with numpy but we have the RH, and the matrix
    # solver computed Vl^T * H
    vl_T_H = np.column_stack([np.dot(test_lvecs[i], ref_H) for i in range(nroot)])
    # value * right_vector (should not matter which one since we just checked them equal)
    w_Vr = np.column_stack([test_rvecs[i] * test_vals[i] for i in range(nroot)])
    #compare
    compare_arrays(vl_T_H, w_Vr, 6, "Hamiltonian Left Eigenvectors")
示例#20
0
def test_restricted_TDA_singlet_df_c1():
    "Build out the full CIS/TDA hamiltonian (A) col by col with the product engine"
    h2o = psi4.geometry("""
    O
    H 1 0.96
    H 1 0.96 2 104.5
    symmetry c1
    """)
    psi4.set_options({"scf_type": "df", 'save_jk': True})
    e, wfn = psi4.energy("hf/cc-pvdz", molecule=h2o, return_wfn=True)
    A_ref, _ = build_RHF_AB_C1_singlet_df(wfn)
    ni, na, _, _ = A_ref.shape
    nia = ni * na
    A_ref = A_ref.reshape((nia, nia))
    # Build engine
    eng = TDRSCFEngine(wfn, ptype='tda', triplet=False)
    # our "guess"" vectors
    ID = [
        psi4.core.Matrix.from_array(v.reshape((ni, na)))
        for v in tuple(np.eye(nia).T)
    ]
    A_test = np.column_stack(
        [x.to_array().flatten() for x in eng.compute_products(ID)[0]])
    assert compare_arrays(A_ref, A_test, 8, "DF-RHF Ax C1 products")
示例#21
0
def run_insertion_sort():
    rand_arr = utils.generate_random_array(101)
    rand_copy = list(rand_arr)
    rand_arr.sort()
    insertion_sort(rand_copy)
    assert_true(utils.compare_arrays(rand_arr, rand_copy), True, 'Insertion Sort')
示例#22
0
def run_merge_sort():
    rand_arr = utils.generate_random_array(100)
    rand_copy = list(rand_arr)
    rand_arr.sort()
    merge_sort(rand_copy)
    assert_true(utils.compare_arrays(rand_arr, rand_copy), True, 'Merge Sort')
示例#23
0
def run_merge_sort():
    rand_arr = utils.generate_random_array(100)
    rand_copy = list(rand_arr)
    rand_arr.sort()
    merge_sort(rand_copy)
    assert_true(utils.compare_arrays(rand_arr, rand_copy), True, 'Merge Sort')
示例#24
0
    def run_bend_flux(self, from_gdsii_file):
        # Normalization run
        self.init(no_bend=True, gdsii=from_gdsii_file)
        self.sim.run(until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, self.pt, 1e-3))
        # Save flux data for use in real run below
        fdata = self.sim.get_flux_data(self.refl)

        expected = [
            (0.1, 3.65231563251e-05, 3.68932495077e-05),
            (0.10101010101, 5.55606718876e-05, 5.6065539588e-05),
            (0.10202020202, 8.38211697478e-05, 8.44909864736e-05),
            (0.10303030303, 0.000125411162229, 0.000126268639045),
            (0.10404040404, 0.000186089117531, 0.000187135303398),
            (0.105050505051, 0.000273848867869, 0.000275039134667),
            (0.106060606061, 0.000399674037745, 0.000400880269423),
            (0.107070707071, 0.00057849953593, 0.000579454087881),
            (0.108080808081, 0.000830418432986, 0.000830635406881),
            (0.109090909091, 0.00118217282661, 0.00118084271347),
            (0.110101010101, 0.00166896468348, 0.00166481944189),
            (0.111111111111, 0.00233661613864, 0.00232776318321),
            (0.112121212121, 0.00324409729096, 0.00322782257917),
            (0.113131313131, 0.00446642217385, 0.00443896468822),
            (0.114141414141, 0.0060978895019, 0.0060541922825),
            (0.115151515152, 0.00825561352398, 0.00818906047274),
            (0.116161616162, 0.0110832518495, 0.010985404883),
            (0.117171717172, 0.0147547920552, 0.0146151488236),
            (0.118181818182, 0.0194782085272, 0.0192840042241),
            (0.119191919192, 0.0254987474079, 0.0252348211592),
        ]

        res = list(zip(mp.get_flux_freqs(self.trans), mp.get_fluxes(self.trans), mp.get_fluxes(self.refl)))

        tolerance = 1e-2 if from_gdsii_file else 1e-3
        compare_arrays(self, np.array(expected), np.array(res[:20]), tol=tolerance)

        # Real run
        self.sim = None
        self.init(gdsii=from_gdsii_file)
        # Load flux data obtained from normalization run
        self.sim.load_minus_flux_data(self.refl, fdata)
        self.sim.run(until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, self.pt, 1e-3))

        expected = [
            (0.09999999999999999, 1.8392235204829767e-5, -7.259467687598002e-6),
            (0.10101010101010101, 2.7629932558236724e-5, -1.1107162110079347e-5),
            (0.10202020202020202, 4.1001228946782745e-5, -1.687561915798036e-5),
            (0.10303030303030304, 6.018966076122556e-5, -2.5425779493709066e-5),
            (0.10404040404040406, 8.758554071933231e-5, -3.794958119189475e-5),
            (0.10505050505050507, 1.2656696778129198e-4, -5.612512808928115e-5),
            (0.10606060606060609, 1.817948859871414e-4, -8.232188174309142e-5),
            (0.10707070707070711, 2.594514094902856e-4, -1.1981531280672989e-4),
            (0.10808080808080812, 3.6736164837695035e-4, -1.7300125173897737e-4),
            (0.10909090909090914, 5.150131339048232e-4, -2.476730940385436e-4),
            (0.11010101010101016, 7.136181099374187e-4, -3.5145561406042276e-4),
            (0.11111111111111117, 9.76491765781944e-4, -4.944142331545938e-4),
            (0.11212121212121219, 0.001320033637882244, -6.897357105189368e-4),
            (0.11313131313131321, 0.0017653940714397098, -9.543556354451615e-4),
            (0.11414141414141422, 0.0023404727796352857, -0.0013095604571818236),
            (0.11515151515151524, 0.0030813962415392098, -0.00178176942635486),
            (0.11616161616161626, 0.00403238648982478, -0.0024036650652026112),
            (0.11717171717171727, 0.005243320443599316, -0.003215529845495731),
            (0.11818181818181829, 0.0067654019326068, -0.004266367104375331),
            (0.11919191919191931, 0.008646855439680507, -0.005614491919262783),

        ]

        res = list(zip(mp.get_flux_freqs(self.trans), mp.get_fluxes(self.trans), mp.get_fluxes(self.refl)))

        tolerance = 1e-2 if from_gdsii_file else 1e-3
        compare_arrays(self, np.array(expected), np.array(res[:20]), tol=tolerance)
示例#25
0
文件: bend_flux.py 项目: oskooi/meep
    def run_bend_flux(self, from_gdsii_file):
        # Normalization run
        self.init(no_bend=True, gdsii=from_gdsii_file)
        self.sim.run(until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, self.pt, 1e-3))
        # Save flux data for use in real run below
        fdata = self.sim.get_flux_data(self.refl)

        expected = [
            (0.1, 3.65231563251e-05, 3.68932495077e-05),
            (0.10101010101, 5.55606718876e-05, 5.6065539588e-05),
            (0.10202020202, 8.38211697478e-05, 8.44909864736e-05),
            (0.10303030303, 0.000125411162229, 0.000126268639045),
            (0.10404040404, 0.000186089117531, 0.000187135303398),
            (0.105050505051, 0.000273848867869, 0.000275039134667),
            (0.106060606061, 0.000399674037745, 0.000400880269423),
            (0.107070707071, 0.00057849953593, 0.000579454087881),
            (0.108080808081, 0.000830418432986, 0.000830635406881),
            (0.109090909091, 0.00118217282661, 0.00118084271347),
            (0.110101010101, 0.00166896468348, 0.00166481944189),
            (0.111111111111, 0.00233661613864, 0.00232776318321),
            (0.112121212121, 0.00324409729096, 0.00322782257917),
            (0.113131313131, 0.00446642217385, 0.00443896468822),
            (0.114141414141, 0.0060978895019, 0.0060541922825),
            (0.115151515152, 0.00825561352398, 0.00818906047274),
            (0.116161616162, 0.0110832518495, 0.010985404883),
            (0.117171717172, 0.0147547920552, 0.0146151488236),
            (0.118181818182, 0.0194782085272, 0.0192840042241),
            (0.119191919192, 0.0254987474079, 0.0252348211592),
        ]

        res = list(zip(mp.get_flux_freqs(self.trans), mp.get_fluxes(self.trans), mp.get_fluxes(self.refl)))

        tolerance = 1e-2 if from_gdsii_file else 1e-3
        compare_arrays(self, np.array(expected), np.array(res[:20]), tol=tolerance)

        # Real run
        self.sim = None
        self.init(gdsii=from_gdsii_file)
        # Load flux data obtained from normalization run
        self.sim.load_minus_flux_data(self.refl, fdata)
        self.sim.run(until_after_sources=mp.stop_when_fields_decayed(50, mp.Ez, self.pt, 1e-3))

        expected = [
            (0.09999999999999999, 1.8392235204829767e-5, -7.259467687598002e-6),
            (0.10101010101010101, 2.7629932558236724e-5, -1.1107162110079347e-5),
            (0.10202020202020202, 4.1001228946782745e-5, -1.687561915798036e-5),
            (0.10303030303030304, 6.018966076122556e-5, -2.5425779493709066e-5),
            (0.10404040404040406, 8.758554071933231e-5, -3.794958119189475e-5),
            (0.10505050505050507, 1.2656696778129198e-4, -5.612512808928115e-5),
            (0.10606060606060609, 1.817948859871414e-4, -8.232188174309142e-5),
            (0.10707070707070711, 2.594514094902856e-4, -1.1981531280672989e-4),
            (0.10808080808080812, 3.6736164837695035e-4, -1.7300125173897737e-4),
            (0.10909090909090914, 5.150131339048232e-4, -2.476730940385436e-4),
            (0.11010101010101016, 7.136181099374187e-4, -3.5145561406042276e-4),
            (0.11111111111111117, 9.76491765781944e-4, -4.944142331545938e-4),
            (0.11212121212121219, 0.001320033637882244, -6.897357105189368e-4),
            (0.11313131313131321, 0.0017653940714397098, -9.543556354451615e-4),
            (0.11414141414141422, 0.0023404727796352857, -0.0013095604571818236),
            (0.11515151515151524, 0.0030813962415392098, -0.00178176942635486),
            (0.11616161616161626, 0.00403238648982478, -0.0024036650652026112),
            (0.11717171717171727, 0.005243320443599316, -0.003215529845495731),
            (0.11818181818181829, 0.0067654019326068, -0.004266367104375331),
            (0.11919191919191931, 0.008646855439680507, -0.005614491919262783),

        ]

        res = list(zip(mp.get_flux_freqs(self.trans), mp.get_fluxes(self.trans), mp.get_fluxes(self.refl)))

        tolerance = 1e-2 if from_gdsii_file else 1e-3
        compare_arrays(self, np.array(expected), np.array(res[:20]), tol=tolerance)