Пример #1
0
    close(fig)


    fig = figure()
    ax = fig.gca()

    ax.semilogy(timegridk, data, label=r"$|E_O^0 - \left( E_k^0 + E_p^0 \right) |$")
    ax.grid(True)
    ax.set_xlabel(r"Time $t$")
    ax.set_ylabel(r"$|E_O^0 - \left( E_k^0 + E_p^0 \right) |$")
    ax.set_title(r"Energy drift of the wavepacket $\Psi$")

    fig.savefig("energy_drift_block"+str(index)+"_log"+GD.output_format)
    close(fig)




if __name__ == "__main__":
    iom = IOManager()

    # Read file with simulation data
    try:
        iom.open_file(filename=sys.argv[1])
    except IndexError:
        iom.open_file()

    read_all_datablocks(iom)

    iom.finalize()
Пример #2
0
        for level in xrange(N):
            z = Psi[level]

            subplot(N, 1, level + 1)
            plotcm(z, darken=0.3)

        savefig("wavefunction_level_" + str(level) + "_timestep_" +
                (5 - len(str(step))) * "0" + str(step) + ".png")
        close(fig)

    print(" Plotting frames finished")


if __name__ == "__main__":
    iom = IOManager()

    # Read file with simulation data
    try:
        iom.open_file(filename=sys.argv[1])
    except IndexError:
        iom.open_file()

    # The axes rectangle that is plotted
    #view = [-3.5, 3.5, -0.1, 3.5]

    # Iterate over all blocks and plot their data
    for blockid in iom.get_block_ids():
        print("Plotting frames of data block '" + str(blockid) + "'")
        # See if we have wavefunction values
        if iom.has_wavefunction(blockid=blockid):
