summaryrefslogtreecommitdiffstats
path: root/polymatrix/expression/mixins/fromnumbersexprmixin.py
blob: 48d2b12e5389423645638d4081e38e5b1aac62ca (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
38
39
40
41
42
from __future__ import annotations

from abc import abstractmethod
from typing_extensions import override
from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from polymatrix.expressionstate.mixins import ExpressionStateMixin

from polymatrix.expression.mixins.expressionbasemixin import ExpressionBaseMixin

from polymatrix.polymatrix.mixins import PolyMatrixMixin
from polymatrix.polymatrix.init import init_poly_matrix
from polymatrix.polymatrix.typing 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: ExpressionStateMixin) -> tuple[ExpressionStateMixin, 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)