sympyextensions.py 25.8 KB
Newer Older
1
import itertools
Martin Bauer's avatar
Martin Bauer committed
2
import operator
Martin Bauer's avatar
Martin Bauer committed
3
4
5
6
7
import warnings
from collections import Counter, defaultdict
from functools import partial, reduce
from typing import Callable, Dict, Iterable, List, Optional, Sequence, Tuple, TypeVar, Union

Martin Bauer's avatar
Martin Bauer committed
8
import sympy as sp
Martin Bauer's avatar
Martin Bauer committed
9
from sympy.functions import Abs
10
from sympy.core.numbers import Zero
Martin Bauer's avatar
Martin Bauer committed
11

12
from pystencils.assignment import Assignment
13
from pystencils.data_types import cast_func, get_type_of_expression, PointerType, VectorType
14
from pystencils.kernelparameters import FieldPointerSymbol
15

Martin Bauer's avatar
Martin Bauer committed
16
17
T = TypeVar('T')

18

Martin Bauer's avatar
Martin Bauer committed
19
def prod(seq: Iterable[T]) -> T:
20
21
22
23
    """Takes a sequence and returns the product of all elements"""
    return reduce(operator.mul, seq, 1)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
def remove_small_floats(expr, threshold):
    """Removes all sp.Float objects whose absolute value is smaller than threshold

    >>> expr = sp.sympify("x + 1e-15 * y")
    >>> remove_small_floats(expr, 1e-14)
    x
    """
    if isinstance(expr, sp.Float) and sp.Abs(expr) < threshold:
        return 0
    else:
        new_args = [remove_small_floats(c, threshold) for c in expr.args]
        return expr.func(*new_args) if new_args else expr


Martin Bauer's avatar
Martin Bauer committed
38
39
def is_integer_sequence(sequence: Iterable) -> bool:
    """Checks if all elements of the passed sequence can be cast to integers"""
40
    try:
Martin Bauer's avatar
Martin Bauer committed
41
42
        for i in sequence:
            int(i)
43
44
45
46
47
        return True
    except TypeError:
        return False


Martin Bauer's avatar
Martin Bauer committed
48
49
def scalar_product(a: Iterable[T], b: Iterable[T]) -> T:
    """Scalar product between two sequences."""
50
51
52
    return sum(a_i * b_i for a_i, b_i in zip(a, b))


Martin Bauer's avatar
Martin Bauer committed
53
54
def kronecker_delta(*args):
    """Kronecker delta for variable number of arguments, 1 if all args are equal, otherwise 0"""
Martin Bauer's avatar
Martin Bauer committed
55
56
57
58
59
60
    for a in args:
        if a != args[0]:
            return 0
    return 1


61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def tanh_step_function_approximation(x, step_location, kind='right', steepness=0.0001):
    """Approximation of step function by a tanh function

    >>> tanh_step_function_approximation(1.2, step_location=1.0, kind='right')
    1.00000000000000
    >>> tanh_step_function_approximation(0.9, step_location=1.0, kind='right')
    0
    >>> tanh_step_function_approximation(1.1, step_location=1.0, kind='left')
    0
    >>> tanh_step_function_approximation(0.9, step_location=1.0, kind='left')
    1.00000000000000
    >>> tanh_step_function_approximation(0.5, step_location=(0, 1), kind='middle')
    1
    """
    if kind == 'left':
        return (1 - sp.tanh((x - step_location) / steepness)) / 2
    elif kind == 'right':
        return (1 + sp.tanh((x - step_location) / steepness)) / 2
    elif kind == 'middle':
        x1, x2 = step_location
Martin Bauer's avatar
Martin Bauer committed
81
82
        return 1 - (tanh_step_function_approximation(x, x1, 'left', steepness)
                    + tanh_step_function_approximation(x, x2, 'right', steepness))
83
84


Martin Bauer's avatar
Martin Bauer committed
85
86
def multidimensional_sum(i, dim):
    """Multidimensional summation
Martin Bauer's avatar
Martin Bauer committed
87

Martin Bauer's avatar
Martin Bauer committed
88
89
90
    Example:
        >>> list(multidimensional_sum(2, dim=3))
        [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
91
    """
Martin Bauer's avatar
Martin Bauer committed
92
93
94
95
96
97
98
99
100
101
102
103
104
    prod_args = [range(dim)] * i
    return itertools.product(*prod_args)


