complex_utils.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191
  1. """Beamformer module."""
  2. from distutils.version import LooseVersion
  3. from typing import Sequence
  4. from typing import Tuple
  5. from typing import Union
  6. import torch
  7. from torch_complex import functional as FC
  8. from torch_complex.tensor import ComplexTensor
  9. EPS = torch.finfo(torch.double).eps
  10. is_torch_1_8_plus = LooseVersion(torch.__version__) >= LooseVersion("1.8.0")
  11. is_torch_1_9_plus = LooseVersion(torch.__version__) >= LooseVersion("1.9.0")
  12. def new_complex_like(
  13. ref: Union[torch.Tensor, ComplexTensor],
  14. real_imag: Tuple[torch.Tensor, torch.Tensor],
  15. ):
  16. if isinstance(ref, ComplexTensor):
  17. return ComplexTensor(*real_imag)
  18. elif is_torch_complex_tensor(ref):
  19. return torch.complex(*real_imag)
  20. else:
  21. raise ValueError(
  22. "Please update your PyTorch version to 1.9+ for complex support."
  23. )
  24. def is_torch_complex_tensor(c):
  25. return (
  26. not isinstance(c, ComplexTensor) and is_torch_1_9_plus and torch.is_complex(c)
  27. )
  28. def is_complex(c):
  29. return isinstance(c, ComplexTensor) or is_torch_complex_tensor(c)
  30. def to_double(c):
  31. if not isinstance(c, ComplexTensor) and is_torch_1_9_plus and torch.is_complex(c):
  32. return c.to(dtype=torch.complex128)
  33. else:
  34. return c.double()
  35. def to_float(c):
  36. if not isinstance(c, ComplexTensor) and is_torch_1_9_plus and torch.is_complex(c):
  37. return c.to(dtype=torch.complex64)
  38. else:
  39. return c.float()
  40. def cat(seq: Sequence[Union[ComplexTensor, torch.Tensor]], *args, **kwargs):
  41. if not isinstance(seq, (list, tuple)):
  42. raise TypeError(
  43. "cat(): argument 'tensors' (position 1) must be tuple of Tensors, "
  44. "not Tensor"
  45. )
  46. if isinstance(seq[0], ComplexTensor):
  47. return FC.cat(seq, *args, **kwargs)
  48. else:
  49. return torch.cat(seq, *args, **kwargs)
  50. def complex_norm(
  51. c: Union[torch.Tensor, ComplexTensor], dim=-1, keepdim=False
  52. ) -> torch.Tensor:
  53. if not is_complex(c):
  54. raise TypeError("Input is not a complex tensor.")
  55. if is_torch_complex_tensor(c):
  56. return torch.norm(c, dim=dim, keepdim=keepdim)
  57. else:
  58. return torch.sqrt(
  59. (c.real**2 + c.imag**2).sum(dim=dim, keepdim=keepdim) + EPS
  60. )
  61. def einsum(equation, *operands):
  62. # NOTE: Do not mix ComplexTensor and torch.complex in the input!
  63. # NOTE (wangyou): Until PyTorch 1.9.0, torch.einsum does not support
  64. # mixed input with complex and real tensors.
  65. if len(operands) == 1:
  66. if isinstance(operands[0], (tuple, list)):
  67. operands = operands[0]
  68. complex_module = FC if isinstance(operands[0], ComplexTensor) else torch
  69. return complex_module.einsum(equation, *operands)
  70. elif len(operands) != 2:
  71. op0 = operands[0]
  72. same_type = all(op.dtype == op0.dtype for op in operands[1:])
  73. if same_type:
  74. _einsum = FC.einsum if isinstance(op0, ComplexTensor) else torch.einsum
  75. return _einsum(equation, *operands)
  76. else:
  77. raise ValueError("0 or More than 2 operands are not supported.")
  78. a, b = operands
  79. if isinstance(a, ComplexTensor) or isinstance(b, ComplexTensor):
  80. return FC.einsum(equation, a, b)
  81. elif is_torch_1_9_plus and (torch.is_complex(a) or torch.is_complex(b)):
  82. if not torch.is_complex(a):
  83. o_real = torch.einsum(equation, a, b.real)
  84. o_imag = torch.einsum(equation, a, b.imag)
  85. return torch.complex(o_real, o_imag)
  86. elif not torch.is_complex(b):
  87. o_real = torch.einsum(equation, a.real, b)
  88. o_imag = torch.einsum(equation, a.imag, b)
  89. return torch.complex(o_real, o_imag)
  90. else:
  91. return torch.einsum(equation, a, b)
  92. else:
  93. return torch.einsum(equation, a, b)
  94. def inverse(
  95. c: Union[torch.Tensor, ComplexTensor]
  96. ) -> Union[torch.Tensor, ComplexTensor]:
  97. if isinstance(c, ComplexTensor):
  98. return c.inverse2()
  99. else:
  100. return c.inverse()
  101. def matmul(
  102. a: Union[torch.Tensor, ComplexTensor], b: Union[torch.Tensor, ComplexTensor]
  103. ) -> Union[torch.Tensor, ComplexTensor]:
  104. # NOTE: Do not mix ComplexTensor and torch.complex in the input!
  105. # NOTE (wangyou): Until PyTorch 1.9.0, torch.matmul does not support
  106. # multiplication between complex and real tensors.
  107. if isinstance(a, ComplexTensor) or isinstance(b, ComplexTensor):
  108. return FC.matmul(a, b)
  109. elif is_torch_1_9_plus and (torch.is_complex(a) or torch.is_complex(b)):
  110. if not torch.is_complex(a):
  111. o_real = torch.matmul(a, b.real)
  112. o_imag = torch.matmul(a, b.imag)
  113. return torch.complex(o_real, o_imag)
  114. elif not torch.is_complex(b):
  115. o_real = torch.matmul(a.real, b)
  116. o_imag = torch.matmul(a.imag, b)
  117. return torch.complex(o_real, o_imag)
  118. else:
  119. return torch.matmul(a, b)
  120. else:
  121. return torch.matmul(a, b)
  122. def trace(a: Union[torch.Tensor, ComplexTensor]):
  123. # NOTE (wangyou): until PyTorch 1.9.0, torch.trace does not
  124. # support bacth processing. Use FC.trace() as fallback.
  125. return FC.trace(a)
  126. def reverse(a: Union[torch.Tensor, ComplexTensor], dim=0):
  127. if isinstance(a, ComplexTensor):
  128. return FC.reverse(a, dim=dim)
  129. else:
  130. return torch.flip(a, dims=(dim,))
  131. def solve(b: Union[torch.Tensor, ComplexTensor], a: Union[torch.Tensor, ComplexTensor]):
  132. """Solve the linear equation ax = b."""
  133. # NOTE: Do not mix ComplexTensor and torch.complex in the input!
  134. # NOTE (wangyou): Until PyTorch 1.9.0, torch.solve does not support
  135. # mixed input with complex and real tensors.
  136. if isinstance(a, ComplexTensor) or isinstance(b, ComplexTensor):
  137. if isinstance(a, ComplexTensor) and isinstance(b, ComplexTensor):
  138. return FC.solve(b, a, return_LU=False)
  139. else:
  140. return matmul(inverse(a), b)
  141. elif is_torch_1_9_plus and (torch.is_complex(a) or torch.is_complex(b)):
  142. if torch.is_complex(a) and torch.is_complex(b):
  143. return torch.linalg.solve(a, b)
  144. else:
  145. return matmul(inverse(a), b)
  146. else:
  147. if is_torch_1_8_plus:
  148. return torch.linalg.solve(a, b)
  149. else:
  150. return torch.solve(b, a)[0]
  151. def stack(seq: Sequence[Union[ComplexTensor, torch.Tensor]], *args, **kwargs):
  152. if not isinstance(seq, (list, tuple)):
  153. raise TypeError(
  154. "stack(): argument 'tensors' (position 1) must be tuple of Tensors, "
  155. "not Tensor"
  156. )
  157. if isinstance(seq[0], ComplexTensor):
  158. return FC.stack(seq, *args, **kwargs)
  159. else:
  160. return torch.stack(seq, *args, **kwargs)