Exemplo n.º 1
0
def test_squeeze(sc):

    from numpy import ones as npones

    x = npones((1, 2, 1, 4))
    b = ones((1, 2, 1, 4), sc, axis=0)
    assert allclose(b.squeeze().toarray(), x.squeeze())
    assert allclose(b.squeeze((0, 2)).toarray(), x.squeeze((0, 2)))
    assert allclose(b.squeeze(0).toarray(), x.squeeze(0))
    assert allclose(b.squeeze(2).toarray(), x.squeeze(2))
    assert b.squeeze().split == 0
    assert b.squeeze((0, 2)).split == 0
    assert b.squeeze(2).split == 1

    x = npones((1, 2, 1, 4))
    b = ones((1, 2, 1, 4), sc, axis=(0, 1))
    assert allclose(b.squeeze().toarray(), x.squeeze())
    assert allclose(b.squeeze((0, 2)).toarray(), x.squeeze((0, 2)))
    assert allclose(b.squeeze(0).toarray(), x.squeeze(0))
    assert allclose(b.squeeze(2).toarray(), x.squeeze(2))
    assert b.squeeze().split == 1
    assert b.squeeze((0, 2)).split == 1
    assert b.squeeze(2).split == 2

    x = npones((1, 1, 1, 1))
    b = ones((1, 1, 1, 1), sc, axis=(0, 1))
    assert allclose(b.squeeze().toarray(), x.squeeze())
Exemplo n.º 2
0
def test_squeeze(sc):

    from numpy import ones as npones

    x = npones((1, 2, 1, 4))
    b = ones((1, 2, 1, 4), sc, axis=0)
    assert allclose(b.squeeze().toarray(), x.squeeze())
    assert allclose(b.squeeze((0, 2)).toarray(), x.squeeze((0, 2)))
    assert allclose(b.squeeze(0).toarray(), x.squeeze(0))
    assert allclose(b.squeeze(2).toarray(), x.squeeze(2))
    assert b.squeeze().split == 0
    assert b.squeeze((0, 2)).split == 0
    assert b.squeeze(2).split == 1

    x = npones((1, 2, 1, 4))
    b = ones((1, 2, 1, 4), sc, axis=(0, 1))
    assert allclose(b.squeeze().toarray(), x.squeeze())
    assert allclose(b.squeeze((0, 2)).toarray(), x.squeeze((0, 2)))
    assert allclose(b.squeeze(0).toarray(), x.squeeze(0))
    assert allclose(b.squeeze(2).toarray(), x.squeeze(2))
    assert b.squeeze().split == 1
    assert b.squeeze((0, 2)).split == 1
    assert b.squeeze(2).split == 2

    x = npones((1, 1, 1, 1))
    b = ones((1, 1, 1, 1), sc, axis=(0, 1))
    assert allclose(b.squeeze().toarray(), x.squeeze())
