def compute_norm_inhawp(iom, blockid=0, eigentrafo=True):
    """Compute the norm of a wavepacket timeseries.
    This function is for inhomogeneous wavepackets.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    :type blockid: Integer, Default is ``0``
    :param eigentrafo: Whether to make a transformation into the eigenbasis.
    :type eigentrafo: Boolean, default is ``True``.
    """
    parameters = iom.load_parameters()

    # Number of time steps we saved
    timesteps = iom.load_inhomogwavepacket_timegrid(blockid=blockid)
    nrtimesteps = timesteps.shape[0]

    # Basis transformator
    if eigentrafo is True:
        # The potential used
        Potential = BlockFactory().create_potential(parameters)
        BT = BasisTransformationHAWP(Potential)

    # We want to save norms, thus add a data slot to the data file
    iom.add_norm(parameters, timeslots=nrtimesteps, blockid=blockid)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_inhomogwavepacket_description(blockid=blockid)
    HAWP = BlockFactory().create_wavepacket(descr)

    if eigentrafo is True:
        BT.set_matrix_builder(HAWP.get_quadrature())

    # Basis shapes
    BS_descr = iom.load_inhomogwavepacket_basisshapes()
    BS = {}
    for ahash, descr in BS_descr.iteritems():
        BS[ahash] = BlockFactory().create_basis_shape(descr)

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Computing norms of timestep "+str(step))

        # Retrieve simulation data
        params = iom.load_inhomogwavepacket_parameters(timestep=step, blockid=blockid)
        hashes, coeffs = iom.load_inhomogwavepacket_coefficients(timestep=step, get_hashes=True, blockid=blockid)

        # Configure the wavepacket
        HAWP.set_parameters(params)
        HAWP.set_basis_shape([ BS[int(ha)] for ha in hashes ])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        if eigentrafo is True:
            BT.transform_to_eigen(HAWP)

        # Measure norms in the eigenbasis
        norm = HAWP.norm()

        # Save the norms
        iom.save_norm(norm, timestep=step, blockid=blockid)
def transform_inhawp_to_eigen(iomin, iomout, blockidin=0, blockidout=0):
    """Compute the transformation to the eigenbasis for a wavepacket.
    Save the result back to a file.

    :param iomin: An :py:class:`IOManager: instance providing the simulation data.
    :param iomout: An :py:class:`IOManager: instance for saving the transformed data.
    :param blockidin: The data block from which the values are read. Default is `0`.
    :param blockidout: The data block to which the values are written. Default is `0`.
    """
    parameters = iomin.load_parameters()

    # Number of time steps we saved
    timesteps = iomin.load_inhomogwavepacket_timegrid(blockid=blockidin)
    nrtimesteps = timesteps.shape[0]

    # The potential used
    Potential = BlockFactory().create_potential(parameters)

    # Basis transformator
    BT = BasisTransformationHAWP(Potential)

    # Initialize a Hagedorn wavepacket with the data
    descr = iomin.load_inhomogwavepacket_description(blockid=blockidin)
    HAWP = BlockFactory().create_wavepacket(descr)

    iomout.add_inhomogwavepacket(descr, timeslots=nrtimesteps, blockid=blockidout)
    iomout.save_inhomogwavepacket_description(HAWP.get_description(), blockid=blockidout)

    BT.set_matrix_builder(HAWP.get_quadrature())

    # Basis shapes
    BS_descr = iomin.load_inhomogwavepacket_basisshapes()
    BS = {}
    for ahash, descr in BS_descr.iteritems():
        BS[ahash] = BlockFactory().create_basis_shape(descr)

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Compute eigentransform at timestep # " + str(step))

        # Retrieve simulation data
        params = iomin.load_inhomogwavepacket_parameters(timestep=step, blockid=blockidin)
        hashes, coeffs = iomin.load_inhomogwavepacket_coefficients(timestep=step, get_hashes=True, blockid=blockidin)

        # Configure the wavepacket
        HAWP.set_parameters(params)
        HAWP.set_basis_shape([ BS[int(ha)] for ha in hashes ])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        BT.transform_to_eigen(HAWP)

        # Save the transformed packet
        # Pi
        iomout.save_inhomogwavepacket_parameters(HAWP.get_parameters(), timestep=step, blockid=blockidout)
        # Basis shapes (in case they changed!)
        for shape in HAWP.get_basis_shape():
            iomout.save_inhomogwavepacket_basisshapes(shape, blockid=blockidout)
        # Coefficients
        iomout.save_inhomogwavepacket_coefficients(HAWP.get_coefficients(), HAWP.get_basis_shape(), timestep=step, blockid=blockidout)