def normalize_product(product: sp.Expr) -> List[sp.Expr]:
    """Expects a sympy expression that can be interpreted as a product and returns a list of all factors.

    Removes sp.Pow nodes that have integer exponent by representing them as single factors in list.

    Returns:
        * for a Mul node list of factors ('args')
        * for a Pow node with positive integer exponent a list of factors
        * for other node types [product] is returned
105
    """
Martin Bauer's avatar
Martin Bauer committed
106
    def handle_pow(power):
107
108
109
110
111
        if power.exp.is_integer and power.exp.is_number and power.exp > 0:
            return [power.base] * power.exp
        else:
            return [power]

Martin Bauer's avatar
Martin Bauer committed
112
113
114
    if isinstance(product, sp.Pow):
        return handle_pow(product)
    elif isinstance(product, sp.Mul):
115
116
117
        result = []
        for a in product.args:
            if a.func == sp.Pow:
Martin Bauer's avatar
Martin Bauer committed
118
                result += handle_pow(a)
119
120
121
122
123
124
125
            else:
                result.append(a)
        return result
    else:
        return [product]


Martin Bauer's avatar
Martin Bauer committed
126
127
128
129
130
131
132
133
134
def symmetric_product(*args, with_diagonal: bool = True) -> Iterable:
    """Similar to itertools.product but yields only values where the index is ascending i.e. values below/up to diagonal

    Examples:
        >>> list(symmetric_product([1, 2, 3], ['a', 'b', 'c']))
        [(1, 'a'), (1, 'b'), (1, 'c'), (2, 'b'), (2, 'c'), (3, 'c')]
        >>> list(symmetric_product([1, 2, 3], ['a', 'b', 'c'], with_diagonal=False))
        [(1, 'b'), (1, 'c'), (2, 'c')]
    """
135
136
    ranges = [range(len(a)) for a in args]
    for idx in itertools.product(*ranges):
Martin Bauer's avatar
Martin Bauer committed
137
        valid_index = True
138
        for t in range(1, len(idx)):
Martin Bauer's avatar
Martin Bauer committed
139
140
            if (with_diagonal and idx[t - 1] > idx[t]) or (not with_diagonal and idx[t - 1] >= idx[t]):
                valid_index = False
141
                break
Martin Bauer's avatar
Martin Bauer committed
142
        if valid_index:
143
144
145
            yield tuple(a[i] for a, i in zip(args, idx))


Martin Bauer's avatar
Martin Bauer committed
146
def fast_subs(expression: T, substitutions: Dict,
Martin Bauer's avatar
Martin Bauer committed
147
              skip: Optional[Callable[[sp.Expr], bool]] = None) -> T:
148
    """Similar to sympy subs function.
Martin Bauer's avatar
Martin Bauer committed
149
150
151
152
153
154
155
156
157
158
159
160

    Args:
        expression: expression where parts should be substituted
        substitutions: dict defining substitutions by mapping from old to new terms
        skip: function that marks expressions to be skipped (if True is returned) - that means that in these skipped
              expressions no substitutions are done

    This version is much faster for big substitution dictionaries than sympy version
    """
    if type(expression) is sp.Matrix:
        return expression.copy().applyfunc(partial(fast_subs, substitutions=substitutions))

161
    def visit(expr):
162
163
        if skip and skip(expr):
            return expr
Martin Bauer's avatar
Martin Bauer committed
164
        if hasattr(expr, "fast_subs"):
165
            return expr.fast_subs(substitutions, skip)
Martin Bauer's avatar
Martin Bauer committed
166
167
        if expr in substitutions:
            return substitutions[expr]
168
169
        if not hasattr(expr, 'args'):
            return expr
Martin Bauer's avatar
Martin Bauer committed
170
171
        param_list = [visit(a) for a in expr.args]
        return expr if not param_list else expr.func(*param_list)
172

Martin Bauer's avatar
Martin Bauer committed
173
174
    if len(substitutions) == 0:
        return expression
175
    else:
Martin Bauer's avatar
Martin Bauer committed
176
177
        return visit(expression)

178

179
180
181
182
183
184
185
def is_constant(expr):
    """Simple version of checking if a sympy expression is constant.
    Works also for piecewise defined functions - sympy's is_constant() has a problem there, see:
    https://github.com/sympy/sympy/issues/16662
    """
    return len(expr.free_symbols) == 0

