{"id":29258690,"url":"https://github.com/NeoVertex1/ComplexTensor","last_synced_at":"2025-07-04T06:03:36.542Z","repository":{"id":257023705,"uuid":"857216109","full_name":"NeoVertex1/ComplexTensor","owner":"NeoVertex1","description":"ComplexTensor: Machine Learning By Bridging Classical and Quantum Computation","archived":false,"fork":false,"pushed_at":"2024-11-20T22:05:11.000Z","size":21093,"stargazers_count":75,"open_issues_count":8,"forks_count":8,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-01T22:11:06.769Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/NeoVertex1.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-09-14T04:21:35.000Z","updated_at":"2025-03-21T14:54:00.000Z","dependencies_parsed_at":"2024-10-26T03:30:56.971Z","dependency_job_id":"ca7864e1-4cbf-45ed-be51-bac48765d6a9","html_url":"https://github.com/NeoVertex1/ComplexTensor","commit_stats":null,"previous_names":["neovertex1/complextensor"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/NeoVertex1/ComplexTensor","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeoVertex1%2FComplexTensor","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeoVertex1%2FComplexTensor/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeoVertex1%2FComplexTensor/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeoVertex1%2FComplexTensor/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/NeoVertex1","download_url":"https://codeload.github.com/NeoVertex1/ComplexTensor/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/NeoVertex1%2FComplexTensor/sbom","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":263150522,"owners_count":23421583,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-07-04T06:02:05.925Z","updated_at":"2025-07-04T06:03:36.526Z","avatar_url":"https://github.com/NeoVertex1.png","language":"Python","readme":"\n# ComplexTensor\n\n\n### **_new:_** \n\u003e 🚀 ` The tutorial is now available for preliminary testing. It covers essential operations with complex numbers and demonstrates the library's functionalities relevant to research applications. Please post any questions or suggestions in the issues section. ` [link to colab](https://colab.research.google.com/drive/1GCJt2a71WgrDd3OvIdsNOU3HNW8-r0Wf?usp=sharing) \n\n\n![complextensor2_changed_test__aaaqkd](animated_visuals.svg)\n\n![License](https://img.shields.io/github/license/NeoVertex1/ComplexTensor)\n![PyPI](https://img.shields.io/pypi/v/complextensor)\n![Python Versions](https://img.shields.io/pypi/pyversions/complextensor)\n\n\n## Table of Contents\n\n- [📦 ComplexTensor](#-complextensor)\n  - [Table of Contents](#table-of-contents)\n  - [Introduction](#introduction)\n  - [Features](#features)\n  - [Installation](#installation)\n  - [Usage](#usage)\n    - [Basic Operations](#basic-operations)\n    - [Advanced Functions](#advanced-functions)\n    - [FFT Operations](#fft-operations)\n    - [Gradient Manipulation](#gradient-manipulation)\n  - [API Reference](#api-reference)\n  - [Limitations](#limitations)\n  - [Contributing](#contributing)\n  - [License](#license)\n  - [Acknowledgements](#acknowledgements)\n\n## Introduction\n\n**ComplexTensor** is a Python library built on top of [PyTorch](https://pytorch.org/) that provides comprehensive support for complex number operations within neural network models. It extends PyTorch's capabilities by handling complex tensors seamlessly, enabling advanced mathematical operations, custom gradient manipulations, and optimized performance on both CPU and GPU devices.\n\n\n\n---\n\n### **Why ComplexTensor?**\n\n- **Ease of Use:** Simplifies the handling of complex numbers with clear and concise APIs, making it accessible for both beginners and experienced developers.\n- **Seamless Integration:** Built on top of PyTorch, allowing you to leverage existing deep learning tools and functionalities without hassle.\n- **Comprehensive Documentation:** Offers detailed guides and examples to help you quickly understand and implement complex tensor operations.\n- **Enhanced Learning:** Facilitates a smooth onboarding experience, enabling learners to experiment with complex computations effortlessly.\n- **Robust Functionality:** Supports a wide range of complex arithmetic operations, custom autograd functions, and advanced mathematical transformations.\n\n### **Get Started Quickly**\n\nComplexTensor is crafted to help you focus on your projects without getting bogged down by the intricacies of complex number computations. With our extensive documentation and practical examples, you'll be up and running in no time, whether you're building neural networks that utilize complex data or exploring quantum-inspired algorithms.\n\n---\n\n\n\n## Features\n\n- **Arithmetic Operations**: Addition, subtraction, multiplication, and division of complex tensors.\n- **Complex Functions**: Implements common complex mathematical functions like exponential (`exp`), logarithm (`log`), sine (`sin`), cosine (`cos`), and tangent (`tan`).\n- **FFT Operations**: Native support for Fast Fourier Transform (FFT) and Inverse FFT (IFFT).\n- **Autograd Support**: Custom autograd functions supporting higher-order gradients and per-component gradient manipulation.\n- **Device Compatibility**: Optimized for both CPU and CUDA (GPU) devices with support for mixed precision.\n- **Utility Functions**: Magnitude (`abs`), phase (`angle`), polar conversion (`to_polar`), complex activation functions (`complex_relu`, `complex_sigmoid`).\n- **State Management**: Save and load the state of complex tensors for model persistence.\n\n## Installation\n\nYou can install **ComplexTensor** via `pip`. Ensure you have [PyTorch](https://pytorch.org/) installed before proceeding.\n\n```bash\npip install complextensor\n```\n\nAlternatively, you can clone the repository and install it manually:\n\n```bash\ngit clone https://github.com/NeoVertex1/ComplexTensor.git\ncd ComplexTensor\npip install -e .\n```\n# Usage\n#### Basic Operations\n\n```python\nimport torch\nfrom complextensor import ComplexTensor\n\n# Initialize real and imaginary parts\nreal = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)\nimag = torch.tensor([4.0, 5.0, 6.0], requires_grad=True)\n\n# Create ComplexTensor instances\nct1 = ComplexTensor(real, imag)\nct2 = ComplexTensor(real * 2, imag * 2)\n\n# Addition\nct_sum = ct1 + ct2\nprint(ct_sum)\n\n# Subtraction\nct_diff = ct1 - ct2\nprint(ct_diff)\n\n# Multiplication\nct_mul = ct1 * ct2\nprint(ct_mul)\n\n# Division\nct_div = ct1 / ct2\nprint(ct_div)\n```\n\n### Advanced Functions\n\n\n```python\n# Compute exponential\nct_exp = ct1.exp()\nprint(ct_exp)\n\n# Compute logarithm\nct_log = ct1.log()\nprint(ct_log)\n\n# Compute sine\nct_sin = ct1.sin()\nprint(ct_sin)\n\n# Compute cosine\nct_cos = ct1.cos()\nprint(ct_cos)\n\n# Compute tangent\nct_tan = ct1.tan()\nprint(ct_tan)\n\n```\n\n### FFT Operations\n\n```python\n# Fast Fourier Transform\nct_fft = ct1.fft()\nprint(ct_fft)\n\n# Inverse Fast Fourier Transform\nct_ifft = ct_fft.ifft()\nprint(ct_ifft)\n```\n\n### Gradient Manipulation\n\n```python\n# Apply gradient scaling\nct_scaled = ct1.apply_gradient_manipulation(grad_scale_real=0.5, grad_scale_imag=2.0)\n\n# Example loss computation\nloss = ct_scaled.abs().sum()\nloss.backward()\n\nprint(real.grad)\nprint(imag.grad)\n```\n\n\n\n## API Reference\n\n### `ComplexTensor` Class\n\n- **Initialization**\n  ```python\n  ComplexTensor(real: Tensor, imag: Optional[Tensor] = None)\n  ```\n  Initializes a complex tensor with real and imaginary parts.\n\n- **Arithmetic Operations**\n  - `__add__(self, other: 'ComplexTensor') -\u003e 'ComplexTensor'`\n  - `__sub__(self, other: 'ComplexTensor') -\u003e 'ComplexTensor'`\n  - `__mul__(self, other: 'ComplexTensor') -\u003e 'ComplexTensor'`\n  - `__truediv__(self, other: 'ComplexTensor') -\u003e 'ComplexTensor'`\n\n- **Complex Functions**\n  - `exp(self) -\u003e 'ComplexTensor'`\n  - `log(self) -\u003e 'ComplexTensor'`\n  - `sin(self) -\u003e 'ComplexTensor'`\n  - `cos(self) -\u003e 'ComplexTensor'`\n  - `tan(self) -\u003e 'ComplexTensor'`\n  - `power(self, exponent: Union[float, 'ComplexTensor']) -\u003e 'ComplexTensor'`\n  - `__pow__(self, exponent: Union[float, 'ComplexTensor']) -\u003e 'ComplexTensor'`\n\n- **FFT Operations**\n  - `fft(self, n: Optional[int] = None, dim: int = -1, norm: Optional[str] = None) -\u003e 'ComplexTensor'`\n  - `ifft(self, n: Optional[int] = None, dim: int = -1, norm: Optional[str] = None) -\u003e 'ComplexTensor'`\n\n- **Utility Functions**\n  - `conj(self) -\u003e 'ComplexTensor'`\n  - `abs(self) -\u003e Tensor`\n  - `angle(self) -\u003e Tensor`\n  - `to_polar(self) -\u003e Tuple[Tensor, Tensor]`\n  - `complex_relu(self) -\u003e 'ComplexTensor'`\n  - `complex_sigmoid(self) -\u003e 'ComplexTensor'`\n  - `detach(self) -\u003e 'ComplexTensor'`\n  - `requires_grad_(self, requires_grad: bool = True) -\u003e 'ComplexTensor'`\n  - `to(self, device: torch.device, dtype: Optional[torch.dtype] = None) -\u003e 'ComplexTensor'`\n\n- **State Management**\n  - `state_dict(self) -\u003e Dict[str, Tensor]`\n  - `load_state_dict(self, state_dict: Dict[str, Tensor]) -\u003e None`\n\n- **Gradient Manipulation**\n  - `apply_gradient_manipulation(self, grad_scale_real: float = 1.0, grad_scale_imag: float = 1.0) -\u003e 'ComplexTensor'`\n\n- **Miscellaneous**\n  - `__repr__(self) -\u003e str`\n  - `__len__(self) -\u003e int`\n  - `__getitem__(self, index) -\u003e 'ComplexTensor'`\n  - `__setitem__(self, index, value: 'ComplexTensor') -\u003e None`\n  - `shape` (property)\n  - `dtype` (property)\n  - `device` (property)\n\n### `ComplexFunction` Class\n\n- **Forward and Backward Methods**\n  Custom autograd functions to handle complex tensor operations, supporting higher-order gradients and per-component gradient manipulation.\n\n## Limitations\n\nWhile **ComplexTensor** offers a robust set of features for handling complex numbers in PyTorch, there are certain limitations to be aware of:\n\n- **Performance Optimization**: Although device-aware operations are supported, further optimizations can be implemented for specific hardware accelerations.\n- **Limited Advanced Functions**: Currently, only a subset of complex functions is implemented. Future versions can include more specialized functions as needed.\n- **Interoperability**: Integration with other complex number libraries or frameworks may require additional adapters or compatibility layers.\n- **Documentation**: While comprehensive, the API reference can be expanded with more detailed examples and edge case explanations.\n\n## Contributing\n\nContributions are welcome! Whether it's reporting bugs, suggesting features, or submitting pull requests, your input helps improve the project.\n\n1. **Fork the Repository**\n\n2. **Create a Feature Branch**\n   ```bash\n   git checkout -b feature/YourFeature\n   ```\n\n3. **Commit Your Changes**\n   ```bash\n   git commit -m \"Add YourFeature\"\n   ```\n\n4. **Push to the Branch**\n   ```bash\n   git push origin feature/YourFeature\n   ```\n\n5. **Open a Pull Request**\n\n## Acknowledgements\n\n- [PyTorch](https://pytorch.org/) for providing the foundational deep learning framework.\n- Contributors and the open-source community for their invaluable feedback and support.\n\n\n\n\n# running tests:\n\nfor the unit test for the main complex_tensor use this command on the root folder:\n\n```bash\npython -m unittest tests.test_complex_tensor\n```\n\n\n## Reporting Issues\n\nIf you encounter any bugs or have suggestions for improvements, please open an issue [here](https://github.com/NeoVertex1/ComplexTensor/issues).\n\n\n\n\n## 🚀 **Getting Started**\n\n\n```python\nimport torch\nimport numpy as np\nfrom complextensor import ComplexTensor\n\ndef quantum_inspired_superposition(states, amplitudes):\n    \"\"\"\n    Create a superposition of quantum-inspired states using ComplexTensor.\n    \n    Args:\n    states (list of ComplexTensor): The basis states to superpose.\n    amplitudes (list of ComplexTensor): The amplitudes for each state.\n    \n    Returns:\n    ComplexTensor: The superposed state.\n    \"\"\"\n    superposed_state = ComplexTensor(torch.zeros_like(states[0].real), torch.zeros_like(states[0].imag))\n    for state, amplitude in zip(states, amplitudes):\n        superposed_state += ComplexTensor(amplitude.real * state.real - amplitude.imag * state.imag,\n                                          amplitude.real * state.imag + amplitude.imag * state.real)\n    return superposed_state\n\ndef quantum_inspired_entanglement(state1, state2):\n    \"\"\"\n    Create an entangled state from two quantum-inspired states using ComplexTensor.\n    \n    Args:\n    state1, state2 (ComplexTensor): The states to entangle.\n    \n    Returns:\n    ComplexTensor: The entangled state.\n    \"\"\"\n    real_kron = torch.kron(state1.real, state2.real) - torch.kron(state1.imag, state2.imag)\n    imag_kron = torch.kron(state1.real, state2.imag) + torch.kron(state1.imag, state2.real)\n    return ComplexTensor(real_kron, imag_kron)\n\ndef measure_state(state):\n    \"\"\"\n    Perform a measurement on the quantum-inspired state using ComplexTensor.\n    \n    Args:\n    state (ComplexTensor): The state to measure.\n    \n    Returns:\n    int: The index of the measured basis state.\n    \"\"\"\n    probabilities = state.abs() ** 2\n    probabilities = probabilities / torch.sum(probabilities)\n    probabilities_np = probabilities.cpu().detach().numpy()  # Convert to numpy for choice\n    return np.random.choice(len(state.real), p=probabilities_np)\n\n# Example usage with ComplexTensor\nif __name__ == \"__main__\":\n    # Define two basis states using ComplexTensor\n    state0_real = torch.tensor([1.0, 0.0], dtype=torch.float32)\n    state1_real = torch.tensor([0.0, 1.0], dtype=torch.float32)\n    state0 = ComplexTensor(state0_real)\n    state1 = ComplexTensor(state1_real)\n\n    # Create a superposition\n    amplitude_real = torch.tensor([1/torch.sqrt(torch.tensor(2.0)), 0.0], dtype=torch.float32)\n    amplitude_imag = torch.tensor([0.0, 1/torch.sqrt(torch.tensor(2.0))], dtype=torch.float32)\n    superposed_state = quantum_inspired_superposition(\n        [state0, state1],\n        [ComplexTensor(amplitude_real[0:1], amplitude_imag[0:1]), ComplexTensor(amplitude_real[1:2], amplitude_imag[1:2])]\n    )\n    print(\"Superposed state:\", superposed_state)\n\n    # Create an entangled state\n    entangled_state = quantum_inspired_entanglement(state0, state1)\n    print(\"Entangled state:\", entangled_state)\n\n    # Perform measurements\n    for _ in range(5):\n        result = measure_state(superposed_state)\n        print(\"Measurement result:\", result)\n\n```\n\n\nThis code simulates quantum-inspired operations like **superposition**, **entanglement**, and **measurement**. Here's a breakdown of the quantum-inspired approach:\n\n### Key Functions:\n1. **Superposition**: \n   - This creates a linear combination of quantum basis states, where each state is weighted by a complex amplitude. Superposition is a key feature in quantum mechanics that allows a quantum system to exist in multiple states simultaneously.\n   \n2. **Entanglement**:\n   - This creates an entangled state using the **Kronecker product** (or tensor product) of two states. Entanglement is a quantum phenomenon where two qubits become linked, such that the state of one qubit instantaneously influences the state of the other, regardless of distance.\n\n3. **Measurement**:\n   - A simulated quantum measurement collapses the superposed state into one of the basis states with a probability proportional to the square of the state's amplitude (following the **Born rule**).\n\n### Example Output:\n\n- **Superposed State**: This creates a superposition of two basis states (|0⟩ and |1⟩), with a real coefficient for |0⟩ and an imaginary coefficient for |1⟩.\n  \n- **Entangled State**: When state0 and state1 are entangled, this forms a combined quantum system. This entanglement would be represented as:\n  \\[\n  |0⟩ ⊗ |1⟩ = \\begin{bmatrix} 0 \\\\ 1 \\\\ 0 \\\\ 0 \\end{bmatrix}\n  \\]\n  \n- **Measurements**: When you measure the superposed state multiple times, the results should follow a probabilistic distribution based on the square of the absolute values of the coefficients.\n\n### Sample Run (using the code):\n```python\nSuperposed state: [0.70710678+0.j         0.        +0.70710678j]\nEntangled state: [0.+0.j 0.+0.j 1.+0.j 0.+0.j]\nMeasurement result: 0\nMeasurement result: 1\nMeasurement result: 0\nMeasurement result: 0\nMeasurement result: 1\n```\n\nHere, you can see that the superposed state has a 50-50 chance of being in state `|0⟩` or state `|1⟩`, with a phase difference introduced by the complex coefficients.\n\n\n2. **Advanced Quantum-Inspired Operations**:\n   - You can expand this further to include other operations like **quantum gates** (Hadamard, Pauli-X), **quantum Fourier transforms**, or **Grover’s algorithm** in the quantum-inspired framework using the complex tensor system.\n\n\nmore examples:\n\n\n```python\nimport torch\nfrom complextensor import ComplexTensor\n\ndef main():\n    # Initialize real and imaginary parts\n    real = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)\n    imag = torch.tensor([4.0, 5.0, 6.0], requires_grad=True)\n    \n    # Create ComplexTensor instances\n    ct1 = ComplexTensor(real, imag)\n    ct2 = ComplexTensor(real * 2, imag * 2)\n    \n    # Perform arithmetic operations\n    ct_sum = ct1 + ct2\n    print(\"Sum:\", ct_sum)\n    \n    ct_diff = ct1 - ct2\n    print(\"Difference:\", ct_diff)\n    \n    ct_mul = ct1 * ct2\n    print(\"Product:\", ct_mul)\n    \n    ct_div = ct1 / ct2\n    print(\"Division:\", ct_div)\n    \n    # Compute complex exponential\n    ct_exp = ct1.exp()\n    print(\"Exponential:\", ct_exp)\n    \n    # Perform FFT\n    ct_fft = ct1.fft()\n    print(\"FFT:\", ct_fft)\n    \n    # Backpropagation example\n    loss = ct_sum.abs().sum()\n    loss.backward()\n    print(\"Gradients - Real:\", real.grad)\n    print(\"Gradients - Imaginary:\", imag.grad)\n\nif __name__ == \"__main__\":\n    main()\n```\n\nRun the example:\n\n```bash\npython examples/example_usage.py\n```\n\n---\n\n## 🧪 **Testing**\n\n Here's a basic example of a test case (`test_complex_tensor.py`):\n\n```python\nimport unittest\nimport torch\nfrom src.complextensor.complex_tensor import ComplexTensor, ComplexFunction\n\nclass TestComplexFunction(unittest.TestCase):\n    def setUp(self):\n        self.real = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)\n        self.imag = torch.tensor([4.0, 5.0, 6.0], requires_grad=True)\n\n    def test_complex_function_forward(self):\n        result = ComplexFunction.apply(self.real, self.imag)\n        self.assertTrue(torch.is_complex(result))\n        self.assertTrue(torch.allclose(result.real, self.real))\n        self.assertTrue(torch.allclose(result.imag, self.imag))\n\n    def test_complex_function_backward(self):\n        result = ComplexFunction.apply(self.real, self.imag)\n        loss = result.abs().sum()\n        loss.backward()\n\n        self.assertIsNotNone(self.real.grad)\n        self.assertIsNotNone(self.imag.grad)\n        self.assertFalse(torch.allclose(self.real.grad, torch.zeros_like(self.real)))\n        self.assertFalse(torch.allclose(self.imag.grad, torch.zeros_like(self.imag)))\n\nclass TestComplexTensor(unittest.TestCase):\n    def setUp(self):\n        self.real = torch.tensor([1.0, 2.0, 3.0])\n        self.imag = torch.tensor([4.0, 5.0, 6.0])\n        self.ct = ComplexTensor(self.real, self.imag)\n\n    def test_initialization(self):\n        self.assertTrue(torch.allclose(self.ct.real, self.real))\n        self.assertTrue(torch.allclose(self.ct.imag, self.imag))\n\n    def test_forward(self):\n        result = self.ct.forward()\n        self.assertTrue(torch.is_complex(result))\n        self.assertTrue(torch.allclose(result.real, self.real))\n        self.assertTrue(torch.allclose(result.imag, self.imag))\n\n    def test_addition(self):\n        other = ComplexTensor(torch.tensor([1.0, 1.0, 1.0]), torch.tensor([2.0, 2.0, 2.0]))\n        result = self.ct + other\n        self.assertTrue(torch.allclose(result.real, self.real + 1))\n        self.assertTrue(torch.allclose(result.imag, self.imag + 2))\n\n    def test_subtraction(self):\n        other = ComplexTensor(torch.tensor([1.0, 1.0, 1.0]), torch.tensor([2.0, 2.0, 2.0]))\n        result = self.ct - other\n        self.assertTrue(torch.allclose(result.real, self.real - 1))\n        self.assertTrue(torch.allclose(result.imag, self.imag - 2))\n\n    def test_multiplication(self):\n        other = ComplexTensor(torch.tensor([2.0, 2.0, 2.0]), torch.tensor([3.0, 3.0, 3.0]))\n        result = self.ct * other\n        expected_real = self.real * 2 - self.imag * 3\n        expected_imag = self.real * 3 + self.imag * 2\n        self.assertTrue(torch.allclose(result.real, expected_real))\n        self.assertTrue(torch.allclose(result.imag, expected_imag))\n\n    def test_division(self):\n        other = ComplexTensor(torch.tensor([2.0, 2.0, 2.0]), torch.tensor([3.0, 3.0, 3.0]))\n        result = self.ct / other\n        denominator = 4 + 9  # 2^2 + 3^2\n        expected_real = (self.real * 2 + self.imag * 3) / denominator\n        expected_imag = (self.imag * 2 - self.real * 3) / denominator\n        self.assertTrue(torch.allclose(result.real, expected_real))\n        self.assertTrue(torch.allclose(result.imag, expected_imag))\n\n    def test_conjugate(self):\n        result = self.ct.conj()\n        self.assertTrue(torch.allclose(result.real, self.real))\n        self.assertTrue(torch.allclose(result.imag, -self.imag))\n\n    def test_abs(self):\n        result = self.ct.abs()\n        expected = torch.sqrt(self.real**2 + self.imag**2)\n        self.assertTrue(torch.allclose(result, expected))\n\n    def test_angle(self):\n        result = self.ct.angle()\n        expected = torch.atan2(self.imag, self.real)\n        self.assertTrue(torch.allclose(result, expected))\n\n    def test_to_polar(self):\n        magnitude, phase = self.ct.to_polar()\n        expected_magnitude = torch.sqrt(self.real**2 + self.imag**2)\n        expected_phase = torch.atan2(self.imag, self.real)\n        self.assertTrue(torch.allclose(magnitude, expected_magnitude))\n        self.assertTrue(torch.allclose(phase, expected_phase))\n\n    def test_complex_relu(self):\n        result = self.ct.complex_relu()\n        self.assertTrue(torch.allclose(result.real, torch.relu(self.real)))\n        self.assertTrue(torch.allclose(result.imag, torch.relu(self.imag)))\n\n    def test_complex_sigmoid(self):\n        result = self.ct.complex_sigmoid()\n        self.assertTrue(torch.allclose(result.real, torch.sigmoid(self.real)))\n        self.assertTrue(torch.allclose(result.imag, torch.sigmoid(self.imag)))\n\n    def test_exp(self):\n        result = self.ct.exp()\n        expected_real = torch.exp(self.real) * torch.cos(self.imag)\n        expected_imag = torch.exp(self.real) * torch.sin(self.imag)\n        self.assertTrue(torch.allclose(result.real, expected_real))\n        self.assertTrue(torch.allclose(result.imag, expected_imag))\n\n    def test_log(self):\n        result = self.ct.log()\n        expected_real = torch.log(self.ct.abs())\n        expected_imag = self.ct.angle()\n        self.assertTrue(torch.allclose(result.real, expected_real))\n        self.assertTrue(torch.allclose(result.imag, expected_imag))\n\n    def test_sin(self):\n        result = self.ct.sin()\n        expected_real = torch.sin(self.real) * torch.cosh(self.imag)\n        expected_imag = torch.cos(self.real) * torch.sinh(self.imag)\n        self.assertTrue(torch.allclose(result.real, expected_real))\n        self.assertTrue(torch.allclose(result.imag, expected_imag))\n\n    def test_cos(self):\n        result = self.ct.cos()\n        expected_real = torch.cos(self.real) * torch.cosh(self.imag)\n        expected_imag = -torch.sin(self.real) * torch.sinh(self.imag)\n        self.assertTrue(torch.allclose(result.real, expected_real))\n        self.assertTrue(torch.allclose(result.imag, expected_imag))\n\n    def test_tan(self):\n        result = self.ct.tan()\n        sin_ct = self.ct.sin()\n        cos_ct = self.ct.cos()\n        expected_real = (sin_ct.real * cos_ct.real + sin_ct.imag * cos_ct.imag) / (cos_ct.real**2 + cos_ct.imag**2)\n        expected_imag = (sin_ct.imag * cos_ct.real - sin_ct.real * cos_ct.imag) / (cos_ct.real**2 + cos_ct.imag**2)\n        self.assertTrue(torch.allclose(result.real, expected_real, atol=1e-5))\n        self.assertTrue(torch.allclose(result.imag, expected_imag, atol=1e-5))\n\n    def test_power(self):\n        exponent = 2\n        result = self.ct.power(exponent)\n        expected = self.ct * self.ct\n        self.assertTrue(torch.allclose(result.real, expected.real))\n        self.assertTrue(torch.allclose(result.imag, expected.imag))\n\n    def test_fft(self):\n        result = self.ct.fft()\n        expected = torch.fft.fft(self.ct.forward())\n        self.assertTrue(torch.allclose(result.real, expected.real))\n        self.assertTrue(torch.allclose(result.imag, expected.imag))\n\n    def test_ifft(self):\n        result = self.ct.ifft()\n        expected = torch.fft.ifft(self.ct.forward())\n        self.assertTrue(torch.allclose(result.real, expected.real))\n        self.assertTrue(torch.allclose(result.imag, expected.imag))\n\n    def test_gradient_computation(self):\n        real = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)\n        imag = torch.tensor([4.0, 5.0, 6.0], requires_grad=True)\n        ct = ComplexTensor(real, imag)\n        \n        output = ct.forward().abs().sum()\n        output.backward()\n        \n        self.assertIsNotNone(real.grad)\n        self.assertIsNotNone(imag.grad)\n        self.assertFalse(torch.allclose(real.grad, torch.zeros_like(real.grad)))\n        self.assertFalse(torch.allclose(imag.grad, torch.zeros_like(imag.grad)))\n\n    def test_to_device(self):\n        if torch.cuda.is_available():\n            ct_gpu = self.ct.to(torch.device('cuda'))\n            self.assertEqual(ct_gpu.real.device.type, 'cuda')\n            self.assertEqual(ct_gpu.imag.device.type, 'cuda')\n\n    def test_detach(self):\n        ct_detached = self.ct.detach()\n        self.assertFalse(ct_detached.real.requires_grad)\n        self.assertFalse(ct_detached.imag.requires_grad)\n\n    def test_requires_grad(self):\n        self.ct.requires_grad_(True)\n        self.assertTrue(self.ct.real.requires_grad)\n        self.assertTrue(self.ct.imag.requires_grad)\n\n    def test_complex_function_integration(self):\n        real = torch.tensor([1.0, 2.0, 3.0], requires_grad=True)\n        imag = torch.tensor([4.0, 5.0, 6.0], requires_grad=True)\n        ct = ComplexTensor(real, imag)\n        \n        result = ct.forward()\n        self.assertTrue(torch.is_complex(result))\n        self.assertTrue(torch.allclose(result.real, real))\n        self.assertTrue(torch.allclose(result.imag, imag))\n\n        loss = result.abs().sum()\n        loss.backward()\n\n        self.assertIsNotNone(real.grad)\n        self.assertIsNotNone(imag.grad)\n        self.assertFalse(torch.allclose(real.grad, torch.zeros_like(real)))\n        self.assertFalse(torch.allclose(imag.grad, torch.zeros_like(imag)))\n\nif __name__ == '__main__':\n    unittest.main()\n```\n\nRun the tests:\n\n```bash\npython -m unittest discover tests\n```\n\n---\n","funding_links":[],"categories":["其他_机器学习与深度学习"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FNeoVertex1%2FComplexTensor","html_url":"https://awesome.ecosyste.ms/projects/github.com%2FNeoVertex1%2FComplexTensor","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2FNeoVertex1%2FComplexTensor/lists"}