def read_data_inhomogeneous(iom, blockid=0):
    r"""
    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    """
    parameters = iom.load_parameters()
    timegrid = iom.load_inhomogwavepacket_timegrid(blockid=blockid)
    time = timegrid * parameters["dt"]

    # The potential used
    Potential = BlockFactory().create_potential(parameters)

    # Basis transformator
    BT = BasisTransformationHAWP(Potential)

    # Basis shapes
    BS_descr = iom.load_wavepacket_basisshapes(blockid=blockid)
    BS = {}
    for ahash, descr in BS_descr.iteritems():
        BS[ahash] = BlockFactory().create_basis_shape(descr)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_inhomogwavepacket_description(blockid=blockid)
    HAWP = BlockFactory().create_wavepacket(descr)

    BT.set_matrix_builder(HAWP.get_quadrature())

    # Store the resulting coefficients here
    CI = [ [] for i in xrange(HAWP.get_number_components()) ]

    # Iterate over all timesteps, this is an *expensive* transformation
    for i, step in enumerate(timegrid):
        print(" Computing eigentransformation at timestep "+str(step))
        # Retrieve simulation data
        params = iom.load_inhomogwavepacket_parameters(timestep=step, blockid=blockid)
        hashes, coeffs = iom.load_inhomogwavepacket_coefficients(timestep=step, get_hashes=True, blockid=blockid)

        # Configure the wavepacket
        HAWP.set_parameters(params)
        HAWP.set_basis_shapes([ BS[int(ha)] for ha in hashes ])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        BT.transform_to_eigen(HAWP)

        for index, item in enumerate(HAWP.get_coefficients()):
            CI[index].append(item)

    CI = [ transpose(hstack(item)) for item in CI ]

    return time, CI
def read_data_inhomogeneous(iom, blockid=0):
    r"""
    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    """
    parameters = iom.load_parameters()
    timegrid = iom.load_inhomogwavepacket_timegrid(blockid=blockid)
    dt = parameters["dt"] if "dt" in parameters else 1.0
    time = timegrid * dt

    # The potential used
    Potential = BlockFactory().create_potential(parameters)

    # Basis transformator
    BT = BasisTransformationHAWP(Potential)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_inhomogwavepacket_description(blockid=blockid)
    HAWP = BlockFactory().create_wavepacket(descr)

    BT.set_matrix_builder(HAWP.get_quadrature())

    # Store the resulting coefficients here
    CI = [[] for i in range(HAWP.get_number_components())]

    # Iterate over all timesteps, this is an *expensive* transformation
    for i, step in enumerate(timegrid):
        print(" Computing eigentransformation at timestep {}".format(step))
        # Retrieve simulation data
        HAWP = iom.load_inhomogwavepacket(timestep=step, blockid=blockid)

        # Transform to the eigenbasis.
        BT.transform_to_eigen(HAWP)

        for index, item in enumerate(HAWP.get_coefficients()):
            CI[index].append(item)

    CI = [transpose(hstack(item)) for item in CI]

    return time, CI
Example #5
0
def read_data_homogeneous(iom, blockid=0):
    r"""
    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    """
    parameters = iom.load_parameters()
    timegrid = iom.load_wavepacket_timegrid(blockid=blockid)
    time = timegrid * parameters["dt"]

    # The potential used
    Potential = BlockFactory().create_potential(parameters)

    # Basis transformator
    BT = BasisTransformationHAWP(Potential)

    # Basis shapes
    BS_descr = iom.load_wavepacket_basisshapes(blockid=blockid)
    BS = {}
    for ahash, descr in BS_descr.iteritems():
        BS[ahash] = BlockFactory().create_basis_shape(descr)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_wavepacket_description(blockid=blockid)
    HAWP = BlockFactory().create_wavepacket(descr)

    BT.set_matrix_builder(HAWP.get_quadrature())

    # Store the resulting coefficients here
    CI = [[] for i in xrange(HAWP.get_number_components())]

    # Iterate over all timesteps, this is an *expensive* transformation
    for i, step in enumerate(timegrid):
        print(" Computing eigentransformation at timestep " + str(step))
        # Retrieve simulation data
        params = iom.load_wavepacket_parameters(timestep=step, blockid=blockid)
        hashes, coeffs = iom.load_wavepacket_coefficients(timestep=step,
                                                          get_hashes=True,
                                                          blockid=blockid)

        # Configure the wavepacket
        HAWP.set_parameters(params)
        HAWP.set_basis_shape([BS[int(ha)] for ha in hashes])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        BT.transform_to_eigen(HAWP)

        for index, item in enumerate(HAWP.get_coefficients()):
            CI[index].append(item)

    CI = [transpose(hstack(item)) for item in CI]

    return time, CI
Example #6
0
def read_data_inhomogeneous(iom, blockid=0):
    r"""
    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    """
    parameters = iom.load_parameters()
    timegrid = iom.load_inhomogwavepacket_timegrid(blockid=blockid)
    dt = parameters["dt"] if "dt" in parameters else 1.0
    time = timegrid * dt

    # The potential used
    Potential = BlockFactory().create_potential(parameters)

    # Basis transformator
    BT = BasisTransformationHAWP(Potential)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_inhomogwavepacket_description(blockid=blockid)
    HAWP = BlockFactory().create_wavepacket(descr)

    BT.set_matrix_builder(HAWP.get_quadrature())

    # Store the resulting coefficients here
    CI = [[] for i in range(HAWP.get_number_components())]

    # Iterate over all timesteps, this is an *expensive* transformation
    for i, step in enumerate(timegrid):
        print(" Computing eigentransformation at timestep {}".format(step))
        # Retrieve simulation data
        HAWP = iom.load_inhomogwavepacket(timestep=step, blockid=blockid)

        # Transform to the eigenbasis.
        BT.transform_to_eigen(HAWP)

        for index, item in enumerate(HAWP.get_coefficients()):
            CI[index].append(item)

    CI = [transpose(hstack(item)) for item in CI]

    return time, CI