Exemplo n.º 3
0
def FillNC(root_grp_ptr, scene_location):
    retGps = NT("returnGroups",  "calGrp, productsGrp, navGrp, slaGrp, periodGrp")
    root_grp_ptr.createDimension('samples', 512)
    root_grp_ptr.createDimension('scan_lines', 2000)
    root_grp_ptr.createDimension('bands', 128)
    root_grp_ptr.instrument = 'HICO'
    root_grp_ptr.institution = 'NASA Goddard Space Flight Center'
    root_grp_ptr.resolution = '100m'
    root_grp_ptr.location_description = scene_location
    root_grp_ptr.license = 'http://science.nasa.gov/earth-science/earth-science-data/data-information-policy/'
    root_grp_ptr.naming_authority = 'gov.nasa.gsfc.sci.oceandata'
    root_grp_ptr.date_created = DT.strftime(DT.utcnow(), '%Y-%m-%dT%H:%M:%SZ')
    root_grp_ptr.creator_name = 'NASA/GSFC'
    root_grp_ptr.creator_email = '*****@*****.**'
    root_grp_ptr.publisher_name = 'NASA/GSFC'
    root_grp_ptr.publisher_url = 'http_oceancolor.gsfc.nasa.gov'
    root_grp_ptr.publisher_email = '*****@*****.**'
    root_grp_ptr.processing_level = 'L1B'
    nav_grp = root_grp_ptr.createGroup('navigation')
    nav_vars = list()
    nav_vars.append(nav_grp.createVariable('sensor_zenith', 'f4', ('scan_lines', 'samples',)))
    nav_vars.append(nav_grp.createVariable('solar_zenith', 'f4', ('scan_lines', 'samples',)))
    nav_vars.append(nav_grp.createVariable('sensor_azimuth', 'f4', ('scan_lines', 'samples',)))
    nav_vars.append(nav_grp.createVariable('solar_azimuth', 'f4', ('scan_lines', 'samples',)))
    nav_vars.append(nav_grp.createVariable('longitudes', 'f4', ('scan_lines', 'samples',)))
    nav_vars.append(nav_grp.createVariable('latitudes', 'f4', ('scan_lines', 'samples',)))
    for var in nav_vars:
        var.units = 'degrees'
        var.valid_min = -180
        var.valid_max = 180
        var.long_name = var.name.replace('_', ' ').rstrip('s')
    retGps.navGrp = nav_grp
    retGps.productsGrp = root_grp_ptr.createGroup('products')
    lt = retGps.productsGrp.createVariable('Lt', 'u2', ('scan_lines',
                                                        'samples', 'bands'))
    lt.scale_factor = float32([0.02])
    lt.add_offset = float32(0)
    lt.units = "W/m^2/micrometer/sr"
    # lt.valid_range = nparray([0, 16384], dtype='u2')
    lt.long_name = "HICO Top of Atmosphere"
    lt.wavelength_units = "nanometers"
    # lt.createVariable('fwhm', 'f4', ('bands',))
    lt.fwhm = npones((128,), dtype='f4') * -1
    # wv = lt.createVariable('wavelengths', 'f4', ('bands',))
    lt.wavelengths = npones((128,), dtype='f4')
    lt.wavelength_units = "nanometers"
    retGps.slaGrp = root_grp_ptr.createGroup('scan_line_attributes')
    retGps.slaGrp.createVariable('scan_quality_flags', 'u1', ('scan_lines',
                                                              'samples'))
    # Create metadata group and sub-groups
    meta_grp = root_grp_ptr.createGroup('metadata')
    pl_info_grp = meta_grp.createGroup("FGDC/Identification_Information/Platform_and_Instrument_Identification")
    pl_info_grp.Instrument_Short_Name = "hico"
    prc_lvl_grp = meta_grp.createGroup("FGDC/Identification_Information/Processing_Level")
    prc_lvl_grp.Processing_Level_Identifier = "Level-1B"
    retGps.periodGrp = meta_grp.createGroup("FGDC/Identification_Information/Time_Period_of_Content")
    # fill HICO group
    retGps.calGrp = meta_grp.createGroup("HICO/Calibration")
    return retGps
Exemplo n.º 4
0
def test_ones(sc):

    from numpy import ones as npones
    x = npones((2, 3, 4))
    b = ones((2, 3, 4), sc)
    assert allclose(x, b.toarray())

    x = npones(5)
    b = ones(5, sc)
    assert allclose(x, b.toarray())
Exemplo n.º 5
0
def test_astype(sc):
    
    from numpy import ones as npones
    
    a = npones(2**8, dtype=int64)
    b = array(a, sc, dtype=int64)
    c = b.astype(bool)
    assert c.dtype == dtype(bool)
    dtypes = c._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(bool)
        
    b = ones((100, 100), sc, dtype=int64)
    c = b.astype(bool)
    assert c.dtype == dtype(bool)
    dtypes = c._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(bool)

    b = ones((100, 100), sc)
    c = b.astype(bool)
    assert c.dtype == dtype(bool)
    dtypes = c._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(bool)
