def test_analyse_orders_from_file_row_csv(self):
     # arrange
     app_dir = os.path.dirname(__file__, )
     rel_path = 'supplychainpy/data.csv'
     abs_file_path = os.path.abspath(os.path.join(app_dir, '..', rel_path))
     # act
     d = model_inventory.analyse_orders_from_file_row(abs_file_path, z_value=Decimal(1.28),
                                                      reorder_cost=Decimal(400), file_type="csv")
     for row in d:
         if row['sku'] == 'KR202-209':
             std = row.get('standard_deviation')
     # assert
     self.assertTrue(isclose(Decimal(std), 976, abs_tol=2))
Beispiel #2
0
def _iterate_newton(func_list, func, deriv_func, x0, max_iter=200, tol=1e-08):
    """
    Iteration process of newton's method
    Parameters
    ----------
    func: function
        the function
    deriv_func: function
        the derivative of the function
    """

    xi = x0
    for i in range(1, max_iter + 1):
        xj = _iterate_newton_step(func, deriv_func, xi, tol)

        # failed
        if xj is None:
            return i, -100

        # close enough
        if cmath.isclose(xi, xj, rel_tol=0, abs_tol=tol):
            return i, xj
        if abs(func(xj)) >= abs(func(xi)):
            xi = xj
            xj = _iterate_robust_step(func_list, func, deriv_func, xi, tol)
            if xj is None:
                return i, -100

            # close enough
            if cmath.isclose(xi, xj, rel_tol=0, abs_tol=tol):
                return i, xj

        xi = xj
    xi = -100

    return i, xi
 def test_analyse_orders_from_file_row_csv(self):
     """"""
     d = model_inventory.analyse_orders_from_file_row(file_path=ABS_FILE_PATH['COMPLETE_CSV_SM'],
                                                      reorder_cost=Decimal(45),
                                                      z_value=Decimal(1.28),
                                                      file_type="csv",
                                                      retail_price=Decimal(30),
                                                      currency='USD')
     std = 0
     for row in d:
         if row.get('sku') == 'KR202-210':
             std = row.get('standard_deviation')
             break
     # assert
     self.assertTrue(isclose(Decimal(std), 950, abs_tol=2))
Beispiel #4
0
 def test_analyse_orders_from_file_row_csv(self):
     """"""
     d = model_inventory.analyse_orders_from_file_row(
         file_path=ABS_FILE_PATH['COMPLETE_CSV_SM'],
         reorder_cost=Decimal(45),
         z_value=Decimal(1.28),
         file_type="csv",
         retail_price=Decimal(30),
         currency='USD')
     std = 0
     for row in d:
         if row.get('sku') == 'KR202-210':
             std = row.get('standard_deviation')
             break
     # assert
     self.assertTrue(isclose(Decimal(std), 950, abs_tol=2))
Beispiel #5
0
def roots(a, b, c):
    """Computes the roots of the ax^2 + bx + x = 0 polynomial.
	
	Pre: -
	Post: Returns a tuple with zero, one or two elements corresponding
		to the roots of the ax^2 + bx + c polynomial.
	"""
    rho = b**2 - 4 * a * c

    if rho < 0:
        return ()

    elif isclose(rho, 0, rel_tol=1e-9):
        return (-b / (2 * a), )

    else:
        return ((-b + sqrt(rho)) / 2 * a, (-b - sqrt(rho) / 2 * a))
def GetAggNums(file, times, fnevals, algo):
    data = pd.read_csv(file)
    c_values = []
    c_iters = []
    iters = []
    sizes = []
    c_fnevals = []
    c_times = []
    total_times = []
    total_evals = []

    for size in data['size'].unique():
        filtered_data = data[data['size'] == size]
        max_value = np.max(filtered_data['fn_value'])
        close_match_indxs = filtered_data[filtered_data['fn_value'] ==
                                          max_value].index
        converged_index = np.min(np.array(close_match_indxs))
        assert (cmath.isclose(max_value,
                              filtered_data.loc[converged_index]['fn_value']))
        converged_iter = filtered_data.loc[converged_index]['iters']
        total_iters = filtered_data['iters'].max()
        total_eval = fnevals.loc[size][algo]
        total_time = times.loc[size][algo]

        c_time = converged_iter * total_time / total_iters
        c_evals = converged_iter * total_eval / total_iters

        sizes.append(size)
        iters.append(total_iters)
        c_iters.append(converged_iter)
        c_values.append(max_value)
        total_times.append(total_time)
        total_evals.append(total_eval)
        c_fnevals.append(c_evals)
        c_times.append(c_time)

    return pd.DataFrame({
        'size': sizes,
        "total_iters": iters,
        'converged_iters': c_iters,
        'value': c_values,
        'converged_evals': c_fnevals,
        'converged_time': c_times,
        'total_evals': total_evals,
        'total_time': total_times
    })
 def test_isclose(self):
     import cmath
     raises(ValueError, cmath.isclose, 2, 3, rel_tol=-0.5)
     raises(ValueError, cmath.isclose, 2, 3, abs_tol=-0.5)
     for z in [
             0.0, 1.0, 1j,
             complex("inf"),
             complex("infj"),
             complex("-inf"),
             complex("-infj")
     ]:
         assert cmath.isclose(z, z)
     assert not cmath.isclose(complex("infj"), complex("-infj"))
     assert cmath.isclose(1j, 1j + 1e-12)
     assert not cmath.isclose(1j, 1j + 1e-12, rel_tol=1e-13)
     assert not cmath.isclose(100000j, 100001j)
     assert cmath.isclose(100000j, 100001j, rel_tol=1e-4)
     assert cmath.isclose(100000j, 100001j, abs_tol=1.5)
     assert not cmath.isclose(100000j, 100001j, abs_tol=0.5)
