summaryrefslogtreecommitdiffstats
path: root/polymatrix/expression/mixins/fromnumbersexprmixin.py
blob: d1c3ccf3b60fc8badca8aae47e20c1e8ae3dc182 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
from abc import abstractmethod
from typing_extensions import override

from polymatrix.expression.mixins.expressionbasemixin import ExpressionBaseMixin
from polymatrix.expressionstate import ExpressionState

from polymatrix.polymatrix.mixins import PolyMatrixMixin
from polymatrix.polymatrix.init import init_poly_matrix
from polymatrix.polymatrix.index import PolyMatrixDict, PolyDict, MonomialIndex


class FromNumbersExprMixin(ExpressionBaseMixin):
    """
    Make an expression from a tuple of tuples of numbers (constant). The tuple
    of tuples is interpreted as a matrix stored with row major ordering.

    ..code:: py
        m = polymatrix.from_numbers(((0, 1), (1, 0))
    """

    @property
    @abstractmethod
    def data(self) -> tuple[tuple[int | float]]:
        """ The matrix of numbers in row major order. """

    @override
    def apply(self, state: ExpressionState) -> tuple[ExpressionState, PolyMatrixMixin]:
        p = PolyMatrixDict.empty()

        for r, row in enumerate(self.data):
            for c, entry in enumerate(row):
                p[r, c] = PolyDict({
                    MonomialIndex.constant(): entry
                })

        shape = (r + 1, c + 1)
        return state, init_poly_matrix(p, shape)