186

Martin Bauer's avatar
Martin Bauer committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
def subs_additive(expr: sp.Expr, replacement: sp.Expr, subexpression: sp.Expr,
                  required_match_replacement: Optional[Union[int, float]] = 0.5,
                  required_match_original: Optional[Union[int, float]] = None) -> sp.Expr:
    """Transformation for replacing a given subexpression inside a sum.

    Examples:
        The next example demonstrates the advantage of replace_additive compared to sympy.subs:
        >>> x, y, z, k = sp.symbols("x y z k")
        >>> subs_additive(3*x + 3*y, replacement=k, subexpression=x + y)
        3*k

        Terms that don't match completely can be substituted at the cost of additional terms.
        This trade-off is managed using the required_match parameters.
        >>> subs_additive(3*x + 3*y + z, replacement=k, subexpression=x+y+z, required_match_original=1.0)
        3*x + 3*y + z
        >>> subs_additive(3*x + 3*y + z, replacement=k, subexpression=x+y+z, required_match_original=0.5)
        3*k - 2*z
204
205
        >>> subs_additive(3*x + 3*y + z, replacement=k, subexpression=x+y+z, required_match_original=2)
        3*k - 2*z
Martin Bauer's avatar
Martin Bauer committed
206
207
208

    Args:
        expr: input expression
Martin Bauer's avatar
Martin Bauer committed
209
        replacement: expression that is inserted for subexpression (if found)
Martin Bauer's avatar
Martin Bauer committed
210
211
        subexpression: expression to replace
        required_match_replacement:
Martin Bauer's avatar
Martin Bauer committed
212
             * if float: the percentage of terms of the subexpression that has to be matched in order to replace
Martin Bauer's avatar
Martin Bauer committed
213
214
215
216
217
218
219
220
221
222
             * if integer: the total number of terms that has to be matched in order to replace
             * None: is equal to integer 1
             * if both match parameters are given, both restrictions have to be fulfilled (i.e. logical AND)
        required_match_original:
             * if float: the percentage of terms of the original addition expression that has to be matched
             * if integer: the total number of terms that has to be matched in order to replace
             * None: is equal to integer 1

    Returns:
        new expression with replacement
223
    """
Martin Bauer's avatar
Martin Bauer committed
224
225
    def normalize_match_parameter(match_parameter, expression_length):
        if match_parameter is None:
226
            return 1
Martin Bauer's avatar
Martin Bauer committed
227
228
229
        elif isinstance(match_parameter, float):
            assert 0 <= match_parameter <= 1
            res = int(match_parameter * expression_length)
230
            return max(res, 1)
Martin Bauer's avatar
Martin Bauer committed
231
232
233
        elif isinstance(match_parameter, int):
            assert match_parameter > 0
            return match_parameter
234
235
        raise ValueError("Invalid parameter")

Martin Bauer's avatar
Martin Bauer committed
236
    normalized_replacement_match = normalize_match_parameter(required_match_replacement, len(subexpression.args))
237

Markus Holzer's avatar
Markus Holzer committed
238
239
240
    if isinstance(subexpression, sp.Number):
        return expr.subs({replacement: subexpression})

Martin Bauer's avatar
Martin Bauer committed
241
242
243
244
245
246
247
248
    def visit(current_expr):
        if current_expr.is_Add:
            expr_max_length = max(len(current_expr.args), len(subexpression.args))
            normalized_current_expr_match = normalize_match_parameter(required_match_original, expr_max_length)
            expr_coefficients = current_expr.as_coefficients_dict()
            subexpression_coefficient_dict = subexpression.as_coefficients_dict()
            intersection = set(subexpression_coefficient_dict.keys()).intersection(set(expr_coefficients))
            if len(intersection) >= max(normalized_replacement_match, normalized_current_expr_match):
249
                # find common factor
250
                factors = defaultdict(int)
251
                skips = 0
Martin Bauer's avatar
Martin Bauer committed
252
253
                for common_symbol in subexpression_coefficient_dict.keys():
                    if common_symbol not in expr_coefficients:
254
255
                        skips += 1
                        continue
Martin Bauer's avatar
Martin Bauer committed
256
                    factor = expr_coefficients[common_symbol] / subexpression_coefficient_dict[common_symbol]
257
258
                    factors[sp.simplify(factor)] += 1