Beispiel #8
0
def test_all():
    funcs = [R, C, W, A, E, G]
    freqs = [0.001, 1.0, 1000]
    correct_vals = [[0.1, 0.1, 0.1],
                    [
                        -1591.5494309189532j, -1.5915494309189535j,
                        -0.0015915494309189533j
                    ],
                    [(0.033333332999112786 - 79.57747433847442j),
                     (0.03300437046673635 - 0.08232866785870396j),
                     (0.0019947114020071634 - 0.0019947114020071634j)],
                    [(0.007926654595212022 - 0.007926654595212022j),
                     (0.25066282746310004 - 0.25066282746310004j),
                     (7.926654595212021 - 7.926654595212021j)],
                    [(26.216236841407248 - 8.51817171087997j),
                     (6.585220960717244 - 2.139667994182814j),
                     (1.6541327179718126 - 0.537460300252313j)],
                    [(0.22352409811104385 - 0.0035102424186296594j),
                     (0.028647452492431665 - 0.02775008505285708j),
                     (0.0008920762553460424 - 0.0008920478601288429j)]]
    input_vals = [0.1, 0.2]
    inputs = [1, 1, 2, 1, 2, 2]
    count = 0
    for f in funcs:
        val = f(input_vals[:inputs[count]], freqs)
        for j in range(len(correct_vals[count])):
            assert cmath.isclose(val[j], correct_vals[count][j])

        # check for typing:
        try:
            f(1, 2)
        except (AssertionError):
            pass
        else:
            raise Exception('unhandled error occurred')
        # test for handling more wrong inputs
        try:
            f(['hi'], ['yes', 'hello'])
        except (AssertionError):
            pass
        else:
            raise Exception('unhandled error occurred')
        return
        count += 1
    pass
Beispiel #9
0
def power(a, b, max_num_roots=10):
    """Computes a set of solutions for `a**b` for real numbers `a, b` by
    finding ALL complex solutions (roots of `x**(1/b) = a`). 
    
    Whee!!"""
    pi = cmath.pi
    isclose = lambda x, y: cmath.isclose(x, y, abs_tol=1e-10)
    roots = []

    # normie math.pow
    pos_result = math.pow(abs(a), b)

    # the start angle of the exponential but including j
    first_pwr = 1j * b * pi

    # 1 if a is negative, 0 otherwise
    # determines whether we rotate all solutions by pi
    phase_shift = a < 0

    #   |a|^b * sign(a)^b
    # = |a|^b * e^(j * b * pi * (2k + [a < 0]? ))
    #    for k in range [0, max_num_roots) or until all
    #    solutions are already found (e.g. the roots become periodic)

    for k in range(0, max_num_roots):

        # calculate complex root according to above expression
        root = pos_result * cmath.exp(first_pwr * (2 * k + phase_shift))

        # stop if the exponential has completed a period
        if k != 0 and isclose(roots[0], root):
            break

        # round off purely imag or real nums
        if isclose(root.real, 0):
            root = complex(0, root.imag)
        if isclose(root.imag, 0):
            root = complex(root.real, 0)

        print(k, ":", root)
        roots.append(root)

    return roots
    def test_normalize_valid_input(self):
        '''
        ``Qubit.change_state()`` should rescale valid new states to unit vectors.
        '''

        for vec in self.valid_qubits:
            # get machine epsilon for relative error
            mach_eps = np.finfo(type(vec[0])).eps

            # change state and compute inner product
            self.test_qubit.change_state(vec)
            state_dual = np.conjugate(self.test_qubit.state())

            # if inner product != 1, then test_qubit.normalize() failed
            inner_product = np.dot(self.test_qubit.state(), state_dual)

            # cmath is used so we don't discard errors in the imaginary part
            norm_query = cmath.isclose(1, inner_product, rel_tol=10 * mach_eps)
            self.assertTrue(norm_query)
 def test_analyse_orders_from_file_row_csv(self):
     # arrange
     app_dir = os.path.dirname(__file__, )
     rel_path = 'supplychainpy/data2.csv'
     abs_file_path = os.path.abspath(os.path.join(app_dir, '..', rel_path))
     # act
     d = model_inventory.analyse_orders_from_file_row(file_path=abs_file_path,
                                                      reorder_cost=Decimal(45),
                                                      z_value=Decimal(1.28),
                                                      file_type="csv",
                                                      retail_price=Decimal(30),
                                                      currency='USD')
     std = 0
     for row in d:
         if row['sku'] == 'KR202-210':
             std = row.get('standard_deviation')
             break
     # assert
     self.assertTrue(isclose(Decimal(std), 950, abs_tol=2))
    def test_local_pbasis_default_and_qubit_states(self):
        """Test qubit states kwarg"""
        size = 3
        qubits = [2, 0]
        default_states = [qi.random_density_matrix(2, seed=20 + i) for i in range(size)]
        qubit_states = {2: [qi.random_statevector(2, seed=40 + i) for i in range(size)]}
        basis = LocalPreparationBasis(
            "fitter_basis", default_states=default_states, qubit_states=qubit_states
        )

        # Check states
        indices = it.product(range(size), repeat=2)
        states0 = qubit_states[qubits[0]] if qubits[0] in qubit_states else default_states
        states1 = qubit_states[qubits[1]] if qubits[1] in qubit_states else default_states
        for index in indices:
            basis_state = qi.DensityMatrix(basis.matrix(index, qubits))
            target = qi.DensityMatrix(states0[index[0]]).expand(states1[index[1]])
            fid = qi.state_fidelity(basis_state, target)
            self.assertTrue(isclose(fid, 1))
    def test_local_pbasis_qubit_states(self):
        """Test qubit states kwarg"""
        size = 3
        qubits = [0, 2]
        qubit_states = {
            qubits[0]: [qi.random_density_matrix(2, seed=30 + i) for i in range(size)],
            qubits[1]: [qi.random_statevector(2, seed=40 + i) for i in range(size)],
        }
        basis = LocalPreparationBasis("fitter_basis", qubit_states=qubit_states)

        # Check states
        indices = it.product(range(size), repeat=2)
        for index in indices:
            basis_state = qi.DensityMatrix(basis.matrix(index, qubits))
            target0 = qi.DensityMatrix(qubit_states[qubits[0]][index[0]])
            target1 = qi.DensityMatrix(qubit_states[qubits[1]][index[1]])
            target = target0.expand(target1)
            fid = qi.state_fidelity(basis_state, target)
            self.assertTrue(isclose(fid, 1))
Beispiel #14
0
def from_axis_angle(axis: numpy.ndarray, angle: float):
    """
	"""
    angle /= 2

    nx = axis[0]
    ny = axis[1]
    nz = axis[2]

    #return math.cos(angle) * I2 - 1j * math.sin(angle) * (nx*X + ny*Y + nz*Z)
    m = math.cos(angle) * I2 - 1j * math.sin(angle) * (nx * X + ny * Y +
                                                       nz * Z)

    # If value is close enough to zero, round it down to zero
    for i in range(0, 4):
        if cmath.isclose(m.A1[i], 0, abs_tol=1e-14):
            m.A1[i] = 0

    return make_SU2(m)
Beispiel #15
0
def test_squeezing_quadratures():
    size = 3

    rho1 = np.zeros((size,) * 4, dtype=complex)
    assert squeezing_quadratures(rho1, channel=1) == (0, 0)
    assert squeezing_quadratures(rho1, channel=2) == (0, 0)

    t = 0.379
    r = sqrt(1 - t**2)
    rho2 = np.zeros((size,) * 4, dtype=complex)
    rho2[2, 0, 2, 0] = 2 * (t**2 - r**2) ** 2
    rho2[2, 0, 1, 1] = - 4j * sqrt(2) * t * r * (t**2 - r**2)
    rho2[2, 0, 0, 2] = 2 * (t**2 - r**2) ** 2
    rho2[1, 1, 2, 0] = 4j * sqrt(2) * t * r * (t**2 - r**2)
    rho2[1, 1, 1, 1] = 16 * t**2 * r**2
    rho2[1, 1, 0, 2] = 4j * sqrt(2) * t * r * (t**2 - r**2)
    rho2[0, 2, 2, 0] = 2 * (t ** 2 - r ** 2) ** 2
    rho2[0, 2, 1, 1] = - 4j * sqrt(2) * t * r * (t ** 2 - r ** 2)
    rho2[0, 2, 0, 2] = 2 * (t ** 2 - r ** 2) ** 2
    rho2 = 0.25 * rho2
    sq2_1 = squeezing_quadratures(rho2, channel=1)
    sq2_2 = squeezing_quadratures(rho2, channel=2)
    assert cmath.isclose(sq2_1[0], sqrt(0.75), rel_tol=1e-9)
    assert cmath.isclose(sq2_1[1], sqrt(0.75), rel_tol=1e-9)
    assert cmath.isclose(sq2_2[0], sqrt(0.75), rel_tol=1e-9)
    assert cmath.isclose(sq2_2[1], sqrt(0.75), rel_tol=1e-9)

    rho3 = np.zeros((size,) * 4, dtype=complex)
    rho3[1, 0, 1, 0] = 2 * t**2
    rho3[1, 0, 0, 1] = -2j * t * r
    rho3[0, 1, 1, 0] = 2j * t * r
    rho3[0, 1, 0, 1] = 2 * r ** 2
    rho3[0, 0, 0, 0] = 1
    rho3 = rho3 / 3
    sq3_1 = squeezing_quadratures(rho3, channel=1)
    sq3_2 = squeezing_quadratures(rho3, channel=2)
    assert cmath.isclose(sq3_1[0], sqrt((t**2)/3 + 0.25), rel_tol=1e-9)
    assert cmath.isclose(sq3_1[1], sqrt((t**2)/3 + 0.25), rel_tol=1e-9)
    assert cmath.isclose(sq3_2[0], sqrt((r**2)/3 + 0.25), rel_tol=1e-9)
    assert cmath.isclose(sq3_2[1], sqrt((r**2)/3 + 0.25), rel_tol=1e-9)
    def set_adj_matrix(self, adj_matrix):
        self.graph = nx.Graph()
        self.adj_matrix = adj_matrix
        self.solution = np.zeros(self.num_nodes)

        fig = plt.figure(figsize=(7, 5))

        self.graph.add_nodes_from(np.arange(0, self.num_nodes, 1))

        # tuple is (i,j,weight) where (i,j) is the edge
        edge_list = []
        for i in range(self.num_nodes):
            for j in range(i + 1, self.num_nodes):
                if not isclose(adj_matrix[i, j], 0.0):
                    edge_list.append((i, j, adj_matrix[i, j]))

        self.graph.add_weighted_edges_from(edge_list)

        self.graph_pos = nx.spring_layout(self.graph)
        self.draw_network_graph(self.calc_node_colors())
Beispiel #17
0
 def invlength(self, frac):
     """Computes the t value where self.length(t) / self.length() = frac."""
     if frac <= 0: return 0
     if frac >= 1: return 1
     whole = self.length()
     target, fa = frac * whole, self.length(frac)
     lower, higher = (frac, 1) if fa < target else (0, frac)
     flower, fire, status = self.length(lower), self.length(higher), 0
     for q in range(64):
         if not isclose(lower, higher, rel_tol=1e-15):
             mt = (target - flower) / (fire - flower)
             if status == 2: mt, status = mt / 2, 0
             elif status == -2: mt, status = (1 + mt) / 2, 0
             mid = linterp(lower, higher, mt)
             fmid = self.length(mid)
             if fmid < target: lower, flower, status = mid, fmid, min(-1, status - 1)
             elif fmid > target: higher, fire, status = mid, fmid, max(1, status + 1)
             else: break
         else: break
     return round(mid, 12)
def test_update_handler_publishes_float_update(pv_value, pv_type):
    producer = FakeProducer()
    context = FakeContext()

    pv_timestamp_s = 1.1  # seconds from unix epoch
    pv_source_name = "source_name"

    pva_update_handler = PVAUpdateHandler(producer, context, pv_source_name,
                                          "output_topic",
                                          "f142")  # type: ignore
    context.call_monitor_callback_with_fake_pv_update(
        NTScalar(pv_type, valueAlarm=True).wrap(pv_value,
                                                timestamp=pv_timestamp_s))

    assert producer.published_payload is not None
    pv_update_output = deserialise_f142(producer.published_payload)
    assert isclose(pv_update_output.value, pv_value, abs_tol=0.0001)
    assert pv_update_output.source_name == pv_source_name

    pva_update_handler.stop()
Beispiel #19
0
def test_type_of_field_can_be_changed(nexus_wrapper):
    """
    This is important to test because the implementation is very different to just changing the value.
    When the type changes the dataset has to be deleted and recreated with the new type
    """

    name = "component_name"
    field_name = "some_field"
    initial_value = 42
    component = add_component_to_file(nexus_wrapper, field_name, initial_value, name)
    returned_value = component.get_field(field_name)
    assert (
        returned_value == initial_value
    ), "Expected to get same value back from field as it was created with"

    new_value = 17.3
    component.set_field("some_field", new_value, dtype=float)
    returned_value = component.get_field(field_name)
    assert isclose(
        returned_value, new_value
    ), "Expected to get same value back from field as it was changed to"
    def test_local_mbasis_default_and_qubit_states(self):
        """Test qubit and default povm kwarg"""
        size = 3
        outcomes = 2
        qubits = [2, 0]
        default_povms = (
            [
                [qi.random_statevector(2, seed=20 + i + j) for i in range(outcomes)]
                for j in range(size)
            ],
        )
        qubit_povms = {
            qubits[0]: [
                [qi.random_density_matrix(2, seed=30 + i + j) for i in range(outcomes)]
                for j in range(size)
            ],
            qubits[1]: [
                [qi.random_density_matrix(2, seed=40 + i + j) for i in range(outcomes)]
                for j in range(size)
            ],
        }
        basis = LocalMeasurementBasis(
            "fitter_basis", default_povms=default_povms, qubit_povms=qubit_povms
        )

        # Check states
        states0 = qubit_povms[qubits[0]] if qubits[0] in qubit_povms else default_povms
        states1 = qubit_povms[qubits[1]] if qubits[1] in qubit_povms else default_povms
        indices = it.product(range(size), repeat=2)
        outcomes = it.product(range(outcomes), repeat=len(qubits))
        for index in indices:
            for outcome in outcomes:
                basis_state = qi.DensityMatrix(
                    basis.matrix(index, self._outcome_tup_to_int(outcome), qubits)
                )
                target0 = qi.DensityMatrix(states0[index[0]][outcome[0]])
                target1 = qi.DensityMatrix(states1[index[1]][outcome[1]])
                target = target0.expand(target1)
                fid = qi.state_fidelity(basis_state, target)
                self.assertTrue(isclose(fid, 1))
