def run_cras(row_totals: numpy.matrix, column_totals: numpy.matrix, conditions: dict, maximum_iterations: int=10000, tol: float=0.00001) -> numpy.matrix: """ :param row_totals: :param column_totals: :param conditions: a condition is a group of cells and a total, dict(tuple(tuples): float), a cell is (row_index, col_index) :param maximum_iterations: big number to stop this running forever :param tol: how close is close enough? :return: """ # TODO remove this hack [max(thing.shape)] a = numpy.matrix(numpy.ones(shape=(max(row_totals.shape), max(column_totals.shape)))) e = numpy.matrix(numpy.ones(shape=(len(row_totals), 1))) for _ in range(maximum_iterations): r_hat = row_scaling(a, row_totals, e) a = matrix_multiply(r_hat, a) s_hat = column_scaling(a, column_totals, e) a = matrix_multiply(a, s_hat) a = apply_conditions(a, conditions) if is_matrix_close_to_i(r_hat, tol) and is_matrix_close_to_i(s_hat, tol): return a return a
def run_ras(row_totals: numpy.matrix, column_totals: numpy.matrix, maximum_iterations: int=10000, a: numpy.matrix=None, tol: float=0.00001) -> numpy.matrix: """ creates a matrix who's respective rows sum to the row_totals and who's respective columns sum to the column_totals within the tolerance. :param row_totals: :param column_totals: :param maximum_iterations: big number to stop this running forever :param tol: how close is close enough? :return: """ if not a: a = numpy.matrix(numpy.ones(shape=(row_totals.shape[0], column_totals.shape[1]))) e = numpy.matrix(numpy.ones(shape=row_totals.shape)) for _ in range(maximum_iterations): r_hat = row_scaling(a, row_totals, e) a = matrix_multiply(r_hat, a) s_hat = column_scaling(a, column_totals, e) a = matrix_multiply(a, s_hat) if is_matrix_close_to_i(r_hat, tol) and is_matrix_close_to_i(s_hat, tol): return a return a
def test_negative_i(self): is_it = is_matrix_close_to_i(numpy.identity(4) * -1, 0.00001) self.assertFalse(is_it)
def test_near_identity(self): is_it = is_matrix_close_to_i(numpy.identity(3) + 0.001 * numpy.identity(3), 0.01) self.assertTrue(is_it)
def test_ones(self): is_it = is_matrix_close_to_i(numpy.ones((3, 3)), 0.1) self.assertFalse(is_it)
def test_type(self): is_it = is_matrix_close_to_i(numpy.matrix([[]]), 0) self.assertTrue(type(is_it), bool)