Martin Bauer's avatar
Martin Bauer committed
259
260
261
                common_factor = max(factors.items(), key=operator.itemgetter(1))[0]
                if factors[common_factor] >= max(normalized_current_expr_match, normalized_replacement_match):
                    return current_expr - common_factor * subexpression + common_factor * replacement
262
263

        # if no subexpression was found
Martin Bauer's avatar
Martin Bauer committed
264
265
266
        param_list = [visit(a) for a in current_expr.args]
        if not param_list:
            return current_expr
267
        else:
268
            if current_expr.func == sp.Mul and Zero() in param_list:
Markus Holzer's avatar
Markus Holzer committed
269
                return sp.simplify(current_expr)
270
271
            else:
                return current_expr.func(*param_list, evaluate=False)
272
273
274
275

    return visit(expr)


Martin Bauer's avatar
Martin Bauer committed
276
277
278
def replace_second_order_products(expr: sp.Expr, search_symbols: Iterable[sp.Symbol],
                                  positive: Optional[bool] = None,
                                  replace_mixed: Optional[List[Assignment]] = None) -> sp.Expr:
279
    """Replaces second order mixed terms like 4*x*y by 2*( (x+y)**2 - x**2 - y**2 ).
Martin Bauer's avatar
Martin Bauer committed
280

281
282
    This makes the term longer - simplify usually is undoing these - however this
    transformation can be done to find more common sub-expressions
Martin Bauer's avatar
Martin Bauer committed
283
284
285
286
287
288
289
290
291
292
293

    Args:
        expr: input expression
        search_symbols: symbols that are searched for
                         for example, given [x,y,z] terms like x*y, x*z, z*y are replaced
        positive: there are two ways to do this substitution, either with term
                 (x+y)**2 or (x-y)**2 . if positive=True the first version is done,
                 if positive=False the second version is done, if positive=None the
                 sign is determined by the sign of the mixed term that is replaced
        replace_mixed: if a list is passed here, the expr x+y or x-y is replaced by a special new symbol
                       and the replacement equation is added to the list
294
    """
Martin Bauer's avatar
Martin Bauer committed
295
    mixed_symbols_replaced = set([e.lhs for e in replace_mixed]) if replace_mixed is not None else set()
296
297

    if expr.is_Mul:
Martin Bauer's avatar
Martin Bauer committed
298
299
        distinct_search_symbols = set()
        nr_of_search_terms = 0
300
        other_factors = sp.Integer(1)
301
        for t in expr.args:
Martin Bauer's avatar
Martin Bauer committed
302
303
304
            if t in search_symbols:
                nr_of_search_terms += 1
                distinct_search_symbols.add(t)
305
            else:
Martin Bauer's avatar
Martin Bauer committed
306
307
308
                other_factors *= t
        if len(distinct_search_symbols) == 2 and nr_of_search_terms == 2:
            u, v = sorted(list(distinct_search_symbols), key=lambda symbol: symbol.name)
309
            if positive is None:
Martin Bauer's avatar
Martin Bauer committed
310
311
312
313
                other_factors_without_symbols = other_factors
                for s in other_factors.atoms(sp.Symbol):
                    other_factors_without_symbols = other_factors_without_symbols.subs(s, 1)
                positive = other_factors_without_symbols.is_positive
314
315
                assert positive is not None
            sign = 1 if positive else -1
Martin Bauer's avatar
Martin Bauer committed
316
317
318
319
320
321
322
            if replace_mixed is not None:
                new_symbol_str = 'P' if positive else 'M'
                mixed_symbol_name = u.name + new_symbol_str + v.name
                mixed_symbol = sp.Symbol(mixed_symbol_name.replace("_", ""))
                if mixed_symbol not in mixed_symbols_replaced:
                    mixed_symbols_replaced.add(mixed_symbol)
                    replace_mixed.append(Assignment(mixed_symbol, u + sign * v))
323
            else:
Martin Bauer's avatar
Martin Bauer committed
324
325
                mixed_symbol = u + sign * v
            return sp.Rational(1, 2) * sign * other_factors * (mixed_symbol ** 2 - u ** 2 - v ** 2)
326

Martin Bauer's avatar
Martin Bauer committed
327
328
    param_list = [replace_second_order_products(a, search_symbols, positive, replace_mixed) for a in expr.args]
    result = expr.func(*param_list, evaluate=False) if param_list else expr