Beispiel #21
0
    def term(cls,
             qubits: Qubits,
             ops: str,
             coefficient: complex = 1.0) -> 'Pauli':
        """
        Create an element of the Pauli algebra from a sequence of qubits
        and operators. Qubits must be unique and sortable
        """
        if not all(op in PAULI_OPS for op in ops):
            raise ValueError("Valid Pauli operators are I, X, Y, and Z")

        coeff = complex(coefficient)

        terms = ()  # type: Tuple[PauliTerm, ...]
        if isclose(coeff, 0.0):
            terms = ()
        else:
            qops = zip(qubits, ops)
            qops = filter(lambda x: x[1] != 'I', qops)
            terms = ((tuple(sorted(qops)), coeff), )

        return cls(terms)
def test_interpret_transactions(parsed_account_data):
    val = interpret_transactions(parsed_account_data)
    assert "2018" in val
    year = val["2018"][KEY_ACCOUNTS]

    assert "NL49INGB0004568299" in year
    assert "NL49INGB0004568333" in year

    _account = year["NL49INGB0004568299"]
    _plus = _account[KEY_PLUS]
    assert _plus["04"] == 57.9
    _minus = _account[KEY_MINUS]
    assert _minus["04"] == -97.17
    _total = _account[KEY_TOTAL]
    assert cmath.isclose(_total["04"], -39.27, abs_tol=0.0001)

    _charity = _account["charity"]
    assert _charity["04"] == -97.17

    _account = year["NL49INGB0004568333"]
    _minus = _account[KEY_MINUS]
    assert _minus["06"] == -88.52
Beispiel #23
0
def isclose(a, b, *, rel_tol=1e-09, abs_tol=0.0) -> bool:
    '''Return True if a is close to b'''
    # Always try optimized c methods first
    try:
        return _math.isclose(a, b)
    except Exception:
        pass
    try:
        return _cmath.isclose(a, b)
    except Exception:
        pass

    # If these fail
    # case checks
    if isnan(a) or isnan(b):
        return False
    if isinf(a) or isinf(b):
        return bool(a == b)

    # find tolerance for 'closeness' and the distance between the values
    tol, difference = max((abs(abs(b) * rel_tol)), abs(abs_tol)), abs(a - b)

    return bool(tol >= difference)
    def handle_element_clicked(self, picker):
        for idx, picker_in_list in enumerate(self.number_pickers_list):
            if picker == picker_in_list:
                row = idx // self.num_nodes
                col = idx % self.num_nodes
                if row != col:
                    if isclose(picker_in_list.number, 0):
                        picker_in_list.number = 1
                        self.adj_matrix_graph_dirty = True
                    elif picker_in_list.number < self.MAX_EDGE_VALUE:
                        picker_in_list.number += 1
                    else:
                        picker_in_list.number = 0
                        self.adj_matrix_graph_dirty = True

                    picker_in_list.draw_number_picker()
                    self.adj_matrix_numeric[row, col] = picker_in_list.number

                    # Also update the other side
                    other_idx = col * self.num_nodes + row
                    other_picker = self.number_pickers_list[other_idx]
                    other_picker.number = picker_in_list.number
                    other_picker.draw_number_picker()
                    self.adj_matrix_numeric[col, row] = picker_in_list.number
Beispiel #25
0
def rot(euler: tuple) -> torch.tensor:
    """
    General rotation matrix
    :param euler: (a, b, r) rotation in rad in ZYX
    
    :return R: a rotation matrix R
    """
    from math import sin, cos
    a, b, r = euler[0], euler[1], euler[2]
    row1 = torch.tensor([
        cos(a) * cos(b),
        cos(a) * sin(b) * sin(r) - sin(a) * cos(r),
        cos(a) * sin(b) * cos(r) + sin(a) * sin(r)
    ])
    row2 = torch.tensor([
        sin(a) * cos(b),
        sin(a) * sin(b) * sin(r) + cos(a) * cos(r),
        sin(a) * sin(b) * cos(r) - cos(a) * sin(r)
    ])
    row3 = torch.tensor([-sin(b), cos(b) * sin(r), cos(b) * cos(r)])
    R = torch.stack((row1, row2, row3), 0)
    assert cmath.isclose(torch.linalg.det(R), 1,
                         rel_tol=1e-04), torch.linalg.det(R)
    return R
    def __init__(self, *terms: PauliTerm) -> None:
        the_terms = []
        qubits: Set[Qubit] = set()

        if len(terms) != 0:  # == 0 zero element
            # print(terms)
            for qbs, ops, coeff in terms:
                if not all(op in PAULI_OPS for op in ops):
                    raise ValueError(
                        "Valid Pauli operators are I, X, Y, and Z")
                if isinstance(coeff, Complex) and isclose(coeff, 0.0):
                    continue
                if len(ops) != 0:
                    qops = sorted(zip(qbs, ops))
                    qops = list(filter(lambda x: x[1] != "I", qops))
                    qbs, ops = zip(*qops) if qops else ((), "")  # type: ignore

                the_terms.append((tuple(qbs), "".join(ops), coeff))
                qubits.update(qbs)

        qbs = sorted(list(qubits))
        super().__init__(qbs)

        self.terms = tuple(the_terms)