Exemplo n.º 6
0
 def __init__(self, leaf_num: int, ancestor_num: int, gene_num: int,
              leaves: List[List[int]], all_paths: List[PGMPathForAGenome],
              medians: List[MedianData], nodes_int: ndarray,
              nodes_str: List[str]):
     """
     Parameters
     ----------
     leaf_num : int
         Number of leaves in the tree
     ancestor_num : int
         Number of ancestors (medians) in the tree
     gene_num : int
         Total number of genes in the tree
     leaves : List[ndarray]
         List of each leaf for each genome in the tree (in relation to the median)
     all_paths : List[PGMPathForAGenome]
         List of all paths for each genome in the tree
     medians : List[MedianData]
         List of all medians in the tree
     nodes_int : ndarray
         List of the integer representations of each node
     nodes_str : List[str]
         List of the string representations of each node
     """
     self.leaf_num: int = leaf_num
     self.changed: ndarray = npones(ancestor_num)
     self.gene_num: int = gene_num
     self.leaves: List[List[int]] = leaves
     self.all_paths: List[PGMPathForAGenome] = all_paths
     self.medians: List[MedianData] = medians
     self.nodes_int: ndarray = nodes_int
     self.nodes_str: List[str] = nodes_str
Exemplo n.º 7
0
def val2vecParams(N, hamParams):
    # Extract values
    if not isinstance(hamParams[0], (collections.Sequence, npndarray)):
        a = float(hamParams[0])
        aVec = npzeros(N, dtype=float_)
        aVec[0] = a
    else:
        aVec = a
    if not isinstance(hamParams[1], (collections.Sequence, npndarray)):
        g = float(hamParams[1])
        gVec = npzeros(N, dtype=float_)
        gVec[0] = g
    else:
        gVec = g
    if not isinstance(hamParams[2], (collections.Sequence, npndarray)):
        p = float(hamParams[2])
        pVec = p * npones(N, dtype=float_)
    else:
        pVec = p
    if not isinstance(hamParams[3], (collections.Sequence, npndarray)):
        q = float(hamParams[3])
        qVec = q * npones(N, dtype=float_)
    else:
        qVec = q
    if not isinstance(hamParams[4], (collections.Sequence, npndarray)):
        b = float(hamParams[4])
        bVec = npzeros(N, dtype=float_)
        bVec[-1] = b
    else:
        bVec = b
    if not isinstance(hamParams[5], (collections.Sequence, npndarray)):
        d = float(hamParams[5])
        dVec = npzeros(N, dtype=float_)
        dVec[-1] = d
    else:
        dVec = d
    if not isinstance(hamParams[6], (collections.Sequence, npndarray)):
        s = float(hamParams[6])
        sVec = s * npones(N, dtype=float_)
    else:
        sVec = s
    # Convert to vectors
    returnParams = (aVec, gVec, pVec, qVec, bVec, dVec, sVec)
    return returnParams
Exemplo n.º 8
0
def test_stacked_shape_inference(sc):

    from numpy import ones as npones

    a = ones((100, 2), sc)
    a._rdd = a._rdd.partitionBy(2)
    s = a.stack(5)
    n = s.tordd().count()

    # operations that preserve keys
    assert s.map(lambda x: x * 2).unstack().shape == (100, 2)
    assert s.map(lambda x: x.sum(axis=1)).unstack().shape == (100, )
    assert s.map(lambda x: tile(x, (1, 2))).unstack().shape == (100, 4)

    # operations that create new keys
    assert s.map(lambda x: npones((2, 2))).unstack().shape == (n, 2, 2)
    assert s.map(lambda x: x.sum(axis=0)).unstack().shape == (n, 2)
    assert s.map(lambda x: asarray([2])).unstack().toarray().shape == (n, 1)
    assert s.map(lambda x: asarray(2)).unstack().toarray().shape == (n, )

    # composing functions works
    assert s.map(lambda x: x * 2).map(lambda x: x * 2).unstack().shape == (100,
                                                                           2)
    assert s.map(lambda x: x * 2).map(lambda x: npones(
        (2, 2))).unstack().shape == (n, 2, 2)
    assert s.map(lambda x: npones((2, 2))).map(
        lambda x: x * 2).unstack().shape == (n, 2, 2)

    # check the result
    assert allclose(
        s.map(lambda x: x.sum(axis=1)).unstack().toarray(),
        npones(100) * 2)
    assert allclose(
        s.map(lambda x: tile(x, (1, 2))).unstack().toarray(), npones((100, 4)))

    with pytest.raises(ValueError):
        s.map(lambda x: 2)

    with pytest.raises(ValueError):
        s.map(lambda x: None)

    with pytest.raises(RuntimeError):
        s.map(lambda x: 1 / 0)
Exemplo n.º 9
0
def test_stacked_shape_inference(sc):

    from numpy import ones as npones

    a = ones((100, 2), sc)
    a._rdd = a._rdd.partitionBy(2)
    s = a.stack(5)
    n = s.tordd().count()

    # operations that preserve keys
    assert s.map(lambda x: x * 2).unstack().shape == (100, 2)
    assert s.map(lambda x: x.sum(axis=1)).unstack().shape == (100,)
    assert s.map(lambda x: tile(x, (1, 2))).unstack().shape == (100, 4)

    # operations that create new keys
    assert s.map(lambda x: npones((2, 2))).unstack().shape == (n, 2, 2)
    assert s.map(lambda x: x.sum(axis=0)).unstack().shape == (n, 2)
    assert s.map(lambda x: asarray([2])).unstack().toarray().shape == (n, 1)
    assert s.map(lambda x: asarray(2)).unstack().toarray().shape == (n,)

    # composing functions works
    assert s.map(lambda x: x * 2).map(lambda x: x * 2).unstack().shape == (100, 2)
    assert s.map(lambda x: x * 2).map(lambda x: npones((2, 2))).unstack().shape == (n, 2, 2)
    assert s.map(lambda x: npones((2, 2))).map(lambda x: x * 2).unstack().shape == (n, 2, 2)

    # check the result
    assert allclose(s.map(lambda x: x.sum(axis=1)).unstack().toarray(), npones(100) * 2)
    assert allclose(s.map(lambda x: tile(x, (1, 2))).unstack().toarray(), npones((100, 4)))

    with pytest.raises(ValueError):
        s.map(lambda x: 2)

    with pytest.raises(ValueError):
        s.map(lambda x: None)

    with pytest.raises(RuntimeError):
        s.map(lambda x: 1/0)
Exemplo n.º 10
0
    def ma(self, tap=3):

        data = self.get_amp()
        data[0] = 0

        from numpy import convolve
        from numpy import ones as npones
        # ma = [1. / tap] * tap
        m = npones(tap) / tap

        res = convolve(data, m, "same")

        Spec = SpectrumData(res, self.get_xdata())
        Spec._fs = self._fs

        return Spec
Exemplo n.º 11
0
    def ma(self, tap=3):

        data = self.get_amp()
        data[0] = 0

        from numpy import convolve
        from numpy import ones as npones
        # ma = [1. / tap] * tap
        m = npones(tap) / tap

        res = convolve(data, m, "same")

        Spec = SpectrumData(res, self.get_xdata())
        Spec._fs = self._fs

        return Spec
