def expectation_values_from_rdms(
    interactionrdm: str,
    qubit_operator: str,
    sort_terms: bool = False,
):
    operator = load_qubit_operator(qubit_operator)
    rdms = load_interaction_rdm(interactionrdm)
    expecval = get_expectation_values_from_rdms(rdms, operator, sort_terms=sort_terms)
    save_expectation_values(expecval, "expectation_values.json")
def test_get_expectation_values_from_rdms(interactionrdm, qubitoperator, sort_terms):
    expecval = get_expectation_values_from_rdms(
        interactionrdm, qubitoperator, sort_terms
    )
    assert len(expecval.values) == len(qubitoperator.terms)
    if not sort_terms:
        coeff = np.array(list(qubitoperator.terms.values()))
    else:
        terms_iterator = sorted(
            qubitoperator.terms.items(), key=lambda x: abs(x[1]), reverse=True
        )
        coeff = np.array([coefficient for _, coefficient in terms_iterator])

    energy_test = np.sum(coeff * expecval.values)
    energy_ref = np.real(interactionrdm.expectation(qubitoperator))
    assert math.isclose(energy_test, energy_ref)
    [
        (
            group_comeasureable_terms_greedy(h2_hamiltonian, False),
            ExpectationValues(np.ones(15)),
        ),
        (
            group_comeasureable_terms_greedy(h2_hamiltonian, False),
            ExpectationValues(np.zeros(15)),
        ),
        (
            group_comeasureable_terms_greedy(h2_hamiltonian, False),
            ExpectationValues(np.repeat(0.5, 15)),
        ),
        (
            group_comeasureable_terms_greedy(h2_hamiltonian, False),
            get_expectation_values_from_rdms(rdms, h2_hamiltonian, False),
        ),
        (
            group_comeasureable_terms_greedy(h2_hamiltonian, True),
            get_expectation_values_from_rdms(rdms, h2_hamiltonian, True),
        ),
        (
            group_comeasureable_terms_greedy(QubitOperator("2[]"), True),
            get_expectation_values_from_rdms(rdms, QubitOperator("2[]"), True),
        ),
    ],
)
def test_compute_group_variances_without_ref(groups, expecval):
    test_variances = compute_group_variances(groups, expecval)
    test_ham_variance = np.sum(test_variances)
    # Assemble H and compute its variances independently