1"Utility functions for pulse generation and manipulation."
2
3import typing
4
5from typing import Callable
6
7g_out = typing.TypeVar("g_out")
8g_args = typing.TypeVar("g_args")
9g_kwargs = typing.TypeVar("g_kwargs")
10f_out = typing.TypeVar("f_out")
11f_args = typing.TypeVar("f_args")
12f_kwargs = typing.TypeVar("f_kwargs")
13
[docs]
14def compose(f: Callable[[g_out, f_args, f_kwargs], f_out],
15 g: Callable[[g_args, g_kwargs], g_out],
16 *args: f_args,
17 **kwargs: f_kwargs
18 ) -> Callable[[g_args, g_kwargs], f_out]:
19 """
20 Creates a function ``h`` given by the composition of `f` and `g`::
21
22 h(...)=f(g(...))
23
24 That is the output of `g` is piped into the first argument of `f`.
25
26 Additionally, additionaly arguments and keyword arguments can be passed to
27 `f` using `args` and `kwargs`::
28
29 h(...)=f(g(...), *args, **kwargs)
30
31 Explicitly ``h`` is defined as::
32
33 h = lambda *a, **kw: f(g(*a, **kw), *args, **kwargs)
34
35 Parameters
36 ----------
37 f : Callable[[g_out, f_args, f_kwargs], f_out]
38 The second function to be called in the composition
39 g : Callable[[g_args, g_kwargs], g_out]
40 The first function to be called in the composition
41 *args : f_args
42 Additional arguments to pass to ``f``
43 **kwargs : f_kwargs
44 Additional keyword arguments to pass to ``f``
45
46 Returns
47 -------
48 Callable[[g_args, g_kwargs], f_out]
49 The composite function ``h``
50
51 See Also
52 --------
53 :func:`compose_unpack()`
54 """
55 return lambda *a, **kw: f(g(*a, **kw), *args, **kwargs)
56
[docs]
57def compose_unpack(f: Callable[[g_out, f_args, f_kwargs], f_out],
58 g: Callable[[g_args, g_kwargs], g_out],
59 *args: f_args,
60 **kwargs: f_kwargs
61 ) -> Callable[[g_args, g_kwargs], f_out]:
62 """
63 Creates a function ``h`` given by the composition of `f` and ``*g``::
64
65 h(...) = f(*g(...))
66
67 That is the output of `g` is unpacked and piped into the arguments of `f`.
68
69 Additionally, additionaly arguments and keyword arguments can be passed to
70 `f` using `args` and `kwargs`::
71
72 h(...) = f(*g(...), *args, **kwargs)
73
74 Explicitly ``h`` is defined as::
75
76 h = lambda *a, **kw: f(*g(*a, **kw), *args, **kwargs)
77
78 Parameters
79 ----------
80 f : Callable[[g_out, f_args, f_kwargs], f_out]
81 The second function to be called in the composition
82 g : Callable[[g_args, g_kwargs], g_out]
83 The first function to be called in the composition
84 *args : f_args
85 Additional arguments to pass to ``f``
86 **kwargs : f_kwargs
87 Additional keyword arguments to pass to ``f``
88
89 Returns
90 -------
91 Callable[[g_args, g_kwargs], f_out]
92 The composite function ``h``
93
94 See Also
95 --------
96 :func:`compose()`
97 """
98 return lambda *a, **kw: f(*g(*a, **kw), *args, **kwargs)