Beispiel #27
0
def test_negativity():
    with pytest.raises(ValueError):
        negativity([], neg_type=None)
    size = 3

    rho1 = np.zeros((size,) * 4, dtype=complex)
    cmath.isclose(negativity(rho1, neg_type='raw'), 0, rel_tol=1e-9)
    cmath.isclose(negativity(rho1, neg_type='logarithmic'), 0, rel_tol=1e-9)

    a02, a11, a20 = 7 + 1j, 3, 5 - 3j
    rho2 = np.zeros((size,) * 4, dtype=complex)
    rho2[0, 2, 0, 2] = a02 * np.conj(a02)
    rho2[0, 2, 1, 1] = a02 * np.conj(a11)
    rho2[0, 2, 2, 0] = a02 * np.conj(a20)
    rho2[1, 1, 0, 2] = a11 * np.conj(a02)
    rho2[1, 1, 1, 1] = a11 * np.conj(a11)
    rho2[1, 1, 2, 0] = a11 * np.conj(a20)
    rho2[2, 0, 0, 2] = a20 * np.conj(a02)
    rho2[2, 0, 1, 1] = a20 * np.conj(a11)
    rho2[2, 0, 2, 0] = a20 * np.conj(a20)
    neg_expected = (abs(a02) + abs(a20)) * abs(a11) + abs(a02) * abs(a20)
    assert cmath.isclose(negativity(rho2, neg_type='raw'), neg_expected, rel_tol=1e-9)
    assert cmath.isclose(negativity(rho2, neg_type='logarithmic'), np.log2(2 * neg_expected + 1), rel_tol=1e-9)
Beispiel #28
0
def good_match(ts, tss):
    return next(
        (x for x in tss if isclose(ts, x, abs_tol=TOLERANCE)), None)
Beispiel #29
0
async def test_data_stream_returns_metadata(queues):
    data_queue, worker_instruction_queue, test_message_queue = queues
    run_info_topic = "fake_topic"
    test_instrument_name = "DATA_STREAM_TEST"

    # The Kafka topics to get metadata from are recorded as "stream" objects in
    # the nexus_structure field of the run start message
    # There are currently 3 schemas for metadata, they have flatbuffer ids
    # f142, senv and tdct
    f142_source_name = "f142_source"
    f142_log_name = "f142_log"
    senv_source_name = "senv_source"
    senv_log_name = "senv_log"
    tdct_source_name = "tdct_source"
    tdct_log_name = "tdct_log"
    streams = [
        Stream(f"/entry/{f142_log_name}", "f142_topic", f142_source_name,
               "f142", "double", "m"),
        Stream(f"/entry/{senv_log_name}", "senv_topic", senv_source_name,
               "senv", "double", "m"),
        Stream(f"/entry/{tdct_log_name}", "tdct_topic", tdct_source_name,
               "tdct")
    ]

    test_stream_args = TEST_STREAM_ARGS.copy()
    test_stream_args["topics"] = None
    n_chunks = 0
    async for data in _data_stream(data_queue,
                                   worker_instruction_queue,
                                   run_info_topic=run_info_topic,
                                   query_consumer=FakeQueryConsumer(
                                       test_instrument_name, streams=streams),
                                   halt_after_n_data_chunks=2,
                                   **test_stream_args,
                                   test_message_queue=test_message_queue):
        data_from_stream = data

        if n_chunks == 0:
            # Fake receiving a Kafka message for each metadata schema
            # Do this after the run start message has been parsed, so that
            # a metadata buffer will have been created for each data source
            # described in the start message.
            f142_value = 26.1236
            f142_timestamp = 123456  # ns after epoch
            f142_test_message = serialise_f142(f142_value, f142_source_name,
                                               f142_timestamp)
            test_message_queue.put(FakeMessage(f142_test_message))
            senv_values = np.array([26, 127, 52])
            senv_timestamp_ns = 123000  # ns after epoch
            senv_timestamp = datetime.datetime.fromtimestamp(
                senv_timestamp_ns * 1e-9, datetime.timezone.utc)
            senv_time_between_samples = 100  # ns
            senv_test_message = serialise_senv(senv_source_name, -1,
                                               senv_timestamp,
                                               senv_time_between_samples, 0,
                                               senv_values, Location.Start)
            test_message_queue.put(FakeMessage(senv_test_message))
            tdct_timestamps = np.array([1234, 2345, 3456])  # ns
            tdct_test_message = serialise_tdct(tdct_source_name,
                                               tdct_timestamps)
            test_message_queue.put(FakeMessage(tdct_test_message))

        n_chunks += 1

    assert isclose(data_from_stream.attrs[f142_source_name].value.values[0],
                   f142_value)
    assert data_from_stream.attrs[f142_source_name].value.coords[
        'time'].values[0] == np.array(f142_timestamp,
                                      dtype=np.dtype('datetime64[ns]'))
    assert np.array_equal(
        data_from_stream.attrs[senv_source_name].value.values, senv_values)
    senv_expected_timestamps = np.array([
        senv_timestamp_ns, senv_timestamp_ns + senv_time_between_samples,
        senv_timestamp_ns + (2 * senv_time_between_samples)
    ],
                                        dtype=np.dtype('datetime64[ns]'))
    assert np.array_equal(
        data_from_stream.attrs[senv_source_name].value.coords['time'].values,
        senv_expected_timestamps)
    assert np.array_equal(
        data_from_stream.attrs[tdct_source_name].value.values, tdct_timestamps)