Exemplo n.º 12
0
def test_dtype(sc):

    a = arange(2 ** 8, dtype=int64)
    b = array(a, sc, dtype=int64)
    assert a.dtype == b.dtype
    assert b.dtype == dtype(int64)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(int64)

    a = arange(2.0 ** 8)
    b = array(a, sc)
    assert a.dtype == b.dtype
    assert b.dtype == dtype(float64)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(float64)

    a = arange(2 ** 8)
    b = array(a, sc)
    assert a.dtype == b.dtype
    assert b.dtype == dtype(int64)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(int64)

    from numpy import ones as npones

    a = npones(2 ** 8, dtype=bool)
    b = array(a, sc)
    assert a.dtype == b.dtype
    assert b.dtype == dtype(bool)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(bool)

    b = ones(2 ** 8, sc)
    assert b.dtype == dtype(float64)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(float64)

    b = ones(2 ** 8, sc, dtype=bool)
    assert b.dtype == dtype(bool)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(bool)
Exemplo n.º 13
0
def test_dtype(sc):

    a = arange(2**8, dtype=int64)
    b = array(a, sc, dtype=int64)
    assert a.dtype == b.dtype
    assert b.dtype == dtype(int64)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(int64)
    
    a = arange(2.0**8)
    b = array(a, sc)
    assert a.dtype == b.dtype
    assert b.dtype == dtype(float64)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(float64)

    a = arange(2**8)
    b = array(a, sc)
    assert a.dtype == b.dtype
    assert b.dtype == dtype(int64)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(int64)

    from numpy import ones as npones
    a = npones(2**8, dtype=bool)
    b = array(a, sc)
    assert a.dtype == b.dtype
    assert b.dtype == dtype(bool)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(bool)

    b = ones(2**8, sc)
    assert b.dtype == dtype(float64)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(float64)

    b = ones(2**8, sc, dtype=bool)
    assert b.dtype == dtype(bool)
    dtypes = b._rdd.map(lambda x: x[1].dtype).collect()
    for dt in dtypes:
        assert dt == dtype(bool)