Example #7
0
def compute_energy_inhawp(iom, blockid=0, eigentrafo=True, iseigen=True):
    """Compute the energies of a wavepacket timeseries.
    This function is for inhomogeneous wavepackets.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    :type blockid: Integer, Default is ``0``
    :param eigentrafo: Whether to make a transformation into the eigenbasis.
    :type eigentrafo: Boolean, default is ``True``.
    :param iseigen: Whether the data is assumed to be in the eigenbasis.
    :type iseigen: Boolean, default is ``True``
    """
    parameters = iom.load_parameters()
    BF = BlockFactory()

    # Number of time steps we saved
    timesteps = iom.load_inhomogwavepacket_timegrid(blockid=blockid)
    nrtimesteps = timesteps.shape[0]

    # The potential used
    Potential = BF.create_potential(parameters)

    # Basis transformator
    if eigentrafo is True:
        BT = BasisTransformationHAWP(Potential)

    # We want to save energies, thus add a data slot to the data file
    iom.add_energy(parameters, timeslots=nrtimesteps, blockid=blockid)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_inhomogwavepacket_description(blockid=blockid)
    HAWP = BF.create_wavepacket(descr)

    # Inner product
    if HAWP.get_innerproduct() is None:
        IP = BF.create_inner_product(parameters["innerproduct"])
        HAWP.set_innerproduct(IP)

    if eigentrafo is True:
        BT.set_matrix_builder(HAWP.get_innerproduct())

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

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

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Computing energies of timestep %d" % step)

        # Retrieve simulation data
        params = iom.load_inhomogwavepacket_parameters(timestep=step,
                                                       blockid=blockid,
                                                       key=KEY)
        hashes, coeffs = iom.load_inhomogwavepacket_coefficients(
            timestep=step, get_hashes=True, blockid=blockid)

        # Configure the wavepacket
        HAWP.set_parameters(params, key=KEY)
        HAWP.set_basis_shapes([BS[int(ha)] for ha in hashes])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        if eigentrafo is True:
            BT.transform_to_eigen(HAWP)

        # Compute the energies
        O.set_innerproduct(HAWP.get_innerproduct())
        O.set_gradient(HAWP.get_gradient_operator())
        ekin = O.kinetic_energy(HAWP)
        if iseigen is True:
            epot = O.potential_energy(HAWP, Potential.evaluate_eigenvalues_at)
        else:
            epot = O.potential_energy(HAWP, Potential.evaluate_at)

        iom.save_energy((ekin, epot), timestep=step, blockid=blockid)
def compute_autocorrelation_inhawp(iom, obsconfig, blockid=0, eigentrafo=True):
    """Compute the autocorrelation of a wavepacket timeseries.
    This function is for inhomogeneous wavepackets.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param obsconfig: Configuration parameters describing f.e. the inner product to use.
    :type obsconfig: A :py:class:`ParameterProvider` instance.
    :param blockid: The data block from which the values are read.
    :type blockid: Integer, Default is ``0``
    :param eigentrafo: Whether to make a transformation into the eigenbasis.
    :type eigentrafo: Boolean, default is ``True``.
    """
    parameters = iom.load_parameters()
    BF = BlockFactory()

    # Number of time steps we saved
    timesteps = iom.load_inhomogwavepacket_timegrid(blockid=blockid)
    nrtimesteps = timesteps.shape[0]

    # Basis transformator
    if eigentrafo is True:
        # The potential used
        Potential = BF.create_potential(parameters)
        BT = BasisTransformationHAWP(Potential)

    # We want to save autocorrelations, thus add a data slot to the data file
    iom.add_autocorrelation(parameters, timeslots=nrtimesteps, blockid=blockid)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_inhomogwavepacket_description(blockid=blockid)
    HAWPo = BF.create_wavepacket(descr)
    HAWPt = BF.create_wavepacket(descr)

    if eigentrafo is True:
        BT.set_matrix_builder(HAWPo.get_innerproduct())

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

    # Comfigure the original wavepacket
    # Retrieve simulation data
    params = iom.load_inhomogwavepacket_parameters(timestep=0, blockid=blockid)
    hashes, coeffs = iom.load_inhomogwavepacket_coefficients(timestep=0, get_hashes=True, blockid=blockid)
    # Configure the wavepacket
    HAWPo.set_parameters(params)
    HAWPo.set_basis_shapes([BS[int(ha)] for ha in hashes])
    HAWPo.set_coefficients(coeffs)

    # Set up the innerproduct for solving the integrals <phi_0 | phi_t>
    IP = BF.create_inner_product(obsconfig["innerproduct"])

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Computing autocorrelations of timestep %d" % step)

        # Retrieve simulation data
        params = iom.load_inhomogwavepacket_parameters(timestep=step, blockid=blockid)
        hashes, coeffs = iom.load_inhomogwavepacket_coefficients(timestep=step, get_hashes=True, blockid=blockid)

        # Configure the wavepacket
        HAWPt.set_parameters(params)
        HAWPt.set_basis_shapes([BS[int(ha)] for ha in hashes])
        HAWPt.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        if eigentrafo is True:
            BT.transform_to_eigen(HAWPt)

        # Measure autocorrelations in the eigenbasis
        acs = IP.quadrature(HAWPo, HAWPt, diagonal=True)

        # Save the autocorrelations
        iom.save_autocorrelation(acs, timestep=step, blockid=blockid)