Beispiel #30
0
def czt(x, A, W, M, axis=-1):
    """
    Chirp Z-Transform.

    This implementation follows the semantics defined in :ref:`CZT_def`.

    Parameters
    ----------
    x : :py:class:`~numpy.ndarray`
        (..., N, ...) input array.
    A : float or complex
        Circular offset from the positive real-axis.
    W : float or complex
        Circular spacing between transform points.
    M : int
        Length of the transform.
    axis : int
        Dimension of `x` along which the samples are stored.

    Returns
    -------
    :py:class:`~numpy.ndarray`
        (..., M, ...) transformed input along the axis indicated by `axis`.

    Notes
    -----
    Due to numerical instability when using large `M`, this implementation only supports transforms where `A` and `W` have unit norm.

    Examples
    --------
    .. testsetup::

       import numpy as np
       from pypeline.util.math.fourier import czt

    Implementation of the DFT:

    .. doctest::

       >>> N = M = 10
       >>> x = np.random.randn(N, 3) + 1j * np.random.randn(N, 3)  # multi-dim

       >>> dft_x = np.fft.fft(x, axis=0)
       >>> czt_x = czt(x, A=1, W=np.exp(-1j * 2 * np.pi / N), M=M, axis=0)

       >>> np.allclose(dft_x, czt_x)
       True

    Implementation of the iDFT:

    .. doctest::

       >>> N = M = 10
       >>> x = np.random.randn(N) + 1j * np.random.randn(N)

       >>> idft_x = np.fft.ifft(x)
       >>> czt_x = czt(x, A=1, W=np.exp(1j * 2 * np.pi / N), M=M)

       >>> np.allclose(idft_x, czt_x / N)  # czt() does not do the scaling.
       True

    See Also
    --------
    :py:class:`~pypeline.util.math.fourier.FFTW_CZT`
    """
    x = np.array(x, copy=False)
    A = complex(A)
    W = complex(W)

    if not cmath.isclose(abs(A), 1):
        raise ValueError('Parameter[A] must lie on the unit circle for '
                         'numerical stability.')
    if not cmath.isclose(abs(W), 1):
        raise ValueError('Parameter[W] must lie on the unit circle.')
    if M <= 0:
        raise ValueError('Parameter[M] must be positive.')
    if not (-x.ndim <= axis < x.ndim):
        raise ValueError('Parameter[axis] is out-of-bounds.')

    # Shape Parameters
    N = x.shape[axis]
    sh_N = [1] * x.ndim
    sh_N[axis] = N
    sh_M = [1] * x.ndim
    sh_M[axis] = M

    L = fftpack.next_fast_len(N + M - 1)
    sh_L = [1] * x.ndim
    sh_L[axis] = L
    sh_Y = list(x.shape)
    sh_Y[axis] = L

    n = np.arange(L)
    y = np.zeros(sh_Y, dtype=complex)
    y_mod = (A ** -n[:N]) * np.float_power(W, (n[:N] ** 2) / 2)
    y[array.index(y, axis, slice(N))] = x
    y[array.index(y, axis, slice(N))] *= y_mod.reshape(sh_N)
    Y = fftpack.fft(y, axis=axis)

    v = np.zeros(L, dtype=complex)
    v[:M] = np.float_power(W, - (n[:M] ** 2) / 2)
    v[L - N + 1:] = np.float_power(W, - ((L - n[L - N + 1:]) ** 2) / 2)
    V = fftpack.fft(v).reshape(sh_L)

    G = Y
    G *= V
    g = fftpack.ifft(G, axis=axis)
    g_mod = np.float_power(W, (n[:M] ** 2) / 2)
    g[array.index(g, axis, slice(M))] *= g_mod.reshape(sh_M)

    X = g[array.index(g, axis, slice(M))]
    return X