329
330
331
    return result


Martin Bauer's avatar
Martin Bauer committed
332
333
def remove_higher_order_terms(expr: sp.Expr, symbols: Sequence[sp.Symbol], order: int = 3) -> sp.Expr:
    """Removes all terms that contain more than 'order' factors of given 'symbols'
Martin Bauer's avatar
Martin Bauer committed
334
335
336
337

    Example:
        >>> x, y = sp.symbols("x y")
        >>> term = x**2 * y + y**2 * x + y**3 + x + y ** 2
Martin Bauer's avatar
Martin Bauer committed
338
        >>> remove_higher_order_terms(term, order=2, symbols=[x, y])
Martin Bauer's avatar
Martin Bauer committed
339
        x + y**2
340
341
342
343
344
    """
    from sympy.core.power import Pow
    from sympy.core.add import Add, Mul

    result = 0
Martin Bauer's avatar
Martin Bauer committed
345
    expr = expr.expand()
346

Martin Bauer's avatar
Martin Bauer committed
347
348
    def velocity_factors_in_product(product):
        factor_count = 0
Martin Bauer's avatar
Martin Bauer committed
349
350
351
352
        if type(product) is Mul:
            for factor in product.args:
                if type(factor) == Pow:
                    if factor.args[0] in symbols:
Martin Bauer's avatar
Martin Bauer committed
353
                        factor_count += factor.args[1]
Martin Bauer's avatar
Martin Bauer committed
354
                if factor in symbols:
Martin Bauer's avatar
Martin Bauer committed
355
                    factor_count += 1
Martin Bauer's avatar
Martin Bauer committed
356
357
        elif type(product) is Pow:
            if product.args[0] in symbols:
Martin Bauer's avatar
Martin Bauer committed
358
359
                factor_count += product.args[1]
        return factor_count
360

Martin Bauer's avatar
Martin Bauer committed
361
362
363
    if type(expr) == Mul or type(expr) == Pow:
        if velocity_factors_in_product(expr) <= order:
            return expr
364
        else:
Markus Holzer's avatar
Markus Holzer committed
365
            return Zero()
366

Martin Bauer's avatar
Martin Bauer committed
367
368
    if type(expr) != Add:
        return expr
369

Martin Bauer's avatar
Martin Bauer committed
370
371
372
    for sum_term in expr.args:
        if velocity_factors_in_product(sum_term) <= order:
            result += sum_term
373
374
375
    return result


Martin Bauer's avatar
Martin Bauer committed
376
377
378
def complete_the_square(expr: sp.Expr, symbol_to_complete: sp.Symbol,
                        new_variable: sp.Symbol) -> Tuple[sp.Expr, Optional[Tuple[sp.Symbol, sp.Expr]]]:
    """Transforms second order polynomial into only squared part.
379

Martin Bauer's avatar
Martin Bauer committed
380
381
382
383
384
385
386
387
    Examples:
        >>> a, b, c, s, n = sp.symbols("a b c s n")
        >>> expr = a * s**2 + b * s + c
        >>> completed_expr, substitution = complete_the_square(expr, symbol_to_complete=s, new_variable=n)
        >>> completed_expr
        a*n**2 + c - b**2/(4*a)
        >>> substitution
        (n, s + b/(2*a))
388

Martin Bauer's avatar
Martin Bauer committed
389
    Returns:
Martin Bauer's avatar
Martin Bauer committed
390
        (replaced_expr, tuple to pass to subs, such that old expr comes out again)
391
    """
Martin Bauer's avatar
Martin Bauer committed
392
393
394
    p = sp.Poly(expr, symbol_to_complete)
    coefficients = p.all_coeffs()
    if len(coefficients) != 3:
395
        return expr, None
Martin Bauer's avatar
Martin Bauer committed
396
397
398
    a, b, _ = coefficients
    expr = expr.subs(symbol_to_complete, new_variable - b / (2 * a))
    return sp.simplify(expr), (new_variable, symbol_to_complete + b / (2 * a))
399
400


Martin Bauer's avatar
Martin Bauer committed
401
402
403
404
405
406
def complete_the_squares_in_exp(expr: sp.Expr, symbols_to_complete: Sequence[sp.Symbol]):
    """Completes squares in arguments of exponential which makes them simpler to integrate.

    Very useful for integrating Maxwell-Boltzmann equilibria and its moment generating function
    """
    dummies = [sp.Dummy() for _ in symbols_to_complete]
