Skip to content

Conversation

@krystophny
Copy link
Member

@krystophny krystophny commented Nov 26, 2025

PR Type

Enhancement


Description

  • Add multiple numerical integration schemes for charged particle dynamics

    • Symplectic midpoint, variational midpoint, Lagrange, Runge-Kutta methods
    • Explicit-implicit and symplectic Euler implementations
  • Create field evaluation module with tokamak magnetic field model

  • Develop manifold analysis and visualization tools for particle trajectories

  • Add plotting utilities for orbit and manifold visualization

  • Reorganize and clean up codebase with test utilities


Diagram Walkthrough

flowchart LR
  A["Field Model<br/>field_correct_test.py"] --> B["Integration Schemes"]
  B --> C["cpp_sym_midpoint.py"]
  B --> D["cp_sym_midpoint.py"]
  B --> E["cpp_lagrange.py"]
  B --> F["cpp_runge_kutta.py"]
  B --> G["cpp_expl_impl.py"]
  C --> H["Visualization"]
  D --> H
  E --> H
  F --> H
  G --> H
  H --> I["plotale.py<br/>manifolds.py"]
Loading

File Walkthrough

Relevant files
Enhancement
13 files
field_correct_test.py
Tokamak magnetic field model implementation                           
+57/-0   
cpp_sym_midpoint.py
Symplectic midpoint integration for charged particles       
+121/-0 
cp_sym_midpoint.py
Classical particle symplectic midpoint scheme                       
+221/-0 
cpp_var_midpoint.py
Variational midpoint integrator implementation                     
+111/-0 
cpp_lagrange.py
Lagrange formalism integration scheme                                       
+97/-0   
cpp_runge_kutta.py
Runge-Kutta explicit integration method                                   
+113/-0 
cpp_expl_impl.py
Explicit-implicit hybrid integration scheme                           
+84/-0   
cpp_sym_euler.py
Symplectic Euler integration method                                           
+79/-0   
cp_runge_kutta.py
Classical particle Runge-Kutta integration                             
+121/-0 
plotale.py
Orbit and manifold visualization utilities                             
+98/-0   
manifolds.py
Manifold analysis and trajectory visualization                     
+431/-0 
field.py
Simple magnetic field models with numba optimization         
+143/-0 
util.py
Legendre polynomials and elliptic integral utilities         
+197/-0 
Formatting
1 files
discrete_variational.py
Minor formatting and print statement additions                     
+3/-1     
Tests
4 files
DELETE.py
Test script for symplectic midpoint method                             
+44/-0   
main.py
Test implementation for guiding center approximation         
+88/-0   
mainHam.py
Hamiltonian formalism test with implicit integration         
+88/-0   
mainLa.py
Lagrangian formalism test implementation                                 
+86/-0   
Miscellaneous
1 files
pauli_particle.py
Removed obsolete Pauli particle implementation                     
+0/-87   

@qodo-code-review
Copy link

PR Compliance Guide 🔍

Below is a summary of compliance checks for this PR:

Security Compliance
🟢
No security concerns identified No security vulnerabilities detected by AI analysis. Human verification advised for critical code.
Ticket Compliance
🎫 No ticket provided
  • Create ticket/issue
Codebase Duplication Compliance
Codebase context is not defined

Follow the guide to enable codebase context checks.

Custom Compliance
🟢
Generic: Secure Error Handling

Objective: To prevent the leakage of sensitive system information through error messages while
providing sufficient detail for internal debugging.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Secure Logging Practices

Objective: To ensure logs are useful for debugging and auditing without exposing sensitive
information like PII, PHI, or cardholder data.

Status: Passed

Learn more about managing compliance generic rules or creating your own custom rules

🔴
Generic: Meaningful Naming and Self-Documenting Code

Objective: Ensure all identifiers clearly express their purpose and intent, making code
self-documenting

Status:
Ambiguous Names: Variables like z1, z2, z3, X, Y, Z, c, and loop counters with reused names reduce clarity
and violate meaningful naming guidance.

