Beispiel #1
0
    def build_initial_state(self, initial_state=[]):
        """ Build the initial density matrix for the atom.

            The default is for all of the population to be in |0> <0|.

            Args:
                rho0: a list or array of populations, length num_states.

            Returns:
                Qu.Qobj: A density matrix representing the initial

            Notes: 
                - The elements must sum to 1 (as this will be the trace of the 
                    density matrix).

        """

        if initial_state:
            if len(initial_state) != self.num_states:
                raise ValueError(
                    'initial_state must have num_states elements.')
            self.initial_state = qu.qzero(self.num_states)
            for i, g in enumerate(initial_state):
                self.initial_state += g * self.sigma(i, i)
        else:
            self.initial_state = self.sigma(0, 0)
        if not np.isclose(self.initial_state.tr(), 1.0):
            raise ValueError(
                'initial_state must have diagonal elements sum to 1.')

        # Initialise rho
        self.rho = self.initial_state

        return self.initial_state
Beispiel #2
0
def get_frem_Hs(qubits, part):
    """
    Turns input H and partition into valid
    QuTip Hx and Hz for both F and R partition.
    Input: isingH Hamiltonian and part(ition) dictionary
    Output: (HFx, HFz, HRx, HRz)
    """
    num_q = len(qubits)
    Rqubits = part['Rqubits']
    HF = part['HF']
    HFx = qt.tensor(*[qt.qzero(2) for n in range(num_q)])
    HFz = HFx.copy()
    HR = part['HR']
    HRx = HFx.copy()
    HRz = HFx.copy()
    for key in HR.keys():
        if key[0] == key[1]:
            if key[0] in Rqubits:
                HRx += nqubit_1pauli(qt.sigmax(), key[0], num_q)
                HRz += HR[key] * nqubit_1pauli(qt.sigmaz(), key[0], num_q)
            else:
                HFx += nqubit_1pauli(qt.sigmax(), key[0], num_q)
                HFz += HF[key] * nqubit_1pauli(qt.sigmaz(), key[0], num_q)
        else:
            HRz += HR[key] * nqubit_2pauli(qt.sigmaz(), qt.sigmaz(), key[0], key[1], num_q)
            HFz += HF[key] * nqubit_2pauli(qt.sigmaz(), qt.sigmaz(), key[0], key[1], num_q)
            
    return (HFx, HFz, HRx, HRz)
Beispiel #3
0
def _parametrize_solver_coefficients(metafunc):
    """
    Perform the parametrisation for test cases using a solver and some
    time-dependent coefficients.  This is necessary because not all solvers can
    accept all combinations of time-dependence specifications.
    """
    size = 10
    times = np.linspace(0, 5, 50)
    c_ops = [qutip.qzero(size)]
    solvers = [
        (qutip.sesolve, 'sesolve'),
        (functools.partial(qutip.mesolve, c_ops=c_ops), 'mesolve'),
        (functools.partial(qutip.mcsolve, c_ops=c_ops), "mcsolve"),
        (qutip.brmesolve, 'brmesolve'),
    ]
    # A list of (reference, test) pairs, where the reference is in function
    # form because that's the fastest, and the test is named type.
    coefficients = [
        ([_real_cos.spline(times)], "real-spline"),
        ([_real_cos.string(), _real_sin.spline(times)], "real-string,spline"),
        ([_real_cos.spline(times),
          _real_sin.function()], "real-spline,function"),
        ([_complex_pos.spline(times),
          _complex_neg.string()], "complex-spline,string"),
    ]

    def _valid_case(solver_id, coefficient_id):
        invalids = [
            "brmesolve" in solver_id and "function" in coefficient_id,
        ]
        return not any(invalids)

    def _make_case(solver, solver_id, coefficients, coefficient_id):
        marks = []
        if "brmesolve" in solver_id:
            # We must use the string as the reference type instead of the
            # function if brmesolve is in use.
            marks.append(pytest.mark.requires_cython)
            coefficients = [(c.string_coefficient, other)
                            for c, other in coefficients]
        id_ = "-".join([solver_id, coefficient_id])
        return pytest.param(solver,
                            coefficients,
                            size,
                            times,
                            id=id_,
                            marks=marks)

    cases = [
        _make_case(solver, solver_id, coefficients_, coefficient_id)
        for solver, solver_id in solvers
        for coefficients_, coefficient_id in coefficients
        if _valid_case(solver_id, coefficient_id)
    ]
    metafunc.parametrize(["solver", "coefficients", "size", "times"], cases)
Beispiel #4
0
def test_commutator():
    A = qutip.qeye(N)
    B = qutip.destroy(N)
    assert qutip.commutator(A, B) == qutip.qzero(N)

    sx = qutip.sigmax()
    sy = qutip.sigmay()
    assert qutip.commutator(sx, sy) / 2 == (qutip.sigmaz() * 1j)

    A = qutip.qeye(N)
    B = qutip.destroy(N)
    assert qutip.commutator(A, B, 'anti') == qutip.destroy(N) * 2

    sx = qutip.sigmax()
    sy = qutip.sigmay()
    assert qutip.commutator(sx, sy, 'anti') == qutip.qzero(2)

    with pytest.raises(TypeError) as e:
        qutip.commutator(sx, sy, 'something')
    assert str(e.value).startswith("Unknown commutator kind")
def compute_free_evolution_hamiltonian(nb_qubits, nb_drives, omega, omega0,
                                       hbar):
    H_res = qt.qzero([[2, 2]])

    for index_qubit in range(nb_qubits):
        H_qubit_tmp = qt.Qobj(np.zeros((2, 2)))

        for index_drive in range(nb_drives):
            delta = omega[index_drive] - omega0[index_qubit]
            H_qubit_tmp += -hbar * delta * (qt.sigmam() * qt.sigmap())

        H_res = H_res + compute_multiqbt_hamil(H_qubit_tmp, nb_qubits,
                                               index_qubit, 2)

    return H_res
Beispiel #6
0
 def test_coefficient_c_ops_3ls(self, dependence_3ls):
     # Calculate zero-delay HOM cross-correlation for incoherently pumped
     # three-level system, g2_ab[0] with gamma = 1.
     dimension = 3
     H = qutip.qzero(dimension)
     start = qutip.basis(dimension, 2)
     times = _3ls_times
     project_0_1 = qutip.projection(dimension, 0, 1)
     project_1_2 = qutip.projection(dimension, 1, 2)
     population_1 = qutip.projection(dimension, 1, 1)
     # Define the pi pulse to be when 99% of the population is transferred.
     rabi = np.sqrt(-np.log(0.01) / (_3ls_args['tp'] * np.sqrt(np.pi)))
     c_ops = [project_0_1, [rabi * project_1_2, dependence_3ls]]
     forwards = qutip.correlation_2op_2t(H,
                                         start,
                                         times,
                                         times,
                                         c_ops,
                                         project_0_1.dag(),
                                         project_0_1,
                                         args=_3ls_args)
     backwards = qutip.correlation_2op_2t(H,
                                          start,
                                          times,
                                          times,
                                          c_ops,
                                          project_0_1.dag(),
                                          project_0_1,
                                          args=_3ls_args,
                                          reverse=True)
     n_expect = qutip.mesolve(H,
                              start,
                              times,
                              c_ops,
                              args=_3ls_args,
                              e_ops=[population_1]).expect[0]
     correlation_ab = -forwards * backwards + _n_correlation(
         times, n_expect)
     g2_ab_0 = _trapz_2d(np.real(correlation_ab), times)
     assert abs(g2_ab_0 - 0.185) < 1e-2
Beispiel #7
0
 def __init__(self, op):
     # Operator decomposition
     dims = op.dims[0]
     op_decomposition = []
     for N in range(len(dims)+1):
         # N = 0 -> constant term
         # N = 1 -> single mode terms
         # N = 2 -> 2 mode interaction
         # and so forth...
         for inds in combinations(iterable=range(len(dims)), r=N):
             if inds: # This if statement is just there because ptrace and tensor does not work if inds is empty
                 h = op.ptrace(inds) / prod([d for i,d in enumerate(dims) if not i in inds])
                 # Figuring out tensor re-ordering
                 new_dims_order = [i for i in inds] + [j for j in range(len(dims)) if not j in inds] # This is the new order (inds[0], ind[1],..., notInds[0],...)
                 reorder = [new_dims_order.index(i) for i in range(len(new_dims_order))] # This restores old order
                 h_tensor = tensor([h]+[qeye(d) for i,d in enumerate(dims) if i not in inds]).permute(reorder) # Tensor product made in new_dims_order. Reordered by permute
             else:
                 h = op.tr()/prod(dims)
                 h_tensor = h*qeye(list(dims))
             op -= h_tensor
             op_decomposition.append([inds,h,h_tensor])
     if not op.tidyup()==qzero(list(dims)):
         warnings.warn("Decomposition seems to be bad!")
     self.decomp = op_decomposition
Beispiel #8
0
def test_zero_type():
    "Operator CSR Type: zero_oper"
    op = qzero(5)
    assert_equal(isspmatrix_csr(op.data), True)
def test_zero_type():
    "Operator CSR Type: zero_oper"
    op = qzero(5, [[5], [5]])
    assert_equal(isspmatrix_csr(op.data), True)
Beispiel #10
0
@pytest.mark.repeat(20)
@pytest.mark.parametrize("hermitian", [False, True], ids=['complex', 'real'])
def test_equivalent_to_matrix_element(hermitian):
    dimension = 20
    state = qutip.rand_ket(dimension, 0.3)
    op = qutip.rand_herm(dimension, 0.2)
    if not hermitian:
        op = op + 1j * qutip.rand_herm(dimension, 0.1)
    expected = (state.dag() * op * state).data[0, 0]
    assert abs(qutip.expect(op, state) - expected) < 1e-14


@pytest.mark.parametrize("solve", [
    pytest.param(qutip.sesolve, id="sesolve"),
    pytest.param(functools.partial(qutip.mesolve, c_ops=[qutip.qzero(2)]),
                 id="mesolve"),
])
def test_compatibility_with_solver(solve):
    e_ops = [getattr(qutip, 'sigma' + x)() for x in 'xyzmp']
    h = qutip.sigmax()
    state = qutip.basis(2, 0)
    times = np.linspace(0, 10, 101)
    options = qutip.Options(store_states=True)
    result = solve(h, state, times, e_ops=e_ops, options=options)
    direct, states = result.expect, result.states
    indirect = qutip.expect(e_ops, states)
    assert len(direct) == len(indirect)
    for direct_, indirect_ in zip(direct, indirect):
        assert len(direct_) == len(indirect_)
        assert isinstance(direct_, np.ndarray)
 def zero(self):
     """Returns the zero operator for the space
     """
     return qt.qzero(self.dims())
Beispiel #12
0
 def zero(self):
     """Returns the <code>Qobj</code> representation of the zero operator
     for the space, which takes any state identically to zero
     """
     return qt.qzero(self.dims())