Пример #3
0
                        nargs=2,
                        default=[None, None])

    args = parser.parse_args()

    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(
            args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # The axes rectangle that is plotted
    view = args.trange + args.vrange

    # Iterate over all blocks
    for blockid in blockids:
        print("Plotting autocorrelations in data block '{}'".format(blockid))

        if iom.has_autocorrelation(blockid=blockid):
Пример #4
0
Compute the eigen transformation of some simulation results.

@author: R. Bourquin
@copyright: Copyright (C) 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import IOManager
from WaveBlocksND import GlobalDefaults as GD


if __name__ == "__main__":

    iomc = IOManager()
    iome = IOManager()

    # Read file with simulation data
    try:
        filename = sys.argv[1]
    except IndexError:
        filename = GD.file_resultdatafile

    iomc.open_file(filename=filename)

    # New file for eigen transformed data
    P = iomc.load_parameters()
    iome.create_file(P, filename=filename[:-5]+"_eigen.hdf5")

    # Iterate over all groups
#                     type = str,
#                     default = "all")

args = parser.parse_args()


# File with the simulation data
resultspath = os.path.abspath(args.resultspath)

if not os.path.exists(resultspath):
    raise IOError("The results path does not exist: {}".format(args.resultspath))

datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

# Read file with simulation data
iom = IOManager()
iom.open_file(filename=datafile)

# Which blocks to handle
blockids = iom.get_block_ids()
if "all" not in args.blockid:
    blockids = [bid for bid in args.blockid if bid in blockids]

# Do we have a specifc configuration file holding
# the definitions for inner products to use?
if args.parametersfile:
    parametersfile = os.path.abspath(os.path.join(args.resultspath, args.parametersfile))
    PA = ParameterLoader().load_from_file(parametersfile)
else:
    # None given, try to load from simulation file
    if iom.has_parameters():
Пример #6
0
"""The WaveBlocks Project

Compute the energies of the different wavepackets or wavefunctions.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import IOManager

if __name__ == "__main__":

    iom = IOManager()

    # Read file with simulation data
    try:
        iom.open_file(filename=sys.argv[1])
    except IndexError:
        iom.open_file()

    # Iterate over all blocks
    for blockid in iom.get_block_ids():
        print("Computing the energies in data block '" + str(blockid) + "'")

        if iom.has_energy(blockid=blockid):
            print("Datablock '" + str(blockid) +
                  "' already contains energy data, silent skip.")
            continue
Пример #7
0
        mlab.savefig("potential_zm_view.png")

        fig.scene.z_plus_view()
        mlab.savefig("potential_zp_view.png")

    if interactive is True:
        # Enable interactive plot
        mlab.show()
    else:
        mlab.close(fig)




if __name__ == "__main__":
    iom = IOManager()

    # Read file with simulation data
    try:
        iom.open_file(filename=sys.argv[1])
    except IndexError:
        iom.open_file()

    parameters = iom.load_parameters()

    # Read file with parameter data for grid
    try:
        PL = ParameterLoader()
        gridparams = PL.load_from_file(sys.argv[2])
    except IndexError:
        gridparams = parameters
Пример #8
0
inputfile = os.path.abspath(os.path.join(args.resultspath, args.inputfile))

# No output file name given
if not args.outputfile:
    outputfile = inputfile.replace(GD.ext_resultdatafile, "") + "_eigen" + GD.ext_resultdatafile
else:
    outputfile = args.outputfile

outputfile = os.path.abspath(os.path.join(args.resultspath, outputfile))

print("Reading simulation data from the file: {}".format(inputfile))
print("Writing transformed data to the file: {}".format(outputfile))

# Read file with simulation data
iomc = IOManager()
iomc.open_file(inputfile)

iome = IOManager()
iome.create_file(outputfile)

# New file for eigen transformed data
P = iomc.load_parameters()

# Save the simulation parameters
iome.add_parameters()
iome.save_parameters(P)

# Iterate over all groups
for groupid in iomc.get_group_ids():
Пример #9
0
def compute_eigenstate(parameters, filename="eigenstates.hdf5", computepq=True, computePQ=True):
    r"""
    Special variables necessary in configuration:

    * eigenstate_of_level (default: 0)
    * eigenstates_indices (default: [0])
    * starting_point (default: (2, ..., 2))
    * hawp_template
    * innerproduct
    """
    D = parameters["dimension"]

    if "eigenstate_of_level" in parameters:
        N = parameters["eigenstate_of_level"]
    else:
        # Upper-most potential surface
        N = 0

    # Create output file now, in case this fails we did not waste computation time
    IOM = IOManager()
    IOM.create_file(filename)

    # Save the simulation parameters
    IOM.add_parameters()
    IOM.save_parameters(parameters)

    gid = IOM.create_group()

    BF = BlockFactory()
    # Create the potential
    V = BF.create_potential(parameters)
    V.calculate_local_quadratic()

    # Compute position and momentum
    if computepq:
        # Minimize the potential to find q0
        f = lambda x: real((squeeze(V.evaluate_at(x)[N])))
        # Start with an offset because exact 0.0 values can give
        # issues, especially with the Hessian evaluation. This way
        # the minimizer will always stay away from zero a tiny bit.
        # The current starting point can give issues if the potential
        # is stationary at the point (2, ..., 2) but that is less likely.
        if "starting_point" in parameters:
            x0 = atleast_1d(parameters["starting_point"])
        else:
            x0 = 0.5 * ones(D)

        q0 = fmin(f, x0, xtol=1e-12)
        q0 = q0.reshape((D, 1))

        # We are at the minimum with no momentum
        p0 = zeros_like(q0)
    else:
        if "q0" in parameters:
            q0 = atleast_2d(parameters["q0"])
        else:
            q0 = zeros((D, 1))
        if "p0" in parameters:
            p0 = atleast_2d(parameters["p0"])
        else:
            p0 = zeros((D, 1))

    # Compute spreads
    if computePQ:
        # Q_0 = H^(-1/4)
        H = V.evaluate_hessian_at(q0)
        Q0 = inv(sqrtm(sqrtm(H)))
        # P_0 = i Q_0^(-1)
        P0 = 1.0j * inv(Q0)
    else:
        if "Q0" in parameters:
            Q0 = atleast_2d(parameters["Q0"])
        else:
            Q0 = identity(D)
        if "P0" in parameters:
            P0 = atleast_2d(parameters["P0"])
        else:
            P0 = 1.0j * inv(Q0)

    # The parameter set Pi
    print(70 * "-")
    print("Parameter values are:")
    print("---------------------")
    print(" q0:")
    print(str(q0))
    print(" p0:")
    print(str(p0))
    print(" Q0:")
    print(str(Q0))
    print(" P0:")
    print(str(P0))
    # Consistency check
    print(" Consistency check:")
    print("   P^T Q - Q^T P  =?=  0")
    print(dot(P0.T, Q0) - dot(Q0.T, P0))
    print("   Q^H P - P^H Q  =?=  2i")
    print(dot(transpose(conjugate(Q0)), P0) - dot(transpose(conjugate(P0)), Q0))

    # Next find the new coefficients c'
    HAWP = BF.create_wavepacket(parameters["hawp_template"])

    # Set the parameter values
    Pi = HAWP.get_parameters()
    Pi[0] = q0
    Pi[1] = p0
    Pi[2] = Q0
    Pi[3] = P0
    HAWP.set_parameters(Pi)

    # Next compute the matrix M_ij = <phi_i | T + V | phi_j>
    # The potential part
    HQ = BF.create_inner_product(parameters["innerproduct"])

    opV = lambda x, q, entry: V.evaluate_at(x, entry=entry)
    MV = HQ.build_matrix(HAWP, operator=opV)

    # The kinetic part
    MT = zeros_like(MV, dtype=complexfloating)
    GR = GradientHAWP()
    BS = HAWP.get_basis_shapes(component=N)

    vects = {}
    for i in BS:
        z = zeros_like(HAWP.get_coefficient_vector(), dtype=complexfloating)
        HAWP.set_coefficient_vector(z)
        HAWP.set_coefficient(N, i, 1.0)
        Kn, cnew = GR.apply_gradient(HAWP, component=N, as_packet=False)
        vects[i] = cnew

    for j in BS:
        for k in BS:
            cj = vects[j]
            ck = vects[k]
            entry = 0.5 * squeeze(sum(conjugate(cj) * ck))
            MT[BS[j], BS[k]] = entry

    # Find eigenvalues and eigenvectors of the whole matrix
    M = MT + MV
    ew, ev = eigh(M)
    ind = argsort(ew)

    # Build the requested energy levels and states
    if "eigenstates_indices" in parameters:
        states = parameters["eigenstates_indices"]
    else:
        # Groundstate only
        states = [0]

    BS = HAWP.get_basis_shapes(component=0)

    KEY = ("q", "p", "Q", "P", "S", "adQ")

    print(70 * "-")
    for state in states:
        if state > BS.get_basis_size():
            print("Warning: can not compute energy level {} with basis size of {}".format((state, BS)))
            continue

        index = ind[state]

        coeffs = ev[:, index]
        energy = ew[index]

        # Try to resolve ambiguities in sign
        imax = argmax(abs(coeffs))
        a = abs(angle(coeffs[imax]))
        if a > pi / 2.0:
            coeffs *= -1

        print("State: {}".format(state))
        print("Energy: {}".format(energy))
        print("Coefficients: \n")
        print(str(coeffs))
        print(70 * "-")

        HAWP.set_coefficient_vector(coeffs.reshape((-1, 1)))

        # Save all the wavepacket data
        bid = IOM.create_block(groupid=gid)
        IOM.add_wavepacket(parameters, blockid=bid, key=KEY)
        IOM.save_wavepacket(HAWP, 0, blockid=bid, key=KEY)

    IOM.finalize()

    # TODO: Find better criterion
    if norm(q0) > 1000:
        print("+----------------------------------+")
        print("| Run-away minimum?                |")
        print("| Maybe try different:             |")
        print("|   starting_point = [x0, y0, ...] |")
        print("+----------------------------------+")
Пример #10
0
#                     type = str,
#                     default = "all")

args = parser.parse_args()

# File with the simulation data
resultspath = os.path.abspath(args.resultspath)

if not os.path.exists(resultspath):
    raise IOError("The results path does not exist: {}".format(
        args.resultspath))

datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

# Read file with simulation data
iom = IOManager()
iom.open_file(filename=datafile)

# Which blocks to handle
blockids = iom.get_block_ids()
if "all" not in args.blockid:
    blockids = [bid for bid in args.blockid if bid in blockids]

# Do we have a specifc configuration file holding
# the definitions for inner products to use?
if args.parametersfile:
    parametersfile = os.path.abspath(
        os.path.join(args.resultspath, args.parametersfile))
    PA = ParameterLoader().load_from_file(parametersfile)
else:
    # None given, try to load from simulation file
Пример #11
0
                        nargs=2,
                        default=[None, None])

    args = parser.parse_args()

    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(
            args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # The axes rectangle that is plotted
    view = args.trange + args.vrange

    # Iterate over all blocks
    for blockid in blockids:
        print("Plotting norms in data block '{}'".format(blockid))

        if iom.has_norm(blockid=blockid):
Пример #12
0
                    help = "Disable transformation of data into the eigenbasis before computing norms.",
                    action = "store_false")

args = parser.parse_args()


# File with the simulation data
resultspath = os.path.abspath(args.resultspath)

if not os.path.exists(resultspath):
    raise IOError("The results path does not exist: {}".format(args.resultspath))

datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

# Read file with simulation data
iom = IOManager()
iom.open_file(filename=datafile)

# Read the additional grid parameters
if args.parametersfile:
    parametersfile = os.path.abspath(os.path.join(args.resultspath, args.parametersfile))
    PA = ParameterLoader().load_from_file(parametersfile)
else:
    PA = None

# Which blocks to handle
blockids = iom.get_block_ids()
if "all" not in args.blockid:
    blockids = [bid for bid in args.blockid if bid in blockids]

# Iterate over all blocks
Пример #13
0
                        nargs=2,
                        default=[None, None])

    args = parser.parse_args()


    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # The axes rectangle that is plotted
    view = args.trange + args.vrange

    # Iterate over all blocks
    for blockid in blockids:
        print("Plotting autocorrelations in data block '{}'".format(blockid))

        if iom.has_autocorrelation(blockid=blockid):
Пример #14
0
        mlab.savefig("potential_zm_view.png")

        fig.scene.z_plus_view()
        mlab.savefig("potential_zp_view.png")

    if interactive is True:
        # Enable interactive plot
        mlab.show()
    else:
        mlab.close(fig)




if __name__ == "__main__":
    iom = IOManager()

    # Read file with simulation data
    try:
        iom.open_file(filename=sys.argv[1])
    except IndexError:
        iom.open_file()

    parameters = iom.load_parameters()

    # Manually adjust the plotting region
    xmin = None
    xmax = None
    ymin = None
    ymax = None
    Nx = None
Пример #15
0
def compute_eigenstate(parameters,
                       filename="eigenstates.hdf5",
                       computepq=True,
                       computePQ=True):
    r"""
    Special variables necessary in configuration:

    * eigenstate_of_level (default: 0)
    * eigenstates_indices (default: [0])
    * starting_point (default: (2, ..., 2))
    * hawp_template
    * innerproduct
    """
    D = parameters["dimension"]

    if "eigenstate_of_level" in parameters:
        N = parameters["eigenstate_of_level"]
    else:
        # Upper-most potential surface
        N = 0

    # Create output file now, in case this fails we did not waste computation time
    IOM = IOManager()
    IOM.create_file(filename)

    # Save the simulation parameters
    IOM.add_parameters()
    IOM.save_parameters(parameters)

    gid = IOM.create_group()

    BF = BlockFactory()
    # Create the potential
    V = BF.create_potential(parameters)
    V.calculate_local_quadratic()

    # Compute position and momentum
    if computepq:
        # Minimize the potential to find q0
        f = lambda x: real((squeeze(V.evaluate_at(x)[N])))
        # Start with an offset because exact 0.0 values can give
        # issues, especially with the Hessian evaluation. This way
        # the minimizer will always stay away from zero a tiny bit.
        # The current starting point can give issues if the potential
        # is stationary at the point (2, ..., 2) but that is less likely.
        if "starting_point" in parameters:
            x0 = atleast_1d(parameters["starting_point"])
        else:
            x0 = 0.5 * ones(D)

        q0 = fmin(f, x0, xtol=1e-12)
        q0 = q0.reshape((D, 1))

        # We are at the minimum with no momentum
        p0 = zeros_like(q0)
    else:
        if "q0" in parameters:
            q0 = atleast_2d(parameters["q0"])
        else:
            q0 = zeros((D, 1))
        if "p0" in parameters:
            p0 = atleast_2d(parameters["p0"])
        else:
            p0 = zeros((D, 1))

    # Compute spreads
    if computePQ:
        # Q_0 = H^(-1/4)
        H = V.evaluate_hessian_at(q0)
        Q0 = inv(sqrtm(sqrtm(H)))
        # P_0 = i Q_0^(-1)
        P0 = 1.0j * inv(Q0)
    else:
        if "Q0" in parameters:
            Q0 = atleast_2d(parameters["Q0"])
        else:
            Q0 = identity(D)
        if "P0" in parameters:
            P0 = atleast_2d(parameters["P0"])
        else:
            P0 = 1.0j * inv(Q0)

    # The parameter set Pi
    print(70 * "-")
    print("Parameter values are:")
    print("---------------------")
    print(" q0:")
    print(str(q0))
    print(" p0:")
    print(str(p0))
    print(" Q0:")
    print(str(Q0))
    print(" P0:")
    print(str(P0))
    # Consistency check
    print(" Consistency check:")
    print("   P^T Q - Q^T P  =?=  0")
    print(dot(P0.T, Q0) - dot(Q0.T, P0))
    print("   Q^H P - P^H Q  =?=  2i")
    print(
        dot(transpose(conjugate(Q0)), P0) - dot(transpose(conjugate(P0)), Q0))

    # Next find the new coefficients c'
    HAWP = BF.create_wavepacket(parameters["hawp_template"])

    # Set the parameter values
    Pi = HAWP.get_parameters()
    Pi[0] = q0
    Pi[1] = p0
    Pi[2] = Q0
    Pi[3] = P0
    HAWP.set_parameters(Pi)

    # Next compute the matrix M_ij = <phi_i | T + V | phi_j>
    # The potential part
    HQ = BF.create_inner_product(parameters["innerproduct"])

    opV = lambda x, q, entry: V.evaluate_at(x, entry=entry)
    MV = HQ.build_matrix(HAWP, operator=opV)

    # The kinetic part
    MT = zeros_like(MV, dtype=complexfloating)
    GR = GradientHAWP()
    BS = HAWP.get_basis_shapes(component=N)

    vects = {}
    for i in BS:
        z = zeros_like(HAWP.get_coefficient_vector(), dtype=complexfloating)
        HAWP.set_coefficient_vector(z)
        HAWP.set_coefficient(N, i, 1.0)
        Kn, cnew = GR.apply_gradient(HAWP, component=N, as_packet=False)
        vects[i] = cnew

    for j in BS:
        for k in BS:
            cj = vects[j]
            ck = vects[k]
            entry = 0.5 * squeeze(sum(conjugate(cj) * ck))
            MT[BS[j], BS[k]] = entry

    # Find eigenvalues and eigenvectors of the whole matrix
    M = MT + MV
    ew, ev = eigh(M)
    ind = argsort(ew)

    # Build the requested energy levels and states
    if "eigenstates_indices" in parameters:
        states = parameters["eigenstates_indices"]
    else:
        # Groundstate only
        states = [0]

    BS = HAWP.get_basis_shapes(component=0)

    KEY = ("q", "p", "Q", "P", "S", "adQ")

    print(70 * "-")
    for state in states:
        if state > BS.get_basis_size():
            print(
                "Warning: can not compute energy level {} with basis size of {}"
                .format((state, BS)))
            continue

        index = ind[state]

        coeffs = ev[:, index]
        energy = ew[index]

        # Try to resolve ambiguities in sign
        imax = argmax(abs(coeffs))
        a = abs(angle(coeffs[imax]))
        if a > pi / 2.0:
            coeffs *= -1

        print("State: {}".format(state))
        print("Energy: {}".format(energy))
        print("Coefficients: \n")
        print(str(coeffs))
        print(70 * "-")

        HAWP.set_coefficient_vector(coeffs.reshape((-1, 1)))

        # Save all the wavepacket data
        bid = IOM.create_block(groupid=gid)
        IOM.add_wavepacket(parameters, blockid=bid, key=KEY)
        IOM.save_wavepacket(HAWP, 0, blockid=bid, key=KEY)

    IOM.finalize()

    # TODO: Find better criterion
    if norm(q0) > 1000:
        print("+----------------------------------+")
        print("| Run-away minimum?                |")
        print("| Maybe try different:             |")
        print("|   starting_point = [x0, y0, ...] |")
        print("+----------------------------------+")
            z = psi[level]
            z = z.reshape(G.get_number_nodes())

            subplot(N,1,level+1)
            #plotcm(z.reshape(G.get_number_nodes()), darken=0.3)
            plotcf2d(u, v, z, darken=0.3, limits=limits)

        savefig("wavepacket_block_"+str(blockid)+"_level_"+str(level)+"_timestep_"+(5-len(str(step)))*"0"+str(step)+".png")
        close(fig)

    print(" Plotting frames finished")



if __name__ == "__main__":
    iom = IOManager()
    PL = ParameterLoader()

    # Read file with simulation data
    try:
        iom.open_file(filename=sys.argv[1])
    except IndexError:
        iom.open_file()

    # Read file with parameter data for grid
    try:
        PP = PL.load_from_file(sys.argv[2])
    except IndexError:
        PP = None

    # The axes rectangle that is plotted
Пример #17
0
                    nargs = "*",
                    default = [0])

parser.add_argument("-p", "--params",
                    help = "An additional configuration parameters file")

# TODO: Filter type of objects
# parser.add_argument("-t", "--type",
#                     help = "The type of objects to consider",
#                     type = str,
#                     default = "all")

args = parser.parse_args()

# Read file with simulation data
iom = IOManager()
iom.open_file(filename=args.simfile)

# Which blocks to handle
if "all" in args.blockid:
    blocks_to_handle = iom.get_block_ids()
else:
    blocks_to_handle = map(int, args.blockid)

# Do we have a specifc configuration file holding
# the definitions for inner products to use?
if args.params:
    parametersfile = args.params
    PA = ParameterLoader().load_from_file(parametersfile)
else:
    # None given, try to load from simulation file
Пример #18
0
    parser.add_argument("-r", "--resultspath", type=str, help="Path where to put the results.", nargs="?", default=".")

    parser.add_argument("--reim", action="store_true", help="Plot the real and imaginary parts")

    args = parser.parse_args()

    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # Read the data and plot it, one plot for each data block.
    parameters = iom.load_parameters()

    # Iterate over all blocks
    for blockid in blockids:
        print("Plotting wavepacket coefficients in data block '{}'".format(blockid))

        # NOTE: Add new algorithms here
Пример #19
0
                        nargs = 2,
                        default = [None, None])

    args = parser.parse_args()


    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # The axes rectangle that is plotted
    view = args.trange + args.vrange

    # Iterate over all blocks
    for blockid in blockids:
        print("Plotting norms in data block '{}'".format(blockid))

        if iom.has_norm(blockid=blockid):
                    help = "The simulation data file",
                    nargs = "?",
                    default = GD.file_resultdatafile)

parser.add_argument("-b", "--blockid",
                    help = "The data block to handle",
                    nargs = "*",
                    default = [0])

parser.add_argument("-p", "--params",
                    help = "An additional configuration parameters file")

args = parser.parse_args()

# Read file with simulation data
iom = IOManager()
iom.open_file(filename=args.simfile)

# Read the additional grid parameters
if args.params:
    parametersfile = args.params
    PA = ParameterLoader().load_from_file(parametersfile)
else:
    PA = None

# Which blocks to handle
if "all" in args.blockid:
    blocks_to_handle = iom.get_block_ids()
else:
    blocks_to_handle = map(int, args.blockid)
Пример #21
0
                        nargs="?",
                        default='.')

    args = parser.parse_args()

    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(
            args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    parameters = iom.load_parameters()

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # Iterate over all blocks
    for blockid in blockids:
        print("Plotting wavepacket coefficients in data block '{}'".format(
            blockid))

        # NOTE: Add new algorithms here
Пример #22
0
def load_from_file(filepath, blockid=0, timestep=0, sizeK=None):
    r"""Utility script to load wavepacket parameters and coefficients
    from another simulation result in a form suitable for the input
    configuration of a new simulation. This is (mainly) used
    to start simulations with previously computed eigenstates.

    :param filepath: The path to the `.hdf5` file from which data will be read.
    :param blockid: The `datablock` from which to read the data.
                    Default is the block with `blockid=0`.
    :param timestep: Load the data corresponding to the given `timestep`.
                     The default timestep is `0`.
    :param sizeK: Load at most 'sizeK' many coefficients. Note that the order
                  is defined by the linearization mapping :math:`\mu` of the
                  packet's current basis shape. We then pick the first `sizeK`
                  ones.
    """
    IOM = IOManager()
    IOM.open_file(filepath)

    # Check if we have data
    tg = IOM.load_wavepacket_timegrid(blockid=blockid)
    if timestep not in tg:
        raise ValueError("No data for timestep {}".format(timestep))

    # Load data and assemble packet
    BF = BlockFactory()

    # Basis shapes
    BS_descr = IOM.load_wavepacket_basisshapes(blockid=blockid)
    BS = {}
    for ahash, descr in BS_descr.items():
        BS[ahash] = BF.create_basis_shape(descr)

    # Create a packet
    wpd = IOM.load_wavepacket_description(blockid=blockid)
    HAWP = BF.create_wavepacket(wpd)

    # Data
    ha, ci = IOM.load_wavepacket_coefficients(blockid=blockid, timestep=timestep, get_hashes=True)
    Pi = IOM.load_wavepacket_parameters(blockid=blockid, timestep=timestep)

    HAWP.set_parameters(Pi)
    HAWP.set_basis_shapes([BS[int(h)] for h in ha])
    HAWP.set_coefficients(ci)

    # Reformat data
    C = []

    for n in range(HAWP.get_number_components()):
        B = HAWP.get_basis_shapes(component=n)
        cn = HAWP.get_coefficients(component=n)
        l = []
        for i in range(B.get_basis_size()):
            l.append((B[i], cn[i, 0]))
        C.append(l)

    if sizeK is not None:
        # We load at most 'sizeK' coefficients.
        # Note that this does NOT specify which
        # ones in terms of multi-indices.
        C = [c[:sizeK] for c in C]

    return Pi, C
Пример #23
0
def compute_eigenstate(parameters):
    r"""
    Special variables necessary in configuration:

    * eigenstate_of_level (default: 0)
    * states_indices (default: [0])
    """
    D = parameters["dimension"]

    if parameters.has_key("eigenstate_of_level"):
        N = parameters["eigenstate_of_level"]
    else:
        # Upper-most potential surface
        N = 0

    # Create output file now, in case this fails we did not waste computations
    IOM = IOManager()
    IOM.create_file("eigenstates.hdf5")

    # Save the simulation parameters
    IOM.add_parameters()
    IOM.save_parameters(parameters)

    gid = IOM.create_group()

    BF = BlockFactory()
    # Create the potential
    V = BF.create_potential(parameters)
    V.calculate_local_quadratic()

    # Minimize the potential to find q0
    f = lambda x: real((squeeze(V.evaluate_at(x)[N])))
    # Start with an offset because exact 0.0 values can give
    # issues, especially with the Hessian evaluation. This way
    # the minimizer will always stay away from zero a tiny bit.
    # The current starting point can give issues if the potential
    # is stationary at the point (2, ..., 2) but that is less likely.
    x0 = 2.0*ones(D)
    q0 = fmin(f, x0, xtol=1e-12)
    q0 = q0.reshape((D,1))

    # We are at the minimum with no momentum
    p0 = zeros_like(q0)

    # Compute spreads now
    # Q_0 = H^(-1/4)
    H = V.evaluate_hessian_at(q0)
    Q0 = inv(sqrtm(sqrtm(H)))
    # Take P_00 = i Q_0^(-1)
    P0 = 1.0j * inv(Q0)

    #
    print(70*"-")
    print("Parameter values are:")
    print("---------------------")
    print(" q0:")
    print(str(q0))
    print(" p0:")
    print(str(p0))
    print(" Q0:")
    print(str(Q0))
    print(" P0:")
    print(str(P0))
    # Consistency check
    print(" consistency:")
    print(str(conj(Q0)*P0 - conj(P0)*Q0))
    print(70*"-")

    # Next find the new coefficients c'
    HAWP = BF.create_wavepacket(parameters["hawp_template"])

    # Set the parameter values
    Pi = HAWP.get_parameters()
    Pi[0] = q0
    Pi[1] = p0
    Pi[2] = Q0
    Pi[3] = P0
    HAWP.set_parameters(Pi)

    # Next compute the matrix M_ij = <phi_i | T + V | phi_j>
    # The potential part
    HQ = BF.create_inner_product(parameters["innerproduct"])

    opV = lambda x, q, entry: V.evaluate_at(x, entry=entry)
    MV = HQ.build_matrix(HAWP, operator=opV)

    # The kinetic part
    MT = zeros_like(MV, dtype=complexfloating)
    GR = GradientHAWP()
    BS = HAWP.get_basis_shapes(N)

    vects = {}
    for i in BS:
        z = zeros_like(HAWP.get_coefficient_vector(), dtype=complexfloating)
        HAWP.set_coefficient_vector(z)
        HAWP.set_coefficient(N, i, 1.0)
        Kn, cnew = GR.apply_gradient(HAWP, N)
        vects[i] = cnew

    for j in BS:
        for k in BS:
            cj = vects[j]
            ck = vects[k]
            entry = 0.5 * squeeze(sum(conj(cj) * ck))
            MT[BS[j], BS[k]] = entry

    # Find eigenvalues and eigenvectors of the whole matrix
    M = MT + MV
    ew, ev = eigh(M)
    ind = argsort(ew)

    # Build the requested energy levels and states
    if parameters.has_key("eigenstates_indices"):
        states = parameters["eigenstates_indices"]
    else:
        # Groundstate only
        states = [0]

    BS = HAWP.get_basis_shapes(component=0)

    KEY = ("q","p","Q","P","S","adQ")

    print(70*"-")
    for state in states:
        if state > BS.get_basis_size():
            print("Warning: can not compute energy level "+state+" with basis size of "+str(BS))
            continue

        index = ind[state]

        coeffs = ev[:,index]
        energy = ew[index]

        print("Level: "+str(state))
        print("Energy: "+str(energy))
        print("Coefficients: \n")
        print(str(coeffs))
        print(70*"-")

        HAWP.set_coefficient_vector(coeffs.reshape((-1, 1)))

        # Save all the wavepacket data
        bid = IOM.create_block(groupid=gid)
        IOM.add_wavepacket(parameters, blockid=bid, key=KEY)
        IOM.save_wavepacket_description(HAWP.get_description(), blockid=bid)
        for shape in HAWP.get_basis_shapes():
            IOM.save_wavepacket_basisshapes(shape, blockid=bid)
        IOM.save_wavepacket_parameters(HAWP.get_parameters(key=KEY), timestep=0, blockid=bid, key=KEY)
        IOM.save_wavepacket_coefficients(HAWP.get_coefficients(), HAWP.get_basis_shapes(), timestep=0, blockid=bid)

    IOM.finalize()
                        help = "Hold the plot open for interactive manipulation")

    args = parser.parse_args()


    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))
    parametersfile = os.path.abspath(os.path.join(args.resultspath, args.parametersfile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Read file with parameter data for grid
    if args.parametersfile:
        PL = ParameterLoader()
        PP = PL.load_from_file(parametersfile)
    else:
        PP = None

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # The axes rectangle that is plotted
Пример #25
0
Compute the energies of the different wavepackets or wavefunctions.

@author: R. Bourquin
@copyright: Copyright (C) 2010, 2011, 2012 R. Bourquin
@license: Modified BSD License
"""

import sys

from WaveBlocksND import IOManager


if __name__ == "__main__":

    iom = IOManager()

    # Read file with simulation data
    try:
        iom.open_file(filename=sys.argv[1])
    except IndexError:
        iom.open_file()

    # Iterate over all blocks
    for blockid in iom.get_block_ids():
        print("Computing the energies in data block '" + str(blockid) + "'")

        if iom.has_energy(blockid=blockid):
            print("Datablock '" + str(blockid) + "' already contains energy data, silent skip.")
            continue
parser.add_argument("-o", "--outputfile",
                    type = str,
                    help = "The data file to write the transformed data.")

args = parser.parse_args()

if not args.outputfile:
    outputfile = args.inputfile.replace(GD.ext_resultdatafile, "") + "_eigen" + GD.ext_resultdatafile
else:
    outputfile = args.outputfile

print("Reading simulation data from the file: "+str(args.inputfile))
print("Writing transformed data to the file: "+str(outputfile))

# Read file with simulation data
iomc = IOManager()
iomc.open_file(args.inputfile)

iome = IOManager()
iome.create_file(outputfile)

# New file for eigen transformed data
P = iomc.load_parameters()

# Save the simulation parameters
iome.add_parameters()
iome.save_parameters(P)

# Iterate over all groups
for groupid in iomc.get_group_ids():
Пример #27
0
                        nargs=2,
                        default=[None, None])

    args = parser.parse_args()

    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(
            args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # The axes rectangle that is plotted
    view = args.trange + args.vrange

    # Iterate over all blocks
    for blockid in iom.get_block_ids():
        print("Plotting energies in data block '{}'".format(blockid))

        if iom.has_energy(blockid=blockid):
Пример #28
0
    args = parser.parse_args()

    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(
            args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))
    parametersfile = os.path.abspath(
        os.path.join(args.resultspath, args.parametersfile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Read file with parameter data for grid
    parameters = iom.load_parameters()

    if args.parametersfile:
        PL = ParameterLoader()
        gridparams = PL.load_from_file(parametersfile)
    else:
        gridparams = parameters

    # The axes rectangle that is plotted
    view = args.xrange + args.yrange + args.zrange

    # Plot
Пример #29
0
        ax.set_ylabel("t")
        ax.set_title(r"Coefficients $c_k^" + str(jndex) + "$")
        fig.savefig("wavepacket_coefficients_map_eigen_cm_component" +
                    str(jndex) + "_block" + str(index) + GD.output_format)
        close(fig)

        fig = figure(figsize=imgsize)
        ax = gca()
        plotcm(coeff, angle(coeff), abs(coeff), darken=True, axes=ax)
        ax.set_xlabel("k")
        ax.set_ylabel("t")
        ax.set_title(r"Coefficients $c_k^" + str(jndex) + "$")
        fig.savefig("wavepacket_coefficients_map_eigen_cm_darken_component" +
                    str(jndex) + "_block" + str(index) + GD.output_format)
        close(fig)


if __name__ == "__main__":
    iom = IOManager()

    # Read file with simulation data
    try:
        iom.open_file(filename=sys.argv[1])
    except IndexError:
        iom.open_file()

    # Read the data and plot it, one plot for each data block.
    read_all_datablocks(iom)

    iom.finalize()
Пример #30
0
def load_from_file(filepath, blockid=0, timestep=0, sizeK=None):
    r"""Utility script to load wavepacket parameters and coefficients
    from another simulation result in a form suitable for the input
    configuration of a new simulation. This is (mainly) used
    to start simulations with previously computed eigenstates.

    :param filepath: The path to the `.hdf5` file from which data will be read.
    :param blockid: The `datablock` from which to read the data.
                    Default is the block with `blockid=0`.
    :param timestep: Load the data corresponding to the given `timestep`.
                     The default timestep is `0`.
    :param sizeK: Load at most 'sizeK' many coefficients. Note that the order
                  is defined by the linearization mapping :math:`\mu` of the
                  packet's current basis shape. We then pick the first `sizeK`
                  ones.
    """
    IOM = IOManager()
    IOM.open_file(filepath)

    # Check if we have data
    tg = IOM.load_wavepacket_timegrid(blockid=blockid)
    if timestep not in tg:
        raise ValueError("No data for timestep {}".format(timestep))

    # Load data and assemble packet
    BF = BlockFactory()

    # Basis shapes
    BS_descr = IOM.load_wavepacket_basisshapes(blockid=blockid)
    BS = {}
    for ahash, descr in BS_descr.items():
        BS[ahash] = BF.create_basis_shape(descr)

    # Create a packet
    wpd = IOM.load_wavepacket_description(blockid=blockid)
    HAWP = BF.create_wavepacket(wpd)

    # Data
    ha, ci = IOM.load_wavepacket_coefficients(blockid=blockid,
                                              timestep=timestep,
                                              get_hashes=True)
    Pi = IOM.load_wavepacket_parameters(blockid=blockid, timestep=timestep)

    HAWP.set_parameters(Pi)
    HAWP.set_basis_shapes([BS[int(h)] for h in ha])
    HAWP.set_coefficients(ci)

    # Reformat data
    C = []

    for n in range(HAWP.get_number_components()):
        B = HAWP.get_basis_shapes(component=n)
        cn = HAWP.get_coefficients(component=n)
        l = []
        for i in range(B.get_basis_size()):
            l.append((B[i], cn[i, 0]))
        C.append(l)

    if sizeK is not None:
        # We load at most 'sizeK' coefficients.
        # Note that this does NOT specify which
        # ones in terms of multi-indices.
        C = [c[:sizeK] for c in C]

    return Pi, C
Пример #31
0
    parser.add_argument("-y", "--yrange", type=float, help="The plot range on the y-axis", nargs=2, default=[-2, 5])

    args = parser.parse_args()

    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))
    parametersfile = os.path.abspath(os.path.join(args.resultspath, args.parametersfile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Read file with parameter data for grid
    parameters = iom.load_parameters()

    if args.parametersfile:
        PL = ParameterLoader()
        gridparams = PL.load_from_file(parametersfile)
    else:
        gridparams = parameters

    # The axes rectangle that is plotted
    view = args.xrange + args.yrange

    if parameters["dimension"] == 1:
Пример #32
0
#                     type = str,
#                     default = "all")

args = parser.parse_args()


# File with the simulation data
resultspath = os.path.abspath(args.resultspath)

if not os.path.exists(resultspath):
    raise IOError("The results path does not exist: {}".format(args.resultspath))

datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

# Read file with simulation data
iom = IOManager()
iom.open_file(filename=datafile)

# Which blocks to handle
blockids = iom.get_block_ids()
if "all" not in args.blockid:
    blockids = [bid for bid in args.blockid if bid in blockids]


print("**************************************************")
print("***            Computing Norms                 ***")
print("**************************************************")

# Iterate over all blocks
for blockid in blockids:
    print("Computing the norms in data block '{}'".format(blockid))
Пример #33
0
parser.add_argument("-d", "--datafile",
                    type = str,
                    help = "The simulation data file",
                    nargs = "?",
                    default = GD.file_resultdatafile)

parser.add_argument("-b", "--blockid",
                    type = str,
                    help = "The data block to handle",
                    nargs = "*",
                    default = ["all"])

args = parser.parse_args()

# Read file with simulation data
iom = IOManager()
iom.open_file(filename=args.datafile)

# Which blocks to handle
blockids = iom.get_block_ids()
if "all" not in args.blockid:
    blockids = [bid for bid in args.blockid if bid in blockids]

# Iterate over all blocks
for blockid in blockids:
    if iom.has_wavefunction(blockid=blockid):
        print("Deleting grid and wavefunction data in block '{}'".format(blockid))
        iom.delete_wavefunction(blockid=blockid)
        if iom.has_grid(blockid=blockid):
            iom.delete_grid(blockid=blockid)
Пример #34
0
                        nargs=2,
                        default=[None, None])

    args = parser.parse_args()


    # File with the simulation data
    resultspath = os.path.abspath(args.resultspath)

    if not os.path.exists(resultspath):
        raise IOError("The results path does not exist: {}".format(args.resultspath))

    datafile = os.path.abspath(os.path.join(args.resultspath, args.datafile))

    # Read file with simulation data
    iom = IOManager()
    iom.open_file(filename=datafile)

    # Which blocks to handle
    blockids = iom.get_block_ids()
    if "all" not in args.blockid:
        blockids = [bid for bid in args.blockid if bid in blockids]

    # The axes rectangle that is plotted
    view = args.trange + args.vrange

    # Iterate over all blocks
    for blockid in iom.get_block_ids():
        print("Plotting energies in data block '{}'".format(blockid))

        if iom.has_energy(blockid=blockid):