Referred Code
# x^i = x^i(q)
x = (R0 + q[:,0] * np.cos(q[:,1])) * np.cos(q[:,2])
y = (R0 + q[:,0] * np.cos(q[:,1])) * np.sin(q[:,2])
z = z0 + q[:,0] * np.sin(q[:,1])
###
#
#
#
#
#
#
#
#


    #vx5[j] = x_dot[0]
    #vy5[j] = x_dot[1]
    #vz5[j] = x_dot[2]





 ... (clipped 58 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Comprehensive Audit Trails

Objective: To create a detailed and reliable record of critical system actions for security analysis
and compliance.

Status:
No Logging: The new simulation steps, root-solver calls, and field evaluations perform critical
numerical actions without any audit/logging of inputs, outputs, or outcomes.

Referred Code
for kt in range(nt):
    pold = p

    sol = root(F, z[:,kt], method='hybr',tol=1e-12,args=(z[:,kt], pold))
    z[:,kt+1] = sol.x

    f.evaluate(z[0,kt+1], z[1,kt+1], z[2,kt+1])
    g = metric(z[:,kt+1])
    vel[:,kt+1] = 1/m * g['^ii']*(p - qe/c*np.array([0, f.co_Ath, f.co_Aph]))

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Robust Error Handling and Edge Case Management

Objective: Ensure comprehensive error handling that provides meaningful context and graceful
degradation

Status:
Unhandled Solver: Calls to scipy.optimize.root assume success without checking sol.success or handling
failures, which may cause silent numerical errors.

Referred Code
pold = p

sol = root(F, z[:,kt], method='hybr',tol=1e-12,args=(z[:,kt], pold))
z[:,kt+1] = sol.x

f.evaluate(z[0,kt+1], z[1,kt+1], z[2,kt+1])
g = metric(z[:,kt+1])
vel[:,kt+1] = 1/m * g['^ii']*(p - qe/c*np.array([0, f.co_Ath, f.co_Aph]))

Learn more about managing compliance generic rules or creating your own custom rules

Generic: Security-First Input Validation and Data Handling

Objective: Ensure all data inputs are validated, sanitized, and handled securely to prevent
vulnerabilities

Status:
Input Bounds: Mathematical functions (e.g., elliptic integrals, Legendre polynomials) accept raw inputs
without explicit validation, relying on comments rather than enforcing domain constraints.

Referred Code
@njit
def ellipe(m):
    """
    Compute the complete elliptic integral of the second kind.
    Adapted from Cephes Math Library by Stephen L. Moshier
    MIT License

    Parameters:
        m (float): Input parameter (0 <= x <= 1)

    Returns:
        float: Computed value of E(m)
    """

    P = np.array(
        [
            1.53552577301013293365e-4,
            2.50888492163602060990e-3,
            8.68786816565889628429e-3,
            1.07350949056076193403e-2,
            7.77395492516787092951e-3,


 ... (clipped 32 lines)

Learn more about managing compliance generic rules or creating your own custom rules

Compliance status legend 🟢 - Fully Compliant
🟡 - Partial Compliant
🔴 - Not Compliant
⚪ - Requires Further Human Verification
🏷️ - Compliance label

@qodo-code-review
Copy link

PR Code Suggestions ✨

Explore these optional code suggestions:

CategorySuggestion                                                                                                                                    Impact
High-level
Consolidate duplicated code and experimental scripts

The PR should be refactored to address widespread code duplication, especially
of the metric function. Additionally, temporary and experimental files like
DELETE.py, the test_delete_later directory, and manifolds.py should be removed
or cleaned up.

Examples:

python/cp_runge_kutta.py [18-28]
metric = lambda z: {
    "_11": 1,
    "_22": z[0]**2,
    "_33": (1 + z[0]*np.cos(z[1]))**2,
    "^11": 1,
    "^22": 1/z[0]**2,
    "^33": 1/(1 + z[0]*np.cos(z[1]))**2,
    "d_11": [0,0,0],
    "d_22": [2*z[0], 0,0],
    "d_33": [2*(1+z[0]*np.cos(z[1]))*np.cos(z[1]), -2*(1+z[0]*np.cos(z[1]))*np.sin(z[1]), 0],

 ... (clipped 1 lines)
python/cp_sym_midpoint.py [17-23]
metric = lambda z: {
    "_ii":  np.array([1, z[0]**2, (1 + z[0]*np.cos(z[1]))**2]),
    "^ii":  np.array([1, 1/z[0]**2, 1/(1 + z[0]*np.cos(z[1]))**2]),
    "d_11": np.array([0,0,0]),
    "d_22": np.array([2*z[0], 0,0]),
    "d_33": np.array([2*(1+z[0]*np.cos(z[1]))*np.cos(z[1]), -2*(1+z[0]*np.cos(z[1]))*np.sin(z[1]), 0]),
}

Solution Walkthrough:

Before:

# In file 'python/cp_runge_kutta.py'
metric = lambda z: { ... } # Definition 1
...

# In file 'python/cp_sym_midpoint.py'
metric = lambda z: { ... } # Definition 2
...

# In file 'python/cpp_expl_impl.py'
metric = lambda z: { ... } # Definition 3
...
# ... and so on in 5 other files

# In file 'python/DELETE.py'
# ... temporary script ...

# In directory 'python/test_delete_later/'
# ... multiple temporary scripts ...

After:

# In a new file 'python/utils.py' or 'python/common.py'
def get_metric(z):
    # Centralized metric function logic
    return {
        "_ii":  np.array([1, z[0]**2, (1 + z[0]*np.cos(z[1]))**2]),
        "^ii":  np.array([1, 1/z[0]**2, 1/(1 + z[0]*np.cos(z[1]))**2]),
        ...
    }

# In file 'python/cp_runge_kutta.py'
from .utils import get_metric
metric = get_metric
...

# In file 'python/cp_sym_midpoint.py'
from .utils import get_metric
metric = get_metric
...
# ... and so on in other files

# Files 'DELETE.py' and directory 'test_delete_later/' are removed.
Suggestion importance[1-10]: 9

__

Why: This suggestion correctly identifies major structural issues, including significant code duplication of the metric function and the inclusion of numerous experimental/temporary files, which severely impact maintainability and code quality across the entire PR.

High
  • More

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants