|
| 1 | +from brml.potential import Potential |
| 2 | +import numpy as np |
| 3 | + |
| 4 | + |
| 5 | +class Const(Potential): |
| 6 | + |
| 7 | + def __init__(self, value): |
| 8 | + """ |
| 9 | + Initializes Constant Potential table. The difference between a Const |
| 10 | + potential and an array is that Const does not need variables. It |
| 11 | + just contains a value (instead of a table). |
| 12 | +
|
| 13 | + :param value: for constant table |
| 14 | + :type value: float |
| 15 | + """ |
| 16 | + # Constant probability table has no variables |
| 17 | + super().__init__([], value) |
| 18 | + |
| 19 | + def _check_table(self, value): |
| 20 | + """ |
| 21 | + This method gets overwritten because now we want value to be one of: |
| 22 | + 1. Float |
| 23 | + 2. Int |
| 24 | + 3. List with length 1 |
| 25 | + 4. Array with size 1 |
| 26 | +
|
| 27 | + :param table: Value to be constant probability table |
| 28 | + :return: |
| 29 | + """ |
| 30 | + # If numeric -> return np.array with that number |
| 31 | + if isinstance(value, (float, int)): |
| 32 | + return np.array([value]) |
| 33 | + # If list or numpy array, check size |
| 34 | + elif isinstance(value, (np.ndarray, list)): |
| 35 | + # If only 1 element -> return flatten array |
| 36 | + if np.array([value]).size == 1: |
| 37 | + return np.array([value]).flatten() |
| 38 | + # Otherwise provided more than one value |
| 39 | + else: |
| 40 | + raise ValueError( |
| 41 | + "Constant potential cannot have more than one value." |
| 42 | + ) |
| 43 | + else: |
| 44 | + raise NotImplementedError( |
| 45 | + "Table value can only be float, int, list or np.array." |
| 46 | + ) |
| 47 | + |
| 48 | + def evalpot(self, evvariables=0, evidence=0): |
| 49 | + """ |
| 50 | + Evaluates the table of a potential. Because this is a constant |
| 51 | + potential, we just return the constant scalar value. Similar to |
| 52 | + @const/evalpot.m |
| 53 | +
|
| 54 | + At the moment I am keeping evvariables and evidence parameters even if |
| 55 | + they are not used. I think this is necessary because during |
| 56 | + calculations with potentials, we can end up having a const or an array |
| 57 | + but this would simply be based on the numerical values. Therefore, |
| 58 | + implementing evalpot in the same way for Const and Array, then we |
| 59 | + don't have any problem. |
| 60 | +
|
| 61 | + :return: |
| 62 | + """ |
| 63 | + return self.table |
| 64 | + |
| 65 | + |
| 66 | +if __name__ == "__main__": |
| 67 | + pot = Const(0.7) |
| 68 | + print("Const potential:", pot) |
| 69 | + print("Table: ", pot.table) |
| 70 | + # TODO: Need to move .size() method to Potential class instead of Array |
| 71 | + print("Variables: ", pot.variables) |
0 commit comments