def __add__(self, other): # Deal with the possibility of an empty matrix. if self._confusion.shape[0] == 0: return copy.deepcopy(other) elif other._confusion.shape[0] == 0: return copy.deepcopy(self) # First, create the merged labels list, and figure out what columns # we'll need to insert in the respective matrices. # Because we've disabled sort by count, _values is already sorted in # alphabetical order. i = 0 j = 0 self_cols_to_add = [0 for _ in range(len(self._values) + 1)] other_cols_to_add = [0 for _ in range(len(other._values) + 1)] merged_values = [] while i < len(self._values) and j < len(other._values): if self._values[i] < other._values[j]: # I have an item other doesn't. Record where to insert it. merged_values.append(self._values[i]) other_cols_to_add[j] += 1 i += 1 elif self._values[i] > other._values[j]: # Other has an item I don't. Record where to insert it. merged_values.append(other._values[j]) self_cols_to_add[i] += 1 j += 1 else: merged_values.append(self._values[i]) i += 1 j += 1 if i < len(self._values): # still some self values left merged_values.extend(self._values[i:]) other_cols_to_add[-1] = len(self._values) - i if j < len(other._values): # still some other values left merged_values.extend(other._values[j:]) self_cols_to_add[-1] = len(other._values) - j augmented_self_matrix = add_rows_and_cols_to_matrix( self._confusion, self_cols_to_add) augmented_other_matrix = add_rows_and_cols_to_matrix( other._confusion, other_cols_to_add) new_matrix = copy.copy(self) new_matrix._values = merged_values new_matrix.class_names = merged_values new_matrix._indices = {val: i for i, val in enumerate(merged_values)} new_matrix._confusion = augmented_self_matrix + augmented_other_matrix new_matrix._max_conf = max(self._max_conf, other._max_conf) new_matrix._total = self._total + other._total new_matrix._correct = self._correct + other._correct return new_matrix
def test_interspersed(self): result = add_rows_and_cols_to_matrix(self.TEST_MATRIX, [0, 2, 1, 0]) correct = np.array([[1, 0, 0, 2, 0, 3], [0] * 6, [0] * 6, [4, 0, 0, 5, 0, 6], [0] * 6, [7, 0, 0, 8, 0, 9]]) self.assertArraysEqual(correct, result)
def test_prepend_multiple(self): result = add_rows_and_cols_to_matrix(self.TEST_MATRIX, [2, 0, 0, 0]) correct = np.array([[0] * 5, [0] * 5, [0, 0, 1, 2, 3], [0, 0, 4, 5, 6], [0, 0, 7, 8, 9]]) self.assertArraysEqual(correct, result)
def test_append_multiple(self): result = add_rows_and_cols_to_matrix(self.TEST_MATRIX, [0, 0, 0, 2]) correct = np.array([[1, 2, 3, 0, 0], [4, 5, 6, 0, 0], [7, 8, 9, 0, 0], [0] * 5, [0] * 5]) self.assertArraysEqual(correct, result)