Exemplo n.º 14
0
def dmrg(mpo,
         mps=None,
         mpsl=None,
         env=None,
         envl=None,
         mbd=10,
         tol=1.e-5,
         max_iter=10,
         min_iter=0,
         noise=0.,
         mps_subdir='mps',
         env_subdir='env',
         mpsl_subdir='mpsl',
         envl_subdir='envl',
         nStates=2,
         dtype=complex_,
         fixed_bd=False,
         alg='davidson',
         return_state=False,
         return_env=False,
         return_entanglement=False,
         return_wgt=False,
         orthonormalize=False,
         state_avg=True,
         left=False,
         start_gauge=0,
         end_gauge=0):
    """
    Run the one-site DMRG algorithm

    Args:
        mpo : 1D Array
            An array that contains a list of mpos, each of which 
            is a list with an array for each site in the lattice
            representing the mpo at that site.

    Kwargs:
        mps : 1D Array of Matrix Product States
            The initial guess for the mps (stored as an mpsList
            as specified in cyclomps.tools.mps_tools)
            Default : None (mps0 will be random)
        mpsl : 1D Array of Matrix Product States
            The initial guess for the left mps (stored as an mpsList
            as specified in cyclomps.tools.mps_tools)
            Default : None (mps0 will be random)
        env : 1D Array of an environment
            The initial environment for mps (stored as an envList
            as specified in cyclomps.tools.env_tools)
            Default : None (env will be built in computation)
        envl : 1D Array of an environment
            The initial environment for the left mps (stored as an envList
            as specified in cyclomps.tools.env_tools)
            Default : None (env will be built in computation)
        mbd : int or 1D Array of ints
            The maximum bond dimension for the mps. 
            If this is a single int, then the bond dimension
            will be held constant for all sweeps. Otherwise, the 
            bond dimension will be incremented after max_iter sweeps
            or until the tolerance is reached.
            sweeps. (Note that if max_iter and/or tol is a list, we 
            require len(max_iter) == len(mbd) == len(tol), and the 
            maximum number of iterations or convergence tolerance
            changes with the retained maximum bond dimension.)
            Default : 10
        tol : int or 1D Array of ints
            The relative convergence tolerance. This may be a list, 
            meaning that as the mbd is increased, different tolerances
            are specified.
            Default : 1.e-5
        max_iter : int or 1D Array of ints
            The maximum number of iterations for each mbd
            Default : 10
        min_iter : int or 1D Array of ints
            The minimum number of iterations for each mbd
            Default : 0
        noise : float or 1D Array of floats
            The magnitude of the noise added to the mbd to prevent
            getting stuck in a local minimum
            !! NOT IMPLEMENTED !!
            Default : 0.
        mps_subdir : string
            The subdirectory under CALC_DIR (specified in cyclomps.tools.params)
            where the mps will be saved. 
            Default : 'mps'
        mpsl_subdir : string
            The subdirectory under CALC_DIR (specified in cyclomps.tools.params)
            where the left mps will be saved.
            Default : 'mpsl'
        env_subdir : string
            The subdirectory under CALC_DIR (specified in cyclomps.tools.params)
            where the environment will be saved.
            Default : 'env'
        envl_subdir : string
            The subdirectory under CALC_DIR (specified in cyclomps.tools.params)
            where the environment for the left mps will be saved.
            Default : 'envl'
        nStates : int
            The number of retained states
            Default : 2
        dtype : dtype
            The data type for the mps and env
            Default : np.complex_
        fixed_bd : bool
            This ensures that all bond dimensions are constant
            throughout the MPS, i.e. mps[0].dim = (1 x d[0] x mbd)
            instead of mps[0].dim = (1 x d[0] x d[0]), and so forth.
            Default : False
        alg : string
            The algorithm that will be used. Available options are
            'arnoldi', 'exact', and 'davidson', current default is 
            'davidson'.
            Default : 'davidson'
        return_state : bool
            Return the resulting mps list
            Default : False
        return_env : bool
            Return the resulting env list
            Default : False
        return_entanglement : bool
            Return the entanglement entropy and entanglement spectrum
            Default : False
        return_wgt : bool
            Return the discarded weights
            Default : False
        orthonormalize : bool
            Specify whether to orthonormalize eigenvectors after solution
            of eigenproblem. This will cause problems for all systems
            unless the eigenstates being orthonormalized are degenerate.
            Default : False
        state_avg : bool
            Specify whether to use the state averaging procedure to target
            multiple states when doing the renormalization step.
            Default : True
            !! ONLY STATE AVG IS IMPLEMENTED !!
        left : bool
            If True, then we calculate the left and right eigenstate
            otherwise, only the right.
            Default : False
        start_gauge : int
            The site at which the gauge should (or is) located in the 
            initial mps.
            Default : 0
        end_gauge : int
            The site at which the gauge should be located when the 
            mps is returned.
            Default : 0

    Returns:
        E : 1D Array
            The energies for the number of states targeted
        EE : 1D Array
            The entanglement entropy for the states targeted
            Returned only if return_entanglement == True
        EEs : 1D Array of 1D Arrays
            The entanglement entropy spectrum for the states targeted
            Returned only if return_entanglement == True
        mps : 1D Array of Matrix Product States
            The resulting matrix product state list
            Returned only if return_state == True
        env : 1D Array of an environment
            The resulting environment list
    """
    t0 = time.time()
    mpiprint(0, '\n\nStarting DMRG one-site calculation')
    mpiprint(0, '#' * 50)

    # Check inputs for problems
    if not hasattr(mbd, '__len__'): mbd = nparray([mbd])
    if not hasattr(tol, '__len__'):
        tol = tol * npones(len(mbd))
    else:
        assert (len(mbd) == len(tol)), 'Lengths of mbd and tol do not agree'
    if not hasattr(max_iter, '__len__'):
        max_iter = max_iter * npones(len(mbd))
    else:
        assert (len(max_iter) == len(mbd)
                ), 'Lengths of mbd and max_iter do not agree'
    if not hasattr(min_iter, '__len__'):
        min_iter = min_iter * npones(len(mbd))
    else:
        assert (len(min_iter) == len(mbd)
                ), 'Lengths of mbd and min_iter do not agree'

    # --------------------------------------------------------------------------------
    # Solve for Right Eigenvector
    # --------------------------------------------------------------------------------
    # Determine local bond dimensions from mpo
    d = mpo_local_dim(mpo)

    # Create structures to save results
    return_E = npzeros((len(mbd), nStates))
    return_EE = npzeros((len(mbd), nStates))
    return_EEs = npzeros((len(mbd), nStates, max(mbd)))
    mps_res = []
    env_res = []
    # Loop through all maximum bond dimensions
    for mbd_ind, mbdi in enumerate(mbd):
        mpiprint(1, '\n' + '/' * 50)
        mpiprint(1, 'Starting Calculation for mbd = {}'.format(mbdi))

        # Set up initial mps
        if mbd_ind == 0:
            if mps is None:
                # There is no previous guess to build on
                mps = create_mps_list(d,
                                      mbdi,
                                      nStates,
                                      dtype=dtype,
                                      fixed_bd=fixed_bd,
                                      subdir=mps_subdir + '_mbd' + str(mbdi) +
                                      '_')
                # Make sure it is in correct canonical form
                mps = make_mps_list_right(mps)
                mps = move_gauge(mps, 0, start_gauge)
        else:
            # Increase the maximum bond dim of the previous system
            mps = increase_bond_dim(mps, mbdi, fixed_bd=fixed_bd)

        # Set up initial env
        if mbd_ind == 0:
            if env is None:
                env = calc_env(mps,
                               mpo,
                               dtype=dtype,
                               subdir='env_mbd' + str(mbdi) + '_')
        else:
            env = calc_env(mps,
                           mpo,
                           dtype=dtype,
                           gSite=end_gauge,
                           subdir='env_mbd' + str(mbdi) + '_')

        # Run the DMRG Sweeps
        outputr = sweeps(mps,
                         mpo,
                         env,
                         max_iter=max_iter[mbd_ind],
                         min_iter=min_iter[mbd_ind],
                         tol=tol[mbd_ind],
                         alg=alg,
                         noise=noise,
                         orthonormalize=orthonormalize,
                         state_avg=state_avg,
                         start_gauge=start_gauge,
                         end_gauge=end_gauge)

        # Collect results
        E = outputr[0]
        EE = outputr[1]
        EEs = outputr[2]
        wgt = outputr[3]
    # --------------------------------------------------------------------------------
    # Solve for Left Eigenvector
    # --------------------------------------------------------------------------------
    if left:
        mpiprint(0, '#' * 50)
        mpiprint(0, 'Left State')
        mpiprint(0, '#' * 50)
        # Create left mpo
        mpol = mpo_conj_trans(mpo)

        # Run this same function, but now with this new left mpo
        outputl = dmrg(mpo,
                       mps=mpsl,
                       env=envl,
                       mbd=mbd,
                       tol=tol,
                       max_iter=max_iter,
                       min_iter=min_iter,
                       noise=noise,
                       mps_subdir=mpsl_subdir,
                       env_subdir=envl_subdir,
                       nStates=nStates,
                       dtype=dtype,
                       fixed_bd=fixed_bd,
                       alg=alg,
                       return_state=True,
                       return_env=True,
                       return_entanglement=True,
                       return_wgt=True,
                       orthonormalize=orthonormalize,
                       state_avg=state_avg,
                       left=False,
                       start_gauge=start_gauge,
                       end_gauge=end_gauge)

        # Collect results
        El = outputl[0]
        EEl = outputl[1]
        EEls = outputl[2]
        wgtl = outputl[3]
        mpsl = outputl[4]
        envl = outputl[5]

    # ---------------------------------------------------------------------------------
    # Wrap Up Calculation
    # ---------------------------------------------------------------------------------
    # Prin://arxiv.org/abs/1706.09537t time for dmrg procedure
    timeprint(1, 'Total time: {} s'.format(time.time() - t0))

    # Return results
    ret_list = [E]
    if left: ret_list += [El]
    if return_entanglement:
        ret_list += [EE, EEs]
        if left: ret_list += [EEl, EEls]
    if return_wgt:
        ret_list += [wgt]
        if left: ret_list += [wgtl]
    if return_state:
        ret_list += [mps]
        if left: ret_list += [mpsl]
    if return_env:
        ret_list += [env]
        if left: ret_list += [envl]
    return ret_list
