Pytorch Torch Polar
## PyTorch `torch.polar` Function
`torch.polar` is a PyTorch function used to construct a complex tensor from its polar coordinates: absolute values (magnitudes) and angles (phases).
---
## Introduction
In mathematics, a complex number can be represented in polar form as:
$$z = r \cdot e^{i\theta} = r \cdot (\cos\theta + i\sin\theta)$$
Where:
* $r$ is the absolute value (magnitude or modulus).
* $\theta$ is the angle (phase or argument) in radians.
`torch.polar` takes these two components as input tensors and returns a complex tensor representing $z$. This is particularly useful in fields like Digital Signal Processing (DSP), Fourier analysis, and quantum computing simulations.
---
## Syntax and Parameters
### Syntax
```python
torch.polar(abs, angle, *, out=None) -> Tensor
```
### Parameters
| Parameter | Type | Description |
| :--- | :--- | :--- |
| **`abs`** | `Tensor` | The absolute value (magnitude) of the complex number. Must contain real values. |
| **`angle`** | `Tensor` | The angle (argument) of the complex number in radians. Must contain real values. |
| **`out`** (Optional) | `Tensor` | The output tensor. |
### Data Type Constraints
* `abs` and `angle` must have the same shape.
* `abs` and `angle` must be of float types (`torch.float32` or `torch.float64`).
* If the inputs are `torch.float32`, the returned tensor will be `torch.complex64`.
* If the inputs are `torch.float64`, the returned tensor will be `torch.complex128`.
---
## Code Examples
### Basic Example
The following example demonstrates how to create a 1D complex tensor from magnitude and phase tensors.
```python
import torch
# Create the absolute value (magnitude) tensor
abs_val = torch.tensor([1.0, 2.0, 3.0])
# Create the angle (radians) tensor
angle = torch.tensor([0.0, torch.pi / 2, torch.pi])
# Construct the complex tensor from polar coordinates
x = torch.polar(abs_val, angle)
print("Constructed Complex Tensor:")
print(x)
# Verify by extracting the magnitude and angle back
print("\nExtracted Absolute Values (Magnitudes):", x.abs())
print("Extracted Angles (Radians):", x.angle())
```
### Output
```text
Constructed Complex Tensor:
tensor([ 1.0000+0.0000j, 0.0000+2.0000j, -3.0000+0.0000j])
Extracted Absolute Values (Magnitudes): tensor([1., 2., 3.])
Extracted Angles (Radians): tensor([0.0000, 1.5708, 3.1416])
```
---
## Key Considerations
1. **Device Matching**: Both `abs` and `angle` must reside on the same device (e.g., both on CPU or both on the same GPU).
2. **Type Matching**: Both input tensors must have the same data type (e.g., both `torch.float32`). Mixing `float32` and `float64` will result in a runtime error.
3. **Inverse Operation**: You can perform the inverse operation (converting a complex tensor back to polar coordinates) using `torch.abs(x)` and `torch.angle(x)`.
YouTip