Example #9
0
def compute_autocorrelation_hawp(iom, obsconfig, blockid=0, eigentrafo=True):
    """Compute the autocorrelation of a wavepacket timeseries.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param obsconfig: Configuration parameters describing f.e. the inner product to use.
    :type obsconfig: A :py:class:`ParameterProvider` instance.
    :param blockid: The data block from which the values are read.
    :type blockid: Integer, Default is ``0``
    :param eigentrafo: Whether to make a transformation into the eigenbasis.
    :type eigentrafo: Boolean, default is ``True``.
    """
    parameters = iom.load_parameters()
    BF = BlockFactory()

    # Number of time steps we saved
    timesteps = iom.load_wavepacket_timegrid(blockid=blockid)
    nrtimesteps = timesteps.shape[0]

    # Basis transformator
    if eigentrafo is True:
        # The potential used
        Potential = BF.create_potential(parameters)
        BT = BasisTransformationHAWP(Potential)

    # We want to save norms, thus add a data slot to the data file
    iom.add_autocorrelation(parameters, timeslots=nrtimesteps, blockid=blockid)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_wavepacket_description(blockid=blockid)
    HAWPo = BF.create_wavepacket(descr)
    HAWPt = BF.create_wavepacket(descr)

    if eigentrafo is True:
        BT.set_matrix_builder(HAWPo.get_innerproduct())

    # 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)

    # Comfigure the original wavepacket
    KEY = ("q", "p", "Q", "P", "S", "adQ")
    # Retrieve simulation data
    params = iom.load_wavepacket_parameters(timestep=0,
                                            blockid=blockid,
                                            key=KEY)
    hashes, coeffs = iom.load_wavepacket_coefficients(timestep=0,
                                                      get_hashes=True,
                                                      blockid=blockid)
    # Configure the wavepacket
    HAWPo.set_parameters(params, key=KEY)
    HAWPo.set_basis_shapes([BS[int(ha)] for ha in hashes])
    HAWPo.set_coefficients(coeffs)

    # Set up the innerproduct for solving the integrals <phi_0 | phi_t>
    IP = BF.create_inner_product(obsconfig["innerproduct"])

    # Transform to the eigenbasis.
    if eigentrafo is True:
        BT.transform_to_eigen(HAWPo)

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Computing autocorrelation of timestep %d" % step)

        # Retrieve simulation data
        paramst = iom.load_wavepacket_parameters(timestep=step,
                                                 blockid=blockid,
                                                 key=KEY)
        hashes, coeffs = iom.load_wavepacket_coefficients(timestep=step,
                                                          get_hashes=True,
                                                          blockid=blockid)

        # Configure the wavepacket
        HAWPt.set_parameters(paramst, key=KEY)
        HAWPt.set_basis_shapes([BS[int(ha)] for ha in hashes])
        HAWPt.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        if eigentrafo is True:
            BT.transform_to_eigen(HAWPt)

        # Measure autocorrelations in the eigenbasis
        acs = IP.quadrature(HAWPo, HAWPt, diagonal=True)

        # Save the autocorrelations
        iom.save_autocorrelation(acs, timestep=step, blockid=blockid)
