map_abstract.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. # map_abstract.py: abstract class for algebraic maps
  2. # Copyright 2022 Romain Serra
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from abc import ABCMeta
  15. import numpy as np
  16. from swiftt.algebraic_abstract import AlgebraicAbstract
  17. class MapAbstract(AlgebraicAbstract, metaclass=ABCMeta):
  18. """Abstract class for "maps" i.e. vectors of a given algebraic type.
  19. Attributes:
  20. _len (int): length.
  21. _items (numpy.array): components.
  22. """
  23. def __init__(self, elements) -> None:
  24. self._len = len(elements)
  25. self._items = np.array(elements, dtype=elements[0].__class__)
  26. def __len__(self) -> int:
  27. return self._len
  28. def __getitem__(self, item: int):
  29. return self._items[item]
  30. def __setitem__(self, item: int, value) -> None:
  31. self._items[item] = value
  32. def copy(self) -> "MapAbstract":
  33. return self.__class__(self._items)
  34. def __add__(self, other) -> "MapAbstract":
  35. return self.__class__(self._items + other)
  36. def __sub__(self, other) -> "MapAbstract":
  37. return self.__class__(self._items - other)
  38. def __rsub__(self, other) -> "MapAbstract":
  39. return self.__class__(-self._items + other)
  40. def __mul__(self, other) -> "MapAbstract":
  41. return self.__class__(self._items * other)
  42. def __truediv__(self, other) -> "MapAbstract":
  43. return self.__class__(self._items / other)
  44. def __rtruediv__(self, other) -> "MapAbstract":
  45. return self.__class__(other / self._items)
  46. def __pow__(self, power, modulo=None) -> "MapAbstract":
  47. return self.__class__([el.__pow__(power, modulo) for el in self])
  48. def __str__(self) -> str:
  49. string = str(self[0])
  50. for el in self[1:]:
  51. string += ", " + str(el)
  52. return "( " + string + " )"
  53. def sqrt(self) -> "MapAbstract":
  54. return self.__class__([el.sqrt() for el in self])
  55. def exp(self) -> "MapAbstract":
  56. return self.__class__([el.exp() for el in self])
  57. def log(self) -> "MapAbstract":
  58. return self.__class__([el.log() for el in self])
  59. def dot(self, other):
  60. return sum(el1 * el2 for el1, el2 in zip(self, other))