summaryrefslogtreecommitdiffstats
path: root/polymatrix/expression/mixins/derivativeexprmixin.py
blob: 4fc48a5ba24aa192686d3d1f7a30f53cdb88688a (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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
import abc
import collections
import dataclasses
import itertools
import typing
from polymatrix.expression.init.initderivativekey import init_derivative_key

from polymatrix.expression.init.initpolymatrix import init_poly_matrix
from polymatrix.expression.mixins.expressionbasemixin import ExpressionBaseMixin
from polymatrix.expression.polymatrix import PolyMatrix
from polymatrix.expression.expressionstate import ExpressionState
from polymatrix.expression.utils.getderivativemonomials import get_derivative_monomials
from polymatrix.expression.utils.getvariableindices import get_variable_indices


class DerivativeExprMixin(ExpressionBaseMixin):
    @property
    @abc.abstractmethod
    def underlying(self) -> ExpressionBaseMixin:
        ...

    @property
    @abc.abstractmethod
    def variables(self) -> typing.Union[tuple, ExpressionBaseMixin]:
        ...

    @property
    @abc.abstractmethod
    def introduce_derivatives(self) -> bool:
        ...

    # overwrites abstract method of `ExpressionBaseMixin`
    def apply(
        self, 
        state: ExpressionState,
    ) -> tuple[ExpressionState, PolyMatrix]:

        state, underlying = self.underlying.apply(state=state)

        assert underlying.shape[1] == 1, f'{underlying.shape=}'
        
        state, diff_wrt_variables = get_variable_indices(state, self.variables)

        # def get_derivative_terms(
        #     monomial_terms, 
        #     diff_wrt_variable: int, 
        #     state: ExpressionState,
        #     considered_variables: set,
        # ):

        #     if self.introduce_derivatives:

        #         raise Exception('not implemented')
                
        #         def gen_new_variables():
        #             for monomial in monomial_terms.keys():
        #                 for var in monomial:
        #                     if var not in diff_wrt_variables and var not in considered_variables:
        #                         yield var

        #         new_variables = set(gen_new_variables())

        #         new_considered_variables = considered_variables | new_variables

        #         def acc_state_candidates(acc, new_variable):
        #             state, candidates = acc

        #             key = init_derivative_key(
        #                 variable=new_variable,
        #                 with_respect_to=diff_wrt_variable,
        #             )
        #             state = state.register(key=key, n_param=1)

        #             state, auxillary_derivation_terms = get_derivative_terms(
        #                 monomial_terms=state.auxillary_equations[new_variable],
        #                 diff_wrt_variable=diff_wrt_variable,
        #                 state=state,
        #                 considered_variables=new_considered_variables,
        #             )

        #             if 1 < len(auxillary_derivation_terms):
        #                 derivation_variable = state.offset_dict[key][0]

        #                 state = dataclasses.replace(
        #                     state,
        #                     auxillary_equations=state.auxillary_equations | {derivation_variable: auxillary_derivation_terms},
        #                 )

        #                 return state, candidates + (new_variable,)

        #             else:
        #                 return state, candidates

        #         *_, (state, confirmed_variables) = itertools.accumulate(
        #             new_variables,
        #             acc_state_candidates,
        #             initial=(state, tuple()),
        #         )

        #     else:
        #         confirmed_variables = tuple()

        #     derivation_terms = collections.defaultdict(float)

        #     for monomial, value in monomial_terms.items():

        #         # # count powers for each variable
        #         # monomial_cnt = dict(collections.Counter(monomial))
        #         monomial_cnt = dict(monomial)

        #         def differentiate_monomial(dependent_variable, derivation_variable=None):
        #             def gen_diff_monomial():
        #                 for current_variable, current_count in monomial:

        #                     if current_variable is dependent_variable:
        #                         sel_counter = current_count - 1

        #                     else:
        #                         sel_counter = current_count

        #                     # for _ in range(sel_counter):
        #                     #     yield current_variable
        #                     yield current_variable, sel_counter

        #                 if derivation_variable is not None:
        #                     yield derivation_variable

        #             diff_monomial = tuple(sorted(gen_diff_monomial()))

        #             return diff_monomial, value * monomial_cnt[dependent_variable]

        #         if diff_wrt_variable in monomial_cnt:
        #             diff_monomial, value = differentiate_monomial(diff_wrt_variable)
        #             derivation_terms[diff_monomial] += value

        #         # only used if introduce_derivatives == True
        #         for candidate_variable in monomial_cnt.keys():
        #             if candidate_variable in considered_variables or candidate_variable in confirmed_variables:
        #                 key = init_derivative_key(
        #                     variable=candidate_variable,
        #                     with_respect_to=diff_wrt_variable,
        #                 )
        #                 derivation_variable = state.offset_dict[key][0]

        #                 diff_monomial, value = differentiate_monomial(
        #                     dependent_variable=candidate_variable, 
        #                     derivation_variable=derivation_variable,
        #                 )
        #                 derivation_terms[diff_monomial] += value

        #     return state, dict(derivation_terms)

        terms = {}

        for row in range(underlying.shape[0]):

            try:
                underlying_terms = underlying.get_poly(row, 0)
            except KeyError:
                continue

            # derivate each variable and map result to the corresponding column
            for col, diff_wrt_variable in enumerate(diff_wrt_variables):

                state, derivation_terms = get_derivative_monomials(
                    monomial_terms=underlying_terms,
                    diff_wrt_variable=diff_wrt_variable,
                    state=state,
                    considered_variables=set(),
                    introduce_derivatives=self.introduce_derivatives,
                )

                if 0 < len(derivation_terms):
                    terms[row, col] = derivation_terms

        poly_matrix = init_poly_matrix(
            terms=terms,
            shape=(underlying.shape[0], len(diff_wrt_variables)),
        )

        return state, poly_matrix