Example #10
0
def plot_frames(PP,
                iom,
                blockid=0,
                eigentransform=False,
                timerange=None,
                view=None,
                plotphase=True,
                plotcomponents=False,
                plotabssqr=False,
                load=False,
                gridblockid=None,
                imgsize=(12, 9),
                path='.'):
    """Plot the wavepacket for a series of timesteps.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    """
    parameters = iom.load_parameters()
    BF = BlockFactory()

    if not parameters["dimension"] == 1:
        print("No one-dimensional wavepacket, silent return!")
        return

    if PP is None:
        PP = parameters

    if load is True:
        if gridblockid is None:
            gridblockid = blockid
        print("Loading grid data from datablock '{}'".format(gridblockid))
        G = iom.load_grid(blockid=gridblockid)
        grid = real(G.reshape(-1))
    else:
        print("Creating new grid")
        G = BlockFactory().create_grid(PP)
        grid = real(G.get_nodes(flat=True).reshape(-1))

    if eigentransform:
        V = BF.create_potential(parameters)
        BT = BasisTransformationHAWP(V)

    timegrid = iom.load_wavepacket_timegrid(blockid=blockid)
    if timerange is not None:
        if len(timerange) == 1:
            I = (timegrid == timerange)
        else:
            I = ((timegrid >= timerange[0]) & (timegrid <= timerange[1]))
        if any(I):
            timegrid = timegrid[I]
        else:
            raise ValueError("No valid timestep remains!")

    # View
    if view is not None:
        if view[0] is None:
            view[0] = grid.min()
        if view[1] is None:
            view[1] = grid.max()

    for step in timegrid:
        print(" Plotting frame of timestep # {}".format(step))

        HAWP = iom.load_wavepacket(step, blockid=blockid)

        # Transform the values to the eigenbasis
        if eigentransform:
            BT.transform_to_eigen(HAWP)

        values = HAWP.evaluate_at(G.get_nodes(), prefactor=True, component=0)

        # Plot
        fig = figure(figsize=imgsize)

        for index, component in enumerate(values):
            ax = fig.add_subplot(parameters["ncomponents"], 1, index + 1)
            ax.ticklabel_format(style="sci", scilimits=(0, 0), axis="y")

            if plotcomponents is True:
                ax.plot(grid, real(component))
                ax.plot(grid, imag(component))
                ax.set_ylabel(r"$\Re \varphi_{%d}, \Im \varphi_{%d}$" %
                              (index, index))
            if plotabssqr is True:
                ax.plot(grid, real(component * conj(component)))
                ax.set_ylabel(
                    r"$\langle \varphi_{%d} | \varphi_{%d} \rangle$" %
                    (index, index))
            if plotphase is True:
                plotcf(grid, angle(component),
                       real(component * conj(component)))
                ax.set_ylabel(
                    r"$\langle \varphi_{%d} | \varphi_{%d} \rangle$" %
                    (index, index))

            ax.set_xlabel(r"$x$")

            # Set the aspect window
            ax.set_xlim(view[:2])
            ax.set_ylim(view[2:])

        if "dt" in parameters:
            fig.suptitle(r"$\Psi$ at time $%f$" % (step * parameters["dt"]))
        else:
            fig.suptitle(r"$\Psi$")

        fig.savefig(
            os.path.join(
                path,
                "wavepacket_block_%s_timestep_%07d.png" % (blockid, step)))
        close(fig)
def plot_frames(PP, iom, blockid=0, load=False, eigentransform=False, timerange=None, view=None, path='.'):
    """Plot the wavepacket for a series of timesteps.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    """
    parameters = iom.load_parameters()
    BF = BlockFactory()

    if not parameters["dimension"] == 2:
        print("No two-dimensional wavepacket, silent return!")
        return

    if PP is None:
        PP = parameters

    if load is True:
        # TODO: Implement reshaping
        raise NotImplementedError("Loading of 2D grids is not implemented")
    else:
        G = BF.create_grid(PP)

    if eigentransform:
        V = BF.create_potential(parameters)
        BT = BasisTransformationHAWP(V)

    timegrid = iom.load_wavepacket_timegrid(blockid=blockid)
    if timerange is not None:
        if len(timerange) == 1:
            I = (timegrid == timerange)
        else:
            I = ((timegrid >= timerange[0]) & (timegrid <= timerange[1]))
        if any(I):
            timegrid = timegrid[I]
        else:
            raise ValueError("No valid timestep remains!")

    u, v = G.get_axes()
    u = real(u.reshape(-1))
    v = real(v.reshape(-1))

    # View
    if view is not None:
        if view[0] is None:
            view[0] = u.min()
        if view[1] is None:
            view[1] = u.max()
        if view[2] is None:
            view[2] = v.min()
        if view[3] is None:
            view[3] = v.max()

    for step in timegrid:
        print(" Plotting frame of timestep # {}".format(step))

        HAWP = iom.load_wavepacket(step, blockid=blockid)
        N = HAWP.get_number_components()

        # Transform the values to the eigenbasis
        if eigentransform:
            BT.transform_to_eigen(HAWP)

        psi = HAWP.evaluate_at(G.get_nodes(), prefactor=True, component=0)

        # Plot
        fig = figure()

        for level in range(N):
            z = psi[level]
            z = z.reshape(G.get_number_nodes())

            fig.add_subplot(N, 1, level + 1)
            plotcf2d(u, v, z, darken=0.3, limits=view)

        fig.savefig(os.path.join(path, "wavepacket_block_%s_level_%d_timestep_%07d.png" % (blockid, level, step)))
        close(fig)
