Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions .serena/memories/code_style_conventions.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# SymPy Code Style and Conventions

## General Style
- **Indentation**: 4 spaces (no tabs)
- **Line endings**: LF (Unix style)
- **Encoding**: UTF-8
- **Trailing whitespace**: Trimmed
- **Final newline**: Required

## Python Code Conventions
- Follows PEP 8 Python style guidelines
- **Import organization**:
- from __future__ imports at the top
- Third-party imports
- Local sympy imports
- Use absolute imports where possible

## Documentation
- **RST files**: 3-space indentation
- Extensive docstrings for all public functions/classes
- Examples in docstrings are tested via doctest

## File Structure
- Main library code in `sympy/` directory
- Tests alongside code in `tests/` subdirectories
- Examples in `examples/` directory
- Documentation source in `doc/`

## Type Hints
- Project predates widespread type hint adoption
- Type hints not consistently used throughout codebase

## Naming Conventions
- Snake_case for functions and variables
- CamelCase for classes
- ALL_CAPS for constants
- Private methods/attributes prefixed with underscore
44 changes: 44 additions & 0 deletions .serena/memories/codebase_structure.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
# SymPy Codebase Structure

## Main Directory Layout
```
sympy/
├── sympy/ # Main library code
│ ├── core/ # Core symbolic computation classes (Basic, Expr, Add, Mul, etc.)
│ ├── functions/ # Mathematical functions (trig, special, elementary)
│ ├── algebras/ # Algebraic structures (quaternions, etc.)
│ ├── calculus/ # Calculus operations
│ ├── geometry/ # Geometric objects and operations
│ ├── matrices/ # Matrix operations and expressions
│ ├── polys/ # Polynomial manipulation
│ ├── solvers/ # Equation solvers
│ ├── simplify/ # Expression simplification
│ ├── series/ # Series expansion
│ ├── integrals/ # Integration
│ ├── plotting/ # Plotting capabilities
│ ├── physics/ # Physics modules (quantum, mechanics, etc.)
│ ├── logic/ # Boolean algebra
│ ├── sets/ # Set theory
│ ├── stats/ # Statistics and probability
│ ├── ntheory/ # Number theory
│ ├── combinatorics/ # Combinatorial functions
│ ├── tensor/ # Tensor operations
│ ├── utilities/ # Utility functions
│ └── printing/ # Pretty printing, code generation
├── bin/ # Executable scripts
├── examples/ # Example usage
├── doc/ # Documentation source
└── release/ # Release management
```

## Key Core Modules
- `core/basic.py` - Basic class (root of all SymPy objects)
- `core/expr.py` - Expression class
- `core/symbol.py` - Symbol definitions
- `core/numbers.py` - Number classes
- `core/add.py`, `core/mul.py`, `core/power.py` - Basic operations

## Test Organization
- Tests located in `tests/` subdirectories within each module
- Test files named `test_*.py`
- Doctests embedded in source code
20 changes: 20 additions & 0 deletions .serena/memories/project_overview.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# SymPy Project Overview

## Purpose
SymPy is a Python library for symbolic mathematics. It aims to become a full-featured computer algebra system (CAS) while keeping the code as simple as possible to be comprehensible and easily extensible. SymPy is written entirely in Python and depends on mpmath as an external library.

## Technology Stack
- **Language**: Python (supports Python 2.7 and 3.4+)
- **Main Dependencies**:
- mpmath (version >= 0.19) - required for mathematical computations
- Optional dependencies for specific features (plotting, etc.)
- **Build System**: setuptools/distutils based setup.py
- **Testing**: Custom test framework (bin/test) with pytest-like interface

## Key Features
- Pure Python implementation
- Symbolic computation capabilities
- Mathematical functions, algebra, calculus, geometry
- Code generation capabilities
- Extensive test suite
- Cross-platform compatibility
34 changes: 34 additions & 0 deletions .serena/memories/suggested_commands.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
# SymPy Development Commands

## Testing Commands
- `python bin/test` - Run the main test suite with pytest-like interface
- `python bin/test [module/path]` - Test specific module or path
- `python bin/test --verbose` - Verbose test output
- `python bin/test --pdb` - Run post-mortem debugger on failures
- `python bin/doctest` - Run doctests
- `python setup.py test` - Alternative way to run tests (though bin/test is preferred)

## Setup and Installation
- `python setup.py install` - Install SymPy
- `python setup.py develop` - Install in development mode
- `python setup.py clean` - Clean build artifacts

## Code Quality Commands
- `python setup.py audit` - Run pyflakes checker on source code
- Code formatting: Project doesn't appear to use automated formatters like black/autopep8

## Interactive Usage
- `python bin/isympy` - Start SymPy interactive console (local development)
- `isympy` - Start SymPy console (if installed)
- `python isympy.py` - Alternative way to start interactive console

## Benchmarking
- `python setup.py bench` - Run benchmark suite