Beispiel #31
0
def test_math():
    def get_arg(prog):
        return prog[0].params[0]

    arg = get_arg(qf.parse_quil("RX(1) 0"))
    assert arg == 1

    arg = get_arg(qf.parse_quil("RX(2.9) 0"))
    assert arg == 2.9

    arg = get_arg(qf.parse_quil("RX(-2.9) 0"))
    assert arg == -2.9

    arg = get_arg(qf.parse_quil("RX(+2.9) 0"))
    assert arg == +2.9

    arg = get_arg(qf.parse_quil("RX(+2.9/4.2) 0"))
    assert arg == +2.9/4.2

    arg = get_arg(qf.parse_quil("RX(+2.9*4.2) 0"))
    assert arg == +2.9*4.2

    arg = get_arg(qf.parse_quil("RX(2.9+4.2) 0"))
    assert arg == 2.9+4.2

    arg = get_arg(qf.parse_quil("RX(2.9-4.2) 0"))
    assert arg == 2.9-4.2

    arg = get_arg(qf.parse_quil("RX(pi) 0"))
    assert arg == math.pi

    arg = get_arg(qf.parse_quil("RX(2.0*pi) 0"))
    assert arg == 2.0*math.pi

    arg = get_arg(qf.parse_quil("RX(sin(1.0)) 0"))
    assert arg == math.sin(1.0)

    arg = get_arg(qf.parse_quil("RX(sin(1.0)) 0"))
    assert arg == math.sin(1.0)

    arg = get_arg(qf.parse_quil("RX(exp(3.3)) 0"))
    assert arg == math.exp(3.3)
    print(arg, type(arg))

    arg = get_arg(qf.parse_quil("RX(cos(2.3)) 0"))
    print(arg, type(arg))
    assert math.cos(2.3) - arg == ALMOST_ZERO

    arg = get_arg(qf.parse_quil("RX( sqrt( 42  )   ) 0"))
    assert math.sqrt(42) - arg == ALMOST_ZERO

    arg = get_arg(qf.parse_quil("RX(cis(2)) 0"))
    assert cmath.isclose(cis(2), arg)

    arg = get_arg(qf.parse_quil("RX(2.3 i) 0"))
    assert arg == 2.3j

    arg = get_arg(qf.parse_quil("RX(exp(2)) 0"))
    assert math.exp(2) - arg == ALMOST_ZERO

    arg = get_arg(qf.parse_quil("RX(2^2) 0"))
    assert 4 - arg == ALMOST_ZERO
# 这些方法分别用于将对象转换为复数或浮点数,然后将函数应用于转换结果。

# 常量
c.tau # 2pi
c.e  
c.pi
c.inf
c.infj #实部为0,虚部为无穷
c.nan

c.sqrt
c.exp
c.log(x,base=e)
c.log10(x)

c.isclose(a,b,rel_tol=1e-9,abs_tol=0) #判断a和b是否足够近,rel_tol为相对公差, abs_tol绝对公差
c.isfinite(z) #real 和image都为有限
c.isinf  #real 和image有一个为无穷
c.isnan

c.phase(z:complex)->float #返回辐角 phase 相位角
c.polar(z:complex) ->tuple[float,float] #直角坐标转换为极坐标
c.rect(r:float,phi:float)->complex  #极坐标转换直角坐标

# 三角函数
c.acos
c.asin
c.atan
c.cos
c.sin
c.tan
import cmath

print(cmath.pi)
print(cmath.sqrt(a))

a = 1 + 1j
## rectangular to polar
print(cmath.phase(a))
print(abs(a))
## polar to rectangular
print(cmath.rect(math.sqrt(2), math.pi / 4))  # wrong

rhs = cmath.exp(cmath.pi * 1j) + 1
print(rhs)

print(cmath.isclose(rhs, 0))  # false
print(cmath.isclose(rhs, 0, abs_tol=0.0001))  # true

######################
# booleans
# descrived in PEP 285
# https://www.python.org/dev/peps/pep-0285/
# subclass of int
######################

print(issubclass(bool, int))  # true
print(type(True))
print(id(True))
print(int(True))
print(type(False))
print(id(False))
Beispiel #34
0
def comp_complex(a, b):
    if cmath.isclose(a, b, rel_tol=1e-2):
        return 1.0
    return 0.0
print('sine =', cmath.sin(c))
print('cosine =', cmath.cos(c))
print('tangent =', cmath.tan(c))

# hyperbolic functions
c = 2 + 2j
print('inverse hyperbolic sine =', cmath.asinh(c))
print('inverse hyperbolic cosine =', cmath.acosh(c))
print('inverse hyperbolic tangent =', cmath.atanh(c))

print('hyperbolic sine =', cmath.sinh(c))
print('hyperbolic cosine =', cmath.cosh(c))
print('hyperbolic tangent =', cmath.tanh(c))

# classification functions
print(cmath.isfinite(2 + 2j))  # True
print(cmath.isfinite(cmath.inf + 2j))  # False

print(cmath.isinf(2 + 2j))  # False
print(cmath.isinf(cmath.inf + 2j))  # True
print(cmath.isinf(cmath.nan + 2j))  # False


print(cmath.isnan(2 + 2j))  # False
print(cmath.isnan(cmath.inf + 2j))  # False
print(cmath.isnan(cmath.nan + 2j))  # True

print(cmath.isclose(2+2j, 2.01+1.9j, rel_tol=0.05))  # True
print(cmath.isclose(2+2j, 2.01+1.9j, abs_tol=0.005))  # False