def compute_energy_inhawp(iom, blockid=0, eigentrafo=True, iseigen=True):
    """Compute the energies of a wavepacket timeseries.
    This function is for inhomogeneous wavepackets.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    :type blockid: Integer, Default is ``0``
    :param eigentrafo: Whether to make a transformation into the eigenbasis.
    :type eigentrafo: Boolean, default is ``True``.
    :param iseigen: Whether the data is assumed to be in the eigenbasis.
    :type iseigen: Boolean, default is ``True``
    """
    parameters = iom.load_parameters()

    # Number of time steps we saved
    timesteps = iom.load_inhomogwavepacket_timegrid(blockid=blockid)
    nrtimesteps = timesteps.shape[0]

    # The potential used
    Potential = BlockFactory().create_potential(parameters)

    # Basis transformator
    if eigentrafo is True:
        BT = BasisTransformationHAWP(Potential)

    # We want to save energies, thus add a data slot to the data file
    iom.add_energy(parameters, timeslots=nrtimesteps, blockid=blockid)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_inhomogwavepacket_description(blockid=blockid)
    HAWP = BlockFactory().create_wavepacket(descr)

    if eigentrafo is True:
        BT.set_matrix_builder(HAWP.get_innerproduct())

    # Basis shapes
    BS_descr = iom.load_inhomogwavepacket_basisshapes(blockid=blockid)
    BS = {}
    for ahash, descr in BS_descr.iteritems():
        BS[ahash] = BlockFactory().create_basis_shape(descr)

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

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Computing energies of timestep "+str(step))

        # Retrieve simulation data
        params = iom.load_inhomogwavepacket_parameters(timestep=step, blockid=blockid, key=KEY)
        hashes, coeffs = iom.load_inhomogwavepacket_coefficients(timestep=step, get_hashes=True, blockid=blockid)

        # Configure the wavepacket
        HAWP.set_parameters(params, key=KEY)
        HAWP.set_basis_shapes([ BS[int(ha)] for ha in hashes ])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        if eigentrafo is True:
            BT.transform_to_eigen(HAWP)

        # Compute the energies
        O.set_innerproduct(HAWP.get_innerproduct())
        ekin = O.kinetic_energy(HAWP)
        if iseigen is True:
            epot = O.potential_energy(HAWP, Potential.evaluate_eigenvalues_at)
        else:
            epot = O.potential_energy(HAWP, Potential.evaluate_at)

        iom.save_energy((ekin, epot), timestep=step, blockid=blockid)
Example #13
0
def compute_norm_inhawp(iom, blockid=0, eigentrafo=True):
    """Compute the norm of a wavepacket timeseries.
    This function is for inhomogeneous wavepackets.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    :type blockid: Integer, Default is ``0``
    :param eigentrafo: Whether to make a transformation into the eigenbasis.
    :type eigentrafo: Boolean, default is ``True``.
    """
    parameters = iom.load_parameters()

    # Number of time steps we saved
    timesteps = iom.load_inhomogwavepacket_timegrid(blockid=blockid)
    nrtimesteps = timesteps.shape[0]

    # Basis transformator
    if eigentrafo is True:
        # The potential used
        Potential = BlockFactory().create_potential(parameters)
        BT = BasisTransformationHAWP(Potential)

    # We want to save norms, thus add a data slot to the data file
    iom.add_norm(parameters, timeslots=nrtimesteps, blockid=blockid)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_inhomogwavepacket_description(blockid=blockid)
    HAWP = BlockFactory().create_wavepacket(descr)

    if eigentrafo is True:
        BT.set_matrix_builder(HAWP.get_quadrature())

    # Basis shapes
    BS_descr = iom.load_inhomogwavepacket_basisshapes()
    BS = {}
    for ahash, descr in BS_descr.iteritems():
        BS[ahash] = BlockFactory().create_basis_shape(descr)

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Computing norms of timestep " + str(step))

        # Retrieve simulation data
        params = iom.load_inhomogwavepacket_parameters(timestep=step,
                                                       blockid=blockid)
        hashes, coeffs = iom.load_inhomogwavepacket_coefficients(
            timestep=step, get_hashes=True, blockid=blockid)

        # Configure the wavepacket
        HAWP.set_parameters(params)
        HAWP.set_basis_shape([BS[int(ha)] for ha in hashes])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        if eigentrafo is True:
            BT.transform_to_eigen(HAWP)

        # Measure norms in the eigenbasis
        norm = HAWP.norm()

        # Save the norms
        iom.save_norm(norm, timestep=step, blockid=blockid)
