def test_get_bit_value(): num_bits = 5 bit_value1 = bl_lstsq.get_bit_value(num_bits) expected_result1 = np.array([-1, 0.5, 0.25, 0.125, 0.0625]) assert_array_equal(bit_value1, expected_result1, err_msg='Wrong bit value') bit_value2 = bl_lstsq.get_bit_value(num_bits, fixed_point=2, sign='p') expected_result2 = np.array([2, 1, 0.5, 0.25, 0.125]) assert_array_equal(bit_value2, expected_result2, err_msg='Wrong bit value') bit_value3 = bl_lstsq.get_bit_value(num_bits, fixed_point=1, sign='n') expected_result3 = np.array([-1, -0.5, -0.25, -0.125, -0.0625]) assert_array_equal(bit_value3, expected_result3, err_msg='Wrong bit value')
def get_laplace_2D(N, delta, BC, num_bits, fixed_point=0): """Get information about 2D Laplace's equation (steady-state heat equation).""" # Get finite-difference stiffness matrix Ax = sparse.diags([-1, 2, -1], [-1, 0, 1], shape=(N['x'], N['x'])) / (delta['x']**2) Ay = sparse.diags([-1, 2, -1], [-1, 0, 1], shape=(N['y'], N['y'])) / (delta['y']**2) Ix = sparse.identity(N['x']) Iy = sparse.identity(N['y']) A = (sparse.kron(Iy, Ax) + sparse.kron(Ay, Ix)).tocsc() # Get RHS b = np.zeros((N['y'], N['x'])) # boundary conditions b[-1, :] = b[-1, :] + BC['top'] / (delta['y']**2) b[0, :] = b[0, :] + BC['bottom'] / (delta['y']**2) b[:, 0] = b[:, 0] + BC['left'] / (delta['x']**2) b[:, -1] = b[:, -1] + BC['right'] / (delta['x']**2) b = sparse.csr_matrix(b.reshape(N['x'] * N['y'], 1)) # set the bit value to discrete the actual value as a fixed point bit_value = bl_lstsq.get_bit_value(num_bits, fixed_point=fixed_point) # discretized version of matrix `A` A_discrete = bl_lstsq.discretize_matrix(A.toarray(), bit_value) output = {'A': A, 'b': b, 'A_discrete': A_discrete, 'bit_value': bit_value} return output
def get_linear_system(N, num_bits, fixed_point=0, exact_x=True, random_seed=None): """Get information about 1D Laplace's equation.""" # number of predictor and number of response num_predictor_discrete = num_bits * N num_response = N # matrix `A` A = (np.eye(num_response, k=-1) - 2 * np.eye(num_response, k=0) + np.eye(num_response, k=1)) # set the bit value to discrete the actual value as a fixed point bit_value = bl_lstsq.get_bit_value(num_bits, fixed_point=fixed_point) # discretized version of matrix `A` A_discrete = bl_lstsq.discretize_matrix(A, bit_value) if random_seed is None: rng = np.random.default_rng() else: rng = np.random.default_rng(random_seed) if exact_x: # binary vector `q` q = rng.choice([0, 1], size=num_predictor_discrete) # vector `x` x = q2x(q, bit_value) else: # vector `x` x = (rng.choice([-1, 1], size=num_response) * (2**fixed_point) * rng.random(num_response)) # calculate vector `b` b = A @ x output = { 'A': A, 'x': x, 'b': b, 'A_discrete': A_discrete, 'bit_value': bit_value } return output
def test_get_bit_value(num_bits, fixed_point, sign, expected_result): assert_array_equal( bl_lstsq.get_bit_value(num_bits, fixed_point=fixed_point, sign=sign), expected_result, err_msg="Wrong bit value", )