mapping.py 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. from typing import Callable, TypeVar
  2. import numpy as np
  3. from charged_shells.expansion import Expansion
  4. from charged_shells.parameters import ModelParams
  5. T = TypeVar('T')
  6. V = TypeVar('V')
  7. Array = np.ndarray
  8. def map_over_expansion(f: Callable[[Expansion, T], V]) -> Callable[[Expansion, T], V]:
  9. """Map a function f over all leading axes of an expansion. Uses for loops, so it is kinda slow."""
  10. def mapped_f(ex: Expansion, *args, **kwargs):
  11. og_shape = ex.shape
  12. flat_ex = ex.flatten()
  13. results = []
  14. for i in range(int(np.prod(og_shape))):
  15. results.append(f(flat_ex[i], *args, **kwargs))
  16. try:
  17. return np.array(results).reshape(og_shape + results[0].shape)
  18. except AttributeError:
  19. return np.array(results).reshape(og_shape)
  20. return mapped_f
  21. def unravel_params(params: ModelParams) -> list[ModelParams]:
  22. if isinstance(params.R, Array) and isinstance(params.kappa, Array):
  23. # if this is to be implemented, watch out for implementations of mapping expansions that depend
  24. # on one of the parameters in ModelParams over other functions that also take the same ModelParameters
  25. raise NotImplementedError("Currently only unravel over a single parameter is supported. ")
  26. if isinstance(params.R, Array):
  27. return [ModelParams(R=r, kappa=params.kappa) for r in params.R]
  28. if isinstance(params.kappa, Array):
  29. return [ModelParams(R=params.R, kappa=kappa) for kappa in params.kappa]
  30. if not (isinstance(params.R, Array) or isinstance(params.kappa, Array)):
  31. return [params]
  32. raise NotImplementedError
  33. def unravel_expansion_over_axis(ex: Expansion, axis: int | None, param_list_len: int) -> list[Expansion]:
  34. if axis is None:
  35. return [ex for _ in range(param_list_len)]
  36. axis_len = ex.shape[axis]
  37. if axis_len != param_list_len:
  38. raise ValueError(f'Parameter list has different length than the provided expansion axis, '
  39. f'got param_list_len={param_list_len} and axis_len={axis_len}.')
  40. return [Expansion(ex.l_array, np.take(ex.coefs, i, axis=axis)) for i in range(axis_len)]
  41. SingleExpansionFn = Callable[[Expansion, ModelParams], T]
  42. TwoExpansionsFn = Callable[[Expansion, Expansion, ModelParams], T]
  43. def parameter_map_single_expansion(f: SingleExpansionFn,
  44. match_expansion_axis_to_params: int = None) -> SingleExpansionFn:
  45. def mapped_f(ex: Expansion, params: ModelParams):
  46. params_list = unravel_params(params)
  47. expansion_list = unravel_expansion_over_axis(ex, match_expansion_axis_to_params, len(params_list))
  48. results = []
  49. for exp, prms in zip(expansion_list, params_list):
  50. results.append(f(exp, prms))
  51. if match_expansion_axis_to_params is not None:
  52. # return the params-matched axis to where it belongs
  53. return np.moveaxis(np.array(results), 0, match_expansion_axis_to_params)
  54. return np.squeeze(np.array(results))
  55. return mapped_f
  56. def parameter_map_two_expansions(f: TwoExpansionsFn,
  57. match_expansion_axis_to_params: int = None,
  58. ) -> TwoExpansionsFn:
  59. def mapped_f(ex1: Expansion, ex2: Expansion, params: ModelParams):
  60. params_list = unravel_params(params)
  61. expansion_list1 = unravel_expansion_over_axis(ex1, match_expansion_axis_to_params, len(params_list))
  62. expansion_list2 = unravel_expansion_over_axis(ex2, match_expansion_axis_to_params, len(params_list))
  63. results = []
  64. for exp1, exp2, prms in zip(expansion_list1, expansion_list2, params_list):
  65. results.append(f(exp1, exp2, prms))
  66. if match_expansion_axis_to_params is not None:
  67. # return the params-matched axis to where it belongs
  68. return np.moveaxis(np.array(results), 0, match_expansion_axis_to_params)
  69. return np.squeeze(np.array(results))
  70. return mapped_f