From 8d2eed1aca7ad1a3750982097b7c35b329f57436 Mon Sep 17 00:00:00 2001 From: Michael Panchenko Date: Tue, 3 Jun 2025 00:57:10 +0200 Subject: [PATCH 1/2] serena onboarding step --- .serena/memories/code_style_conventions.md | 37 +++++++++++ .serena/memories/codebase_structure.md | 44 +++++++++++++ .serena/memories/project_overview.md | 20 ++++++ .serena/memories/suggested_commands.md | 34 ++++++++++ .serena/memories/task_completion_checklist.md | 38 +++++++++++ .serena/memories/windows_system_commands.md | 41 ++++++++++++ .serena/project.yml | 66 +++++++++++++++++++ 7 files changed, 280 insertions(+) create mode 100644 .serena/memories/code_style_conventions.md create mode 100644 .serena/memories/codebase_structure.md create mode 100644 .serena/memories/project_overview.md create mode 100644 .serena/memories/suggested_commands.md create mode 100644 .serena/memories/task_completion_checklist.md create mode 100644 .serena/memories/windows_system_commands.md create mode 100644 .serena/project.yml diff --git a/.serena/memories/code_style_conventions.md b/.serena/memories/code_style_conventions.md new file mode 100644 index 000000000000..cdec0692a93c --- /dev/null +++ b/.serena/memories/code_style_conventions.md @@ -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 diff --git a/.serena/memories/codebase_structure.md b/.serena/memories/codebase_structure.md new file mode 100644 index 000000000000..cc2e75021663 --- /dev/null +++ b/.serena/memories/codebase_structure.md @@ -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 diff --git a/.serena/memories/project_overview.md b/.serena/memories/project_overview.md new file mode 100644 index 000000000000..6fea3e08fefe --- /dev/null +++ b/.serena/memories/project_overview.md @@ -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 diff --git a/.serena/memories/suggested_commands.md b/.serena/memories/suggested_commands.md new file mode 100644 index 000000000000..16ef76b8a5b8 --- /dev/null +++ b/.serena/memories/suggested_commands.md @@ -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 diff --git a/.serena/memories/task_completion_checklist.md b/.serena/memories/task_completion_checklist.md new file mode 100644 index 000000000000..1da615b3dec6 --- /dev/null +++ b/.serena/memories/task_completion_checklist.md @@ -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 diff --git a/.serena/memories/windows_system_commands.md b/.serena/memories/windows_system_commands.md new file mode 100644 index 000000000000..5fecf6dbf6f6 --- /dev/null +++ b/.serena/memories/windows_system_commands.md @@ -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 ` - 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 diff --git a/.serena/project.yml b/.serena/project.yml new file mode 100644 index 000000000000..8ea5c7141d20 --- /dev/null +++ b/.serena/project.yml @@ -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" From 53734344d50a11795c8e7efea1ac563916d3eb9e Mon Sep 17 00:00:00 2001 From: Michael Panchenko Date: Thu, 5 Jun 2025 17:00:27 +0200 Subject: [PATCH 2/2] Opus4 Solving 13974, https://claude.ai/share/5cc6565d-c645-47dd-8c07-350c28353452 --- sympy/physics/quantum/tensorproduct.py | 46 ++++++++++++++++++- .../quantum/tests/test_tensorproduct.py | 40 +++++++++++++++- 2 files changed, 84 insertions(+), 2 deletions(-) diff --git a/sympy/physics/quantum/tensorproduct.py b/sympy/physics/quantum/tensorproduct.py index 9dd10d219e43..eb6c37a52fc2 100644 --- a/sympy/physics/quantum/tensorproduct.py +++ b/sympy/physics/quantum/tensorproduct.py @@ -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. @@ -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): diff --git a/sympy/physics/quantum/tests/test_tensorproduct.py b/sympy/physics/quantum/tests/test_tensorproduct.py index 9f65844c85d6..0ed50580c2a2 100644 --- a/sympy/physics/quantum/tests/test_tensorproduct.py +++ b/sympy/physics/quantum/tests/test_tensorproduct.py @@ -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