Exemplo n.º 15
0
    def rep2(serie=[], option={}):
        n_serie = 10
        if type(serie) != int:
            # it's a list
            if len(serie) == 0:
                serie = range(0, n_serie)
            if len(serie) > n_serie:
                raise ExperimentalInfoError('Serie list is too long.')
            if max(serie) > n_serie:
                raise ExperimentalInfoError('Serie index out of range.')
        else:
            # it's a int
            if serie > n_serie:
                raise ExperimentalInfoError('Serie index out of range.')

        t_givrage = nparray([
            14,
            20,
            44,
            40,
            38,
            34,
            34,
            35,
            35,
            37,
        ])
        t_total = nparray([
            158,
            86,
            46,
            50,
            51,
            50,
            54,
            56,
            45,
            52,
        ])
        air_temperature = nparray([
            22.0,
            22.8,
            22.6,
            22.8,
            22.8,
            22.8,
            22.8,
            22.8,
            22.7,
            22.7,
        ])
        ca_left = nparray([0])

        ca_right = nparray([0])

        Tw = -7. * npones(n_serie)

        try:
            if option['wall temperature']:
                return Tw
        except Exception as e:
            pass

        ca = (ca_right + ca_left) / 2
        ca = nparray([
            60.,
            64.,
            79.,
            79.,
            79.,
            71.,
            76.,
            75.,
            72.,
            80.,
        ])

        return (t_givrage[serie], t_total[serie], air_temperature[serie],
                ca[serie])