407
408
409

    def visit(term):
        if term.func == sp.exp:
Martin Bauer's avatar
Martin Bauer committed
410
411
412
413
            exp_arg = term.args[0]
            for symbol_to_complete, dummy in zip(symbols_to_complete, dummies):
                exp_arg, substitution = complete_the_square(exp_arg, symbol_to_complete, dummy)
            return sp.exp(sp.expand(exp_arg))
414
        else:
Martin Bauer's avatar
Martin Bauer committed
415
416
            param_list = [visit(a) for a in term.args]
            if not param_list:
417
418
                return term
            else:
Martin Bauer's avatar
Martin Bauer committed
419
                return term.func(*param_list)
420
421

    result = visit(expr)
Martin Bauer's avatar
Martin Bauer committed
422
423
    for s, d in zip(symbols_to_complete, dummies):
        result = result.subs(d, s)
424
425
426
    return result


Martin Bauer's avatar
Martin Bauer committed
427
def extract_most_common_factor(term):
428
    """Processes a sum of fractions: determines the most common factor and splits term in common factor and rest"""
Martin Bauer's avatar
Martin Bauer committed
429
430
431
    coefficient_dict = term.as_coefficients_dict()
    counter = Counter([Abs(v) for v in coefficient_dict.values()])
    common_factor, occurrences = max(counter.items(), key=operator.itemgetter(1))
Martin Bauer's avatar
Martin Bauer committed
432
    if occurrences == 1 and (1 in counter):
Martin Bauer's avatar
Martin Bauer committed
433
434
        common_factor = 1
    return common_factor, term / common_factor
435
436


437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
def recursive_collect(expr, symbols, order_by_occurences=False):
    """Applies sympy.collect recursively for a list of symbols, collecting symbol 2 in the coefficients of symbol 1, 
    and so on.

    Args:
        expr: A sympy expression
        symbols: A sequence of symbols
        order_by_occurences: If True, during recursive descent, always collect the symbol occuring 
                             most often in the expression.
    """
    if order_by_occurences:
        symbols = list(expr.atoms(sp.Symbol) & set(symbols))
        symbols = sorted(symbols, key=expr.count, reverse=True)
    if len(symbols) == 0:
        return expr
    symbol = symbols[0]
    collected_poly = sp.Poly(expr.collect(symbol), symbol)
    coeffs = collected_poly.all_coeffs()[::-1]
    rec_sum = sum(symbol**i * recursive_collect(c, symbols[1:], order_by_occurences) for i, c in enumerate(coeffs))
    return rec_sum


Frederik Hennig's avatar
Frederik Hennig committed
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
def summands(expr):
    return set(expr.args) if isinstance(expr, sp.Add) else {expr}


def simplify_by_equality(expr, a, b, c):
    """
    Uses the equality a = b + c, where a and b must be symbols, to simplify expr 
    by attempting to express additive combinations of two quantities by the third.

    This works on expressions that are reducible to the form 
    :math:`a * (...) + b * (...) + c * (...)`,
    without any mixed terms of a, b and c.
    """
    if not isinstance(a, sp.Symbol) or not isinstance(b, sp.Symbol):
        raise ValueError("a and b must be symbols.")

    c = sp.sympify(c)

    if not (isinstance(c, sp.Symbol) or is_constant(c)):
        raise ValueError("c must be either a symbol or a constant!")

    expr = sp.sympify(expr)

    expr_expanded = sp.expand(expr)
    a_coeff = expr_expanded.coeff(a, 1)
    expr_expanded -= (a * a_coeff).expand()
    b_coeff = expr_expanded.coeff(b, 1)
    expr_expanded -= (b * b_coeff).expand()
    if isinstance(c, sp.Symbol):
        c_coeff = expr_expanded.coeff(c, 1)
        rest = expr_expanded - (c * c_coeff).expand()
    else:
        c_coeff = expr_expanded / c
        rest = 0

    a_summands = summands(a_coeff)
    b_summands = summands(b_coeff)
    c_summands = summands(c_coeff)

    # replace b + c by a
    b_plus_c_coeffs = b_summands & c_summands
    for coeff in b_plus_c_coeffs:
        rest += a * coeff
    b_summands -= b_plus_c_coeffs
    c_summands -= b_plus_c_coeffs

    # replace a - b by c
    neg_b_summands = {-x for x in b_summands}
    a_minus_b_coeffs = a_summands & neg_b_summands
    for coeff in a_minus_b_coeffs:
        rest += c * coeff
    a_summands -= a_minus_b_coeffs
    b_summands -= {-x for x in a_minus_b_coeffs}

    # replace a - c by b
    neg_c_summands = {-x for x in c_summands}
    a_minus_c_coeffs = a_summands & neg_c_summands
    for coeff in a_minus_c_coeffs:
        rest += b * coeff
    a_summands -= a_minus_c_coeffs
    c_summands -= {-x for x in a_minus_c_coeffs}

    # put it back together
    return (rest + a * sum(a_summands) + b * sum(b_summands) + c * sum(c_summands)).expand()


525
def count_operations(term: Union[sp.Expr, List[sp.Expr], List[Assignment]],
Martin Bauer's avatar
Martin Bauer committed
526
527
                     only_type: Optional[str] = 'real') -> Dict[str, int]:
    """Counts the number of additions, multiplications and division.
Martin Bauer's avatar
Martin Bauer committed
528

Martin Bauer's avatar
Martin Bauer committed
529
530
531
    Args:
        term: a sympy expression (term, assignment) or sequence of sympy objects
        only_type: 'real' or 'int' to count only operations on these types, or None for all
Martin Bauer's avatar
Martin Bauer committed
532

Martin Bauer's avatar
Martin Bauer committed
533
534
    Returns:
        dict with 'adds', 'muls' and 'divs' keys
535
    """
536
537
538
539
    from pystencils.fast_approximation import fast_sqrt, fast_inv_sqrt, fast_division

    result = {'adds': 0, 'muls': 0, 'divs': 0, 'sqrts': 0,
              'fast_sqrts': 0, 'fast_inv_sqrts': 0, 'fast_div': 0}
540
541
    if isinstance(term, Sequence):
        for element in term:
Martin Bauer's avatar
Martin Bauer committed
542
            r = count_operations(element, only_type)
Martin Bauer's avatar
Martin Bauer committed
543
544
            for operation_name in result.keys():
                result[operation_name] += r[operation_name]
545
        return result
546
    elif isinstance(term, Assignment):
547
548
        term = term.rhs

Martin Bauer's avatar
Martin Bauer committed
549
550
    def check_type(e):
        if only_type is None:
551
            return True
552
553
554
        if isinstance(e, FieldPointerSymbol) and only_type == "real":
            return only_type == "int"

555
        try:
556
            base_type = get_type_of_expression(e)
557
558
        except ValueError:
            return False
559
560
        if isinstance(base_type, VectorType):
            return False
561
562
        if isinstance(base_type, PointerType):
            return only_type == 'int'
Martin Bauer's avatar
Martin Bauer committed
563
        if only_type == 'int' and (base_type.is_int() or base_type.is_uint()):
564
            return True
Martin Bauer's avatar
Martin Bauer committed
565
        if only_type == 'real' and (base_type.is_float()):
566
567
            return True
        else:
Martin Bauer's avatar
Martin Bauer committed
568
            return base_type == only_type
569

570
    def visit(t):
Martin Bauer's avatar
Martin Bauer committed
571
        visit_children = True
572
        if t.func is sp.Add:
Martin Bauer's avatar
Martin Bauer committed
573
            if check_type(t):
574
                result['adds'] += len(t.args) - 1
Julian Hammer's avatar
Julian Hammer committed
575
576
        elif t.func in [sp.Or, sp.And]:
            pass
577
        elif t.func is sp.Mul:
Martin Bauer's avatar
Martin Bauer committed
578
            if check_type(t):
Markus Holzer's avatar
Markus Holzer committed
579
                result['muls'] += len(t.args) - 1
580
581
582
                for a in t.args:
                    if a == 1 or a == -1:
                        result['muls'] -= 1
Martin Bauer's avatar
Martin Bauer committed
583
        elif isinstance(t, sp.Float) or isinstance(t, sp.Rational):
584
585
            pass
        elif isinstance(t, sp.Symbol):
Martin Bauer's avatar
Martin Bauer committed
586
            visit_children = False
587
        elif isinstance(t, sp.Indexed):
Martin Bauer's avatar
Martin Bauer committed
588
            visit_children = False
589
590
        elif t.is_integer:
            pass
591
        elif isinstance(t, cast_func):
Martin Bauer's avatar
Martin Bauer committed
592
593
            visit_children = False
            visit(t.args[0])
594
595
596
597
598
599
        elif t.func is fast_sqrt:
            result['fast_sqrts'] += 1
        elif t.func is fast_inv_sqrt:
            result['fast_inv_sqrts'] += 1
        elif t.func is fast_division:
            result['fast_div'] += 1
600
        elif t.func is sp.Pow:
Martin Bauer's avatar
Martin Bauer committed
601
            if check_type(t.args[0]):
602
                visit_children = True
603
604
605
606
                if t.exp.is_integer and t.exp.is_number:
                    if t.exp >= 0:
                        result['muls'] += int(t.exp) - 1
                    else:
Markus Holzer's avatar
Markus Holzer committed
607
608
                        if result['muls'] > 0:
                            result['muls'] -= 1
609
610
                        result['divs'] += 1
                        result['muls'] += (-int(t.exp)) - 1
611
612
                elif sp.nsimplify(t.exp) == sp.Rational(1, 2):
                    result['sqrts'] += 1
613
614
615
                elif sp.nsimplify(t.exp) == -sp.Rational(1, 2):
                    result["sqrts"] += 1
                    result["divs"] += 1
616
                else:
617
                    warnings.warn(f"Cannot handle exponent {t.exp} of sp.Pow node")
618
619
620
            else:
                warnings.warn("Counting operations: only integer exponents are supported in Pow, "
                              "counting will be inaccurate")
621
622
623
624
        elif t.func is sp.Piecewise:
            for child_term, condition in t.args:
                visit(child_term)
            visit_children = False
625
626
        elif isinstance(t, sp.Rel):
            pass
627
        else:
628
            warnings.warn(f"Unknown sympy node of type {str(t.func)} counting will be inaccurate")
629

Martin Bauer's avatar
Martin Bauer committed
630
        if visit_children:
631
632
633
634
635
            for a in t.args:
                visit(a)

    visit(term)
    return result
636
637


Martin Bauer's avatar
Martin Bauer committed
638
639
def count_operations_in_ast(ast) -> Dict[str, int]:
    """Counts number of operations in an abstract syntax tree, see also :func:`count_operations`"""
640
    from pystencils.astnodes import SympyAssignment
641
    result = defaultdict(int)
642
643
644

    def visit(node):
        if isinstance(node, SympyAssignment):
Martin Bauer's avatar
Martin Bauer committed
645
            r = count_operations(node.rhs)
646
647
            for k, v in r.items():
                result[k] += v
648
649
650
651
652
653
654
        else:
            for arg in node.args:
                visit(arg)
    visit(ast)
    return result


Martin Bauer's avatar
Martin Bauer committed
655
656
def common_denominator(expr: sp.Expr) -> sp.Expr:
    """Finds least common multiple of all denominators occurring in an expression"""
657
658
    denominators = [r.q for r in expr.atoms(sp.Rational)]
    return sp.lcm(denominators)
659

Martin Bauer's avatar
Martin Bauer committed
660

Martin Bauer's avatar
Martin Bauer committed
661
def get_symmetric_part(expr: sp.Expr, symbols: Iterable[sp.Symbol]) -> sp.Expr:
Martin Bauer's avatar
Martin Bauer committed
662
663
664
    """
    Returns the symmetric part of a sympy expressions.

Martin Bauer's avatar
Martin Bauer committed
665
666
667
668
669
670
    Args:
        expr: sympy expression, labeled here as :math:`f`
        symbols: sequence of symbols which are considered as degrees of freedom, labeled here as :math:`x_0, x_1,...`

    Returns:
        :math:`\frac{1}{2} [ f(x_0, x_1, ..) + f(-x_0, -x_1) ]`
Martin Bauer's avatar
Martin Bauer committed
671
    """
Martin Bauer's avatar
Martin Bauer committed
672
673
    substitution_dict = {e: -e for e in symbols}
    return sp.Rational(1, 2) * (expr + expr.subs(substitution_dict))
674
675


Martin Bauer's avatar
Martin Bauer committed
676
677
678
class SymbolCreator:
    def __getattribute__(self, name):
        return sp.Symbol(name)