## Git Commands (Development)
- `git clean -Xdf` - Clean all ignored files
- `git clean -df` - Clean all untracked files
- `git reset --hard` - Revert recent changes (WARNING: destructive)

## Documentation
- `cd doc && make html` - Build HTML documentation locally
38 changes: 38 additions & 0 deletions .serena/memories/task_completion_checklist.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
# Task Completion Guidelines for SymPy

## When a Development Task is Completed

### 1. Testing
**Always run tests after making changes:**
- `python bin/test [affected_module]` - Test the specific module you modified
- `python bin/test` - Run full test suite for comprehensive changes
- `python bin/doctest [module]` - Test documentation examples if you modified docstrings

### 2. Code Quality Checks
- `python setup.py audit` - Run pyflakes to check for code issues
- Manually review code for style compliance with project conventions

### 3. Documentation Updates
- Update docstrings if you added/modified public APIs
- Add examples to docstrings when appropriate
- Update relevant documentation files if needed

### 4. Validation Steps
- Verify your changes work in the interactive console: `python bin/isympy`
- Test with different Python versions if making significant changes
- Check that imports still work correctly

### 5. Performance Considerations
- For performance-critical changes, consider running benchmarks: `python setup.py bench`
- Profile code if making changes to core modules

### 6. Integration Testing
- Test how your changes interact with other SymPy modules
- Verify backward compatibility is maintained
- Check that mathematical properties still hold

## Before Submitting Changes
- Ensure all tests pass
- Code follows project style guidelines
- Documentation is updated appropriately
- Changes are well-tested with edge cases
41 changes: 41 additions & 0 deletions .serena/memories/windows_system_commands.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
# Windows-Specific System Commands for SymPy Development

## File and Directory Operations
- `dir` - List directory contents (equivalent to `ls`)
- `type filename` - Display file contents (equivalent to `cat`)
- `copy source dest` - Copy files (equivalent to `cp`)
- `del filename` - Delete files (equivalent to `rm`)
- `rmdir /s dirname` - Remove directory recursively (equivalent to `rm -rf`)
- `mkdir dirname` - Create directory
- `cd dirname` - Change directory
- `cd ..` - Go up one directory
- `cd \` - Go to root directory

## Text Processing
- `findstr pattern filename` - Search for patterns in files (equivalent to `grep`)
- `findstr /s /i pattern *` - Recursive case-insensitive search
- `fc file1 file2` - Compare files (equivalent to `diff`)

## System Information
- `echo %PATH%` - Display PATH environment variable
- `where python` - Find Python executable location (equivalent to `which`)
- `python --version` - Check Python version

## Process Management
- `tasklist` - List running processes (equivalent to `ps`)
- `taskkill /f /pid <pid>` - Kill process by PID

## Network
- `ping hostname` - Test network connectivity
- `ipconfig` - Display network configuration

## Git Commands (same on Windows)
- All git commands work the same way on Windows
- Use Git Bash for Unix-like command experience if preferred

## PowerShell Alternatives
If using PowerShell instead of Command Prompt:
- `Get-ChildItem` or `ls` - List directory contents
- `Get-Content filename` or `cat filename` - Display file contents
- `Copy-Item` or `cp` - Copy files
- `Remove-Item` or `rm` - Delete files
66 changes: 66 additions & 0 deletions .serena/project.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
# language of the project (csharp, python, rust, java, typescript, javascript, go, cpp, or ruby)
# Special requirements:
# * csharp: Requires the presence of a .sln file in the project folder.
language: python

# whether to use the project's gitignore file to ignore files
# Added on 2025-04-07
ignore_all_files_in_gitignore: true
# list of additional paths to ignore
# same syntax as gitignore, so you can use * and **
# Was previously called `ignored_dirs`, please update your config if you are using that.
# Added (renamed)on 2025-04-07
ignored_paths: []

# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false


# list of tool names to exclude. We recommend not excluding any tools, see the readme for more details.
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project by name.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_lines`: Deletes a range of lines within a file.
# * `delete_memory`: Deletes a memory from Serena's project-specific memory store.
# * `execute_shell_command`: Executes a shell command.
# * `find_referencing_code_snippets`: Finds code snippets in which the symbol at the given location is referenced.
# * `find_referencing_symbols`: Finds symbols that reference the symbol at the given location (optionally filtered by type).
# * `find_symbol`: Performs a global (or local) search for symbols with/containing a given name/substring (optionally filtered by type).
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file or directory.
# * `initial_instructions`: Gets the initial instructions for the current project.
# Should only be used in settings where the system prompt cannot be set,
# e.g. in clients you have no control over, like Claude Desktop.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_at_line`: Inserts content at a given line in a file.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: Lists memories in Serena's project-specific memory store.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `prepare_for_new_conversation`: Provides instructions for preparing for a new conversation (in order to continue with the necessary context).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Reads the memory with the given name from Serena's project-specific memory store.
# * `remove_project`: Removes a project from the Serena configuration.
# * `replace_lines`: Replaces a range of lines within a file with new content.
# * `replace_symbol_body`: Replaces the full definition of a symbol.
# * `restart_language_server`: Restarts the language server, may be necessary when edits not through Serena happen.
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `summarize_changes`: Provides instructions for summarizing the changes made to the codebase.
# * `switch_modes`: Activates modes by providing a list of their names
# * `think_about_collected_information`: Thinking tool for pondering the completeness of collected information.
# * `think_about_task_adherence`: Thinking tool for determining whether the agent is still on track with the current task.
# * `think_about_whether_you_are_done`: Thinking tool for determining whether the task is truly completed.
# * `write_memory`: Writes a named memory (for future reference) to Serena's project-specific memory store.
excluded_tools: []

# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""

project_name: "sympy"
46 changes: 45 additions & 1 deletion sympy/physics/quantum/tensorproduct.py
Original file line number Diff line number Diff line change
Expand Up @@ -344,6 +344,50 @@ def tensor_product_simp_Mul(e):
else:
return e

def tensor_product_simp_Pow(e):
"""Simplify a Pow with TensorProduct.

This function simplifies expressions of the form ``TensorProduct(...)^n``
by distributing the power to each argument in the tensor product.

Parameters
==========

e : Expr
A power expression where the base is a ``TensorProduct``.

Returns
=======

e : Expr
A ``TensorProduct`` where each argument is raised to the given power.

Examples
========

>>> from sympy.physics.quantum.tensorproduct import \
tensor_product_simp_Pow, TensorProduct
>>> from sympy import Symbol
>>> A = Symbol('A',commutative=False)
>>> B = Symbol('B',commutative=False)
>>> e = TensorProduct(A, B)**2
>>> tensor_product_simp_Pow(e)
(A**2)x(B**2)

"""
if not isinstance(e, Pow):
return e

base, exp = e.as_base_exp()

# Check if the base is a TensorProduct
if isinstance(base, TensorProduct):
# Distribute the power to each argument
new_args = [arg**exp for arg in base.args]
return TensorProduct(*new_args)
else:
# If not a TensorProduct, just return the simplified base raised to exp
return tensor_product_simp(base)**exp

def tensor_product_simp(e, **hints):
"""Try to simplify and combine TensorProducts.
Expand Down Expand Up @@ -382,7 +426,7 @@ def tensor_product_simp(e, **hints):
if isinstance(e, Add):
return Add(*[tensor_product_simp(arg) for arg in e.args])
elif isinstance(e, Pow):
return tensor_product_simp(e.base) ** e.exp
return tensor_product_simp_Pow(e)
elif isinstance(e, Mul):
return tensor_product_simp_Mul(e)
elif isinstance(e, Commutator):
Expand Down
40 changes: 39 additions & 1 deletion sympy/physics/quantum/tests/test_tensorproduct.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,45 @@ def test_tensor_product_commutator():
def test_tensor_product_simp():
assert tensor_product_simp(TP(A, B)*TP(B, C)) == TP(A*B, B*C)


def test_tensor_product_simp_pow():
"""Test tensor_product_simp for powers of TensorProducts."""
# Test with commutative scalars
assert tensor_product_simp(TP(1, 1)**2) == TP(1, 1)
assert tensor_product_simp(TP(2, 3)**2) == TP(4, 9)
assert tensor_product_simp(TP(x, x)**2) == TP(x**2, x**2)

# Test with non-commutative symbols
assert tensor_product_simp(TP(A, B)**2) == TP(A**2, B**2)
assert tensor_product_simp(TP(A, B, C)**2) == TP(A**2, B**2, C**2)
assert tensor_product_simp(TP(A, B)**3) == TP(A**3, B**3)

# Test with mixed commutative and non-commutative
assert tensor_product_simp(TP(2, A)**2) == TP(4, A**2)
assert tensor_product_simp(TP(x, B)**2) == TP(x**2, B**2)

# Test nested case: simplify inside a Mul
assert tensor_product_simp(3*TP(A, B)**2) == 3*TP(A**2, B**2)

# Test that non-TensorProduct powers are handled correctly
assert tensor_product_simp(A**2) == A**2
assert tensor_product_simp((A*B)**2) == (A*B)**2

def test_tensor_product_simp_pow_issue():
"""Test the specific examples from the issue."""
from sympy.physics.paulialgebra import Pauli

# Test case 1: (1x1)**2
t1 = TP(1, 1)**2
assert tensor_product_simp(t1) == TP(1, 1)

# Test case 2: (1xsigma_3)**2
# Note: Pauli(3)**2 = 1 (identity)
t2 = TP(1, Pauli(3))**2
assert tensor_product_simp(t2) == TP(1, 1)

# Additional test with symbolic power
n = symbols('n')
assert tensor_product_simp(TP(A, B)**n) == TP(A**n, B**n)
def test_issue_5923():
# most of the issue regarding sympification of args has been handled
# and is tested internally by the use of args_cnc through the quantum
Expand Down