Exemplo n.º 16
0
    def rep1(serie=[], option={}):
        n_serie = 10
        if type(serie) != int:
            # it's a list
            if len(serie) == 0:
                serie = range(0, n_serie)
            if len(serie) > n_serie:
                raise ExperimentalInfoError('Serie list is too long.')
            if max(serie) > n_serie:
                raise ExperimentalInfoError('Serie index out of range.')
        else:
            # it's a int
            if serie > n_serie:
                raise ExperimentalInfoError('Serie index out of range.')

        # === user entrance information === #
        t_givrage = nparray([
            40,
            43,
            51,
            46,
            46,
            38,
            80,
            76,
            70,
            npnan,
        ])
        t_total = nparray([120, 266, 177, 193, 329, 324, 80, 90, 70, 166])
        air_temperature = nparray(
            [20.6, 20.6, 21., 21.2, 21.2, 21.6, 21.6, 21.8, 21.5, 21.5])

        ca_left = nparray([0])

        ca_right = nparray([0])

        ca = (ca_left + ca_right) / 2

        ca = nparray([
            51.,
            78.,
            74.,
            76.,
            56.,
            62.,
            63.,
            75.,
            64.,
            81,
        ])
        Tw = -7. * npones(n_serie)

        # /!\ l'angle 9, 7 on été mesuré après début du givrage #
        try:
            if option['wall temperature']:
                return Tw
        except Exception as e:
            pass

        return (t_givrage[serie], t_total[serie], air_temperature[serie],
                ca[serie])
Exemplo n.º 17
0
Arquivo: tensor.py Projeto: guochu/RQC
def ones(shape, dtype=float, order='C'):
    return tensor(npones(shape, dtype=dtype, order=order))