|
| 1 | +from eff_conv.ib.language import IBLanguage |
| 2 | + |
| 3 | +from scipy.spatial import ConvexHull |
| 4 | + |
| 5 | +import numpy as np |
| 6 | + |
| 7 | + |
| 8 | +class SimilaritySpace: |
| 9 | + """A similarity space contains points (which should correspond in order to referents or meanings) and the priors upon those points. |
| 10 | +
|
| 11 | + Properties: |
| 12 | + sim_space: A matrix which stores a list of points, each point should correspond to a referent or meaning. Dimensions are D x ||P||. |
| 13 | + Where D is the dimension of the points and P is the set of points. |
| 14 | +
|
| 15 | + point_prior: Probability distribution for the points. Length must be ||P||. Cannot have any 0s in it. |
| 16 | + If no value is passed in then a uniform distribution will be given. |
| 17 | + """ |
| 18 | + |
| 19 | + sim_space: np.ndarray |
| 20 | + point_prior: np.ndarray |
| 21 | + |
| 22 | + def __init__(self, sim_space: np.ndarray, point_prior: np.ndarray = None): |
| 23 | + if len(sim_space.shape) != 2: |
| 24 | + raise ValueError("Similarity space input must be a 2d matrix") |
| 25 | + self.sim_space = sim_space |
| 26 | + if point_prior is not None: |
| 27 | + if ( |
| 28 | + len(point_prior.shape) != 1 |
| 29 | + or point_prior.shape[0] != sim_space.shape[0] |
| 30 | + ): |
| 31 | + raise ValueError("Point priors not of correct size") |
| 32 | + self.point_prior = point_prior |
| 33 | + else: |
| 34 | + self.point_prior = np.array( |
| 35 | + [1.0 / sim_space.shape[0] for _ in range(sim_space.shape[0])] |
| 36 | + ) |
| 37 | + |
| 38 | + def _1d_convexity_amount(self, points: np.ndarray, level: np.ndarray) -> int: |
| 39 | + """Finds the number of points which are contained within a 1d range. |
| 40 | +
|
| 41 | + Args: |
| 42 | + points (np.ndarray): The points to check. |
| 43 | + level (np.ndarray): The points which make up the 1d range |
| 44 | +
|
| 45 | + Returns: |
| 46 | + int: The number of points which are in the range spanned by levels. |
| 47 | + """ |
| 48 | + l_flat = level.flatten() |
| 49 | + p_flat = points.flatten() |
| 50 | + lo, hi = min(l_flat), max(l_flat) |
| 51 | + return sum((p_flat <= hi) & (p_flat >= lo)) + level.shape[0] |
| 52 | + |
| 53 | + def quasi_convexity(self, point_dist: np.ndarray, steps: int) -> float: |
| 54 | + """Finds the quasi-convexity of a probability. Algorithm from Skinner L. (2025). |
| 55 | +
|
| 56 | + Args: |
| 57 | + point_dist (np.ndarray): The probability distribution to be evaluated. |
| 58 | + steps (int): The number of steps to interate over the probability (higher is more accurate but slower) |
| 59 | +
|
| 60 | + Returns: |
| 61 | + float: The quasi-convexity of the probabilty distribution. |
| 62 | + """ |
| 63 | + |
| 64 | + if len(point_dist.shape) != 1: |
| 65 | + raise ValueError("Quasi-Convexity input must be a probability distribution") |
| 66 | + if np.size(point_dist) != self.sim_space.shape[0]: |
| 67 | + raise ValueError("Quasi-Convexity input must map to all points") |
| 68 | + if steps <= 0: |
| 69 | + raise ValueError("Steps must be positive") |
| 70 | + |
| 71 | + mesh = 1.0 / steps |
| 72 | + |
| 73 | + qc = 0 |
| 74 | + |
| 75 | + steps = np.linspace(0, np.max(point_dist), steps)[::-1] |
| 76 | + |
| 77 | + for i in steps: |
| 78 | + level = self.sim_space[point_dist >= i] |
| 79 | + out_points = self.sim_space[point_dist < i] |
| 80 | + # If everything is on a line a very simple calculation can be done |
| 81 | + if self.sim_space.shape[1] == 1: |
| 82 | + qc += ( |
| 83 | + mesh * level.shape[0] / self._1d_convexity_amount(out_points, level) |
| 84 | + ) |
| 85 | + else: |
| 86 | + # See if the points don't span the space (If so, ConvexHull will throw an error) |
| 87 | + consider = out_points |
| 88 | + rank = np.linalg.matrix_rank(level - level[0]) |
| 89 | + if rank < self.sim_space.shape[1]: |
| 90 | + consider = [] |
| 91 | + for p in out_points: |
| 92 | + check = np.concatenate((level, [p])) |
| 93 | + if rank == np.linalg.matrix_rank(check - check[0]): |
| 94 | + consider.append(p) |
| 95 | + |
| 96 | + # Project down |
| 97 | + U, _, _ = np.linalg.svd(level.T, full_matrices=False) |
| 98 | + proj = U[:, :rank].T |
| 99 | + if len(consider) > 0: |
| 100 | + consider = (proj @ np.array(consider).T).T |
| 101 | + else: |
| 102 | + qc += mesh |
| 103 | + continue |
| 104 | + level = (proj @ level.T).T |
| 105 | + |
| 106 | + if rank == 1: |
| 107 | + amount = self._1d_convexity_amount(consider, level) |
| 108 | + else: |
| 109 | + hull = ConvexHull(level) |
| 110 | + eqs = hull.equations[:, :-1] |
| 111 | + end = hull.equations[:, -1] |
| 112 | + amount = level.shape[0] + sum( |
| 113 | + np.all(eqs @ consider.T + end[:, None] <= 1e-12, axis=0) |
| 114 | + ) |
| 115 | + |
| 116 | + qc += mesh * level.shape[0] / amount |
| 117 | + return qc |
| 118 | + |
| 119 | + def encoder_convexity( |
| 120 | + self, distrubitions: np.ndarray, prior: np.ndarray, steps: int = 100 |
| 121 | + ) -> float: |
| 122 | + """Finds the quasi-convexity of a conditional probabilty matrix, typically an IB encoder. Algorithm from Skinner L. (2025). |
| 123 | +
|
| 124 | + Args: |
| 125 | + distrubitions (np.ndarray): The conditional probaility matrix to be evaluated. Shape is of ||P|| x n where n > 0. |
| 126 | + Each column of the matrix should be a probability distrubtion over P. |
| 127 | +
|
| 128 | + prior (np.ndarray): The probability distribution of inputs into the encoder. Must be of size n. |
| 129 | + steps (int, default: 100): The number of steps to interate over the probability (higher is more accurate but slower) |
| 130 | +
|
| 131 | + Returns: |
| 132 | + float: The quasi-convexity of the matrix. |
| 133 | + """ |
| 134 | + |
| 135 | + # Apply Bayes' rule |
| 136 | + reconstructed = distrubitions.T * prior[:, None] / self.point_prior |
| 137 | + maximums = np.max(reconstructed, axis=0) |
| 138 | + |
| 139 | + reconstructed[~(reconstructed == maximums)] = 0 |
| 140 | + reconstructed[reconstructed == maximums] = 1 |
| 141 | + |
| 142 | + weighted_sum = np.sum(reconstructed.T, axis=0) |
| 143 | + weighted_sum = weighted_sum / np.sum(weighted_sum) |
| 144 | + |
| 145 | + convexities = [] |
| 146 | + for word in distrubitions.T: |
| 147 | + convexities.append(self.quasi_convexity(word, steps)) |
| 148 | + return np.sum(np.array(convexities) * weighted_sum) |
| 149 | + |
| 150 | + def language_convexity( |
| 151 | + self, lang: IBLanguage, steps: int = 100, referents=False |
| 152 | + ) -> float: |
| 153 | + """Finds the quasi-convexity of an IBLanguage by evaluating the Q(m|w) matrix. |
| 154 | +
|
| 155 | + Args: |
| 156 | + lang (IBLanguage): The language to be evaluated. |
| 157 | + steps (int, default: 100): The number of steps to iterate over the probability (higher is more accurate but slower). |
| 158 | + refeernts (boolean, default: False): Whether to evaluate q(u|w) or q(m|w). |
| 159 | +
|
| 160 | + Returns: |
| 161 | + float: The quasi-convexity of the language. |
| 162 | + """ |
| 163 | + |
| 164 | + return self.encoder_convexity( |
| 165 | + lang.reconstructed_meanings if referents else lang.qmw, |
| 166 | + lang.expressions_prior, |
| 167 | + steps=steps, |
| 168 | + ) |
0 commit comments