Example #14
0
def plot_frames(PP, iom, blockid=0, eigentransform=False, timerange=None, view=None,
                plotphase=True, plotcomponents=False, plotabssqr=False,
                load=False, gridblockid=None, imgsize=(12, 9), path='.'):
    """Plot the wavepacket for a series of timesteps.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    """
    parameters = iom.load_parameters()
    BF = BlockFactory()

    if not parameters["dimension"] == 1:
        print("No one-dimensional wavepacket, silent return!")
        return

    if PP is None:
        PP = parameters

    if load is True:
        if gridblockid is None:
            gridblockid = blockid
        print("Loading grid data from datablock '{}'".format(gridblockid))
        G = iom.load_grid(blockid=gridblockid)
        grid = real(G.reshape(-1))
    else:
        print("Creating new grid")
        G = BlockFactory().create_grid(PP)
        grid = real(G.get_nodes(flat=True).reshape(-1))

    if eigentransform:
        V = BF.create_potential(parameters)
        BT = BasisTransformationHAWP(V)

    timegrid = iom.load_wavepacket_timegrid(blockid=blockid)
    if timerange is not None:
        if len(timerange) == 1:
            I = (timegrid == timerange)
        else:
            I = ((timegrid >= timerange[0]) & (timegrid <= timerange[1]))
        if any(I):
            timegrid = timegrid[I]
        else:
            raise ValueError("No valid timestep remains!")

    # View
    if view is not None:
        if view[0] is None:
            view[0] = grid.min()
        if view[1] is None:
            view[1] = grid.max()

    for step in timegrid:
        print(" Plotting frame of timestep # {}".format(step))

        HAWP = iom.load_wavepacket(step, blockid=blockid)

        # Transform the values to the eigenbasis
        if eigentransform:
            BT.transform_to_eigen(HAWP)

        values = HAWP.evaluate_at(G.get_nodes(), prefactor=True, component=0)

        # Plot
        fig = figure(figsize=imgsize)

        for index, component in enumerate(values):
            ax = fig.add_subplot(parameters["ncomponents"], 1, index + 1)
            ax.ticklabel_format(style="sci", scilimits=(0, 0), axis="y")

            if plotcomponents is True:
                ax.plot(grid, real(component))
                ax.plot(grid, imag(component))
                ax.set_ylabel(r"$\Re \varphi_{%d}, \Im \varphi_{%d}$" % (index, index))
            if plotabssqr is True:
                ax.plot(grid, real(component * conj(component)))
                ax.set_ylabel(r"$\langle \varphi_{%d} | \varphi_{%d} \rangle$" % (index, index))
            if plotphase is True:
                plotcf(grid, angle(component), real(component * conj(component)))
                ax.set_ylabel(r"$\langle \varphi_{%d} | \varphi_{%d} \rangle$" % (index, index))

            ax.set_xlabel(r"$x$")

            # Set the aspect window
            ax.set_xlim(view[:2])
            ax.set_ylim(view[2:])

        if "dt" in parameters:
            fig.suptitle(r"$\Psi$ at time $%f$" % (step * parameters["dt"]))
        else:
            fig.suptitle(r"$\Psi$")

        fig.savefig(os.path.join(path, "wavepacket_block_%s_timestep_%07d.png" % (blockid, step)))
        close(fig)
def plot_frames(PP,
                iom,
                blockid=0,
                load=False,
                eigentransform=False,
                timerange=None,
                view=None,
                path='.'):
    """Plot the wavepacket for a series of timesteps.

    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    """
    parameters = iom.load_parameters()
    BF = BlockFactory()

    if not parameters["dimension"] == 2:
        print("No two-dimensional wavepacket, silent return!")
        return

    if PP is None:
        PP = parameters

    if load is True:
        # TODO: Implement reshaping
        raise NotImplementedError("Loading of 2D grids is not implemented")
    else:
        G = BF.create_grid(PP)

    if eigentransform:
        V = BF.create_potential(parameters)
        BT = BasisTransformationHAWP(V)

    timegrid = iom.load_wavepacket_timegrid(blockid=blockid)
    if timerange is not None:
        if len(timerange) == 1:
            I = (timegrid == timerange)
        else:
            I = ((timegrid >= timerange[0]) & (timegrid <= timerange[1]))
        if any(I):
            timegrid = timegrid[I]
        else:
            raise ValueError("No valid timestep remains!")

    u, v = G.get_axes()
    u = real(u.reshape(-1))
    v = real(v.reshape(-1))

    # View
    if view is not None:
        if view[0] is None:
            view[0] = u.min()
        if view[1] is None:
            view[1] = u.max()
        if view[2] is None:
            view[2] = v.min()
        if view[3] is None:
            view[3] = v.max()

    for step in timegrid:
        print(" Plotting frame of timestep # {}".format(step))

        HAWP = iom.load_wavepacket(step, blockid=blockid)
        N = HAWP.get_number_components()

        # Transform the values to the eigenbasis
        if eigentransform:
            BT.transform_to_eigen(HAWP)

        psi = HAWP.evaluate_at(G.get_nodes(), prefactor=True, component=0)

        # Plot
        fig = figure()

        for level in range(N):
            z = psi[level]
            z = z.reshape(G.get_number_nodes())

            fig.add_subplot(N, 1, level + 1)
            plotcf2d(u, v, z, darken=0.3, limits=view)

        fig.savefig(
            os.path.join(
                path, "wavepacket_block_%s_level_%d_timestep_%07d.png" %
                (blockid, level, step)))
        close(fig)
