How to fill an empty Sympy Piecewise function?

43 Views Asked by At

I have a function called 'symbolic_a0(array, T)' and the objective of that function is to create a piecewise function from the array that is given. The way that the function works is the following:

  1. Create the symbols.
  2. Create an empty Piecewise function.
  3. Iterate the array and fill the empty piecewise function.
  4. In this case do a symbolic integration of the piecewise function.

But when I try to run the code, the line "piecewise_expr = smp.Piecewise()" gives me the next error: At least one (expr, cond) pair expected.

import numpy as np
import sympy as smp

def symbolic_a0(array, T):
  t = smp.symbols('t', real=True)
  piecewise_expr = smp.Piecewise() # Create an empty piecewise function.

  # Build the Piecewise function from the array
  for segment in array:
    equation_lambda_numpy = lambda t: eval(segment["equation"].get()) # Lambda function with numpy expressions
    equation_sympy = smp.sympify(equation_lambda_numpy(t))
    lower_bound = int(segment["lower_bound"].get())
    upper_bound = int(segment["upper_bound"].get())
    piecewise_expr += (equation_sympy, (t, lower_bound, upper_bound))

  return smp.integrate(piecewise_expr, (t, 0, T))

The array that is given:

piecewise_data = [
    {"equation": 0, "lower_bound": -2, "upper_bound": -1},
    {"equation": 1, "lower_bound": -1, "upper_bound": 1},
    {"equation": 0, "lower_bound": 1, "upper_bound": 2},
]

How do I get rid of this error?

The things that I already tried:

  1. piecewise_expr = smp.Piecewise(None, None).
  2. Giving it a dummy function, but I don't want to use it in my calculation.
1

There are 1 best solutions below

0
smichr On BEST ANSWER

Make a list of arguments for the Piecewise and create the Piecewise when you are done:

import numpy as np
import sympy as smp

def symbolic_a0(array, T):
  t = smp.symbols('t', real=True)
  r = lambda t, lo, hi: (t>lo) & (t < hi) 
  piecewise_args = []

  # Build the Piecewise function from the array
  for segment in array:
    equation_lambda_numpy = lambda t: eval(segment["equation"].get()) # Lambda function with numpy expressions
    equation_sympy = smp.sympify(equation_lambda_numpy(t))
    lower_bound = int(segment["lower_bound"].get())
    upper_bound = int(segment["upper_bound"].get())
    piecewise_args.append((equation_sympy, r(t, lower_bound, upper_bound)))

  return smp.integrate(Piecewise(*piecewise_args), (t, 0, T))

Note use of r to create relational from the symbols and bounds. Piecewise args are (expr, condition) tuples.