Skip to content

models

polynomial

Polynomial

Bases: ObjBase

A polynomial model.

Parameters

name : str The name of the model. degree : int The degree of the polynomial.

Source code in src/easyscience/models/polynomial.py
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
class Polynomial(ObjBase):
    """A polynomial model.

    Parameters
    ----------
    name : str
        The name of the model.
    degree : int
        The degree of the polynomial.
    """

    coefficients: ClassVar[CollectionBase]

    def __init__(
        self,
        name: str = 'polynomial',
        coefficients: Optional[Union[Iterable[Union[float, Parameter]], CollectionBase]] = None,
    ):
        super(Polynomial, self).__init__(name, coefficients=CollectionBase('coefficients'))
        if coefficients is not None:
            if issubclass(type(coefficients), CollectionBase):
                self.coefficients = coefficients
            elif isinstance(coefficients, Iterable):
                for index, item in enumerate(coefficients):
                    if issubclass(type(item), Parameter):
                        self.coefficients.append(item)
                    elif isinstance(item, float):
                        self.coefficients.append(Parameter(name='c{}'.format(index), value=item))
                    else:
                        raise TypeError('Coefficients must be floats or Parameters')
            else:
                raise TypeError('coefficients must be a list or a CollectionBase')

    def __call__(self, x: np.ndarray, *args, **kwargs) -> np.ndarray:
        return np.polyval([c.value for c in self.coefficients], x)

    def __repr__(self):
        s = []
        if len(self.coefficients) >= 1:
            s += [f'{self.coefficients[0].value}']
            if len(self.coefficients) >= 2:
                s += [f'{self.coefficients[1].value}x']
                if len(self.coefficients) >= 3:
                    s += [
                        f'{c.value}x^{i + 2}'
                        for i, c in enumerate(self.coefficients[2:])
                        if c.value != 0
                    ]
        s.reverse()
        s = ' + '.join(s)
        return 'Polynomial({}, {})'.format(self.name, s)