Example #16
0
def transform_inhawp_to_eigen(iomin, iomout, blockidin=0, blockidout=0):
    """Compute the transformation to the eigenbasis for a wavepacket.
    Save the result back to a file.

    :param iomin: An :py:class:`IOManager: instance providing the simulation data.
    :param iomout: An :py:class:`IOManager: instance for saving the transformed data.
    :param blockidin: The data block from which the values are read. Default is `0`.
    :param blockidout: The data block to which the values are written. Default is `0`.
    """
    parameters = iomin.load_parameters()

    # Number of time steps we saved
    timesteps = iomin.load_inhomogwavepacket_timegrid(blockid=blockidin)
    nrtimesteps = timesteps.shape[0]

    # The potential used
    Potential = BlockFactory().create_potential(parameters)

    # Basis transformator
    BT = BasisTransformationHAWP(Potential)

    # Initialize a Hagedorn wavepacket with the data
    descr = iomin.load_inhomogwavepacket_description(blockid=blockidin)
    HAWP = BlockFactory().create_wavepacket(descr)

    iomout.add_inhomogwavepacket(descr,
                                 timeslots=nrtimesteps,
                                 blockid=blockidout)
    iomout.save_inhomogwavepacket_description(HAWP.get_description(),
                                              blockid=blockidout)

    BT.set_matrix_builder(HAWP.get_quadrature())

    # Basis shapes
    BS_descr = iomin.load_inhomogwavepacket_basisshapes()
    BS = {}
    for ahash, descr in BS_descr.iteritems():
        BS[ahash] = BlockFactory().create_basis_shape(descr)

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Compute eigentransform at timestep # " + str(step))

        # Retrieve simulation data
        params = iomin.load_inhomogwavepacket_parameters(timestep=step,
                                                         blockid=blockidin)
        hashes, coeffs = iomin.load_inhomogwavepacket_coefficients(
            timestep=step, get_hashes=True, blockid=blockidin)

        # Configure the wavepacket
        HAWP.set_parameters(params)
        HAWP.set_basis_shape([BS[int(ha)] for ha in hashes])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        BT.transform_to_eigen(HAWP)

        # Save the transformed packet
        # Pi
        iomout.save_inhomogwavepacket_parameters(HAWP.get_parameters(),
                                                 timestep=step,
                                                 blockid=blockidout)
        # Basis shapes (in case they changed!)
        for shape in HAWP.get_basis_shape():
            iomout.save_inhomogwavepacket_basisshapes(shape,
                                                      blockid=blockidout)
        # Coefficients
        iomout.save_inhomogwavepacket_coefficients(HAWP.get_coefficients(),
                                                   HAWP.get_basis_shape(),
                                                   timestep=step,
                                                   blockid=blockidout)
Example #17
0
def compute_evaluate_wavepackets(pp, iom, blockid=0, eigentrafo=True):
    """Evaluate a homogeneous Hagedorn wavepacket on a given grid for each timestep.

    :param pp: An :py:class:`ParameterProvider` instance providing the grid data.
    :param iom: An :py:class:`IOManager` instance providing the simulation data.
    :param blockid: The data block from which the values are read.
    :param eigentrafo: Whether or not do an eigentransformation before evaluation is done.
    """
    parameters = iom.load_parameters()
    if pp is None:
        pp = parameters

    # Number of time steps we saved
    timesteps = iom.load_wavepacket_timegrid(blockid=blockid)
    nrtimesteps = timesteps.shape[0]

    # Prepare the potential for basis transformations
    Potential = BlockFactory().create_potential(parameters)
    grid = BlockFactory().create_grid(pp)

    # We want to save wavefunctions, thus add a data slot to the data file
    d = {"ncomponents": parameters["ncomponents"],
         "number_nodes": pp["number_nodes"],
         "dimension": parameters["dimension"]}
    iom.add_grid(d, blockid=blockid)
    iom.add_wavefunction(d, timeslots=nrtimesteps, flat=True, blockid=blockid)

    iom.save_grid(grid.get_nodes(), blockid=blockid)

    # Initialize a Hagedorn wavepacket with the data
    descr = iom.load_wavepacket_description(blockid=blockid)
    HAWP = BlockFactory().create_wavepacket(descr)

    # Basis transformator
    if eigentrafo is True:
        BT = BasisTransformationHAWP(Potential)
        BT.set_matrix_builder(HAWP.get_innerproduct())

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

    WF = WaveFunction(parameters)
    WF.set_grid(grid)

    # Iterate over all timesteps
    for i, step in enumerate(timesteps):
        print(" Evaluating homogeneous wavepacket at timestep %d" % step)

        # Retrieve simulation data
        params = iom.load_wavepacket_parameters(timestep=step, blockid=blockid, key=("q", "p", "Q", "P", "S", "adQ"))
        hashes, coeffs = iom.load_wavepacket_coefficients(timestep=step, get_hashes=True, blockid=blockid)

        # Configure the wavepacket
        HAWP.set_parameters(params, key=("q", "p", "Q", "P", "S", "adQ"))
        HAWP.set_basis_shapes([BS[int(ha)] for ha in hashes])
        HAWP.set_coefficients(coeffs)

        # Transform to the eigenbasis.
        if eigentrafo is True:
            BT.transform_to_eigen(HAWP)

        # Evaluate the wavepacket
        values = HAWP.evaluate_at(grid, prefactor=True)
        WF.set_values(values)

        # Save the wave function
        iom.save_wavefunction(WF.get_values(), timestep=step, blockid=blockid)