iTensor Architecture

A comprehensive overview of iTensor's system design and components

iTensor Architecture

A comprehensive look at iTensor's technical architecture, component interactions, and design principles.

Architecture Overview

Understanding the architecture of iTensor helps contributors and advanced users navigate the codebase and understand how different components interact. iTensor follows a client-server model with a modern web frontend and Python backend, organized in a modular structure that facilitates both educational use and research-grade simulations.

Key Architectural Components

  • A Next.js frontend (TypeScript/React) serving as the user interface with Anime.js for dynamic, interactive visualizations
  • A Backend computation engine (Python) housing core tensor calculation logic
  • Dedicated modules for symbolic (using SymPy) and numerical (using NumPy, SciPy) tensor operations
  • Coordinate system and differential operator modules supporting arbitrary curvilinear coordinates
  • Visualization modules for rendering black hole simulations and tensor transformations
  • REST API endpoints that facilitate communication between frontend and backend

System Architecture Diagram

The following simplified diagram illustrates the high-level architecture of iTensor and the flow of operations:

┌─────────────────────────────┐          ┌──────────────────────────────────────┐
│                             │          │                                      │
│         Next.js             │  HTTP    │        Computation Engine            │
│         Frontend            │◄────────►│            (Python)                  │
│     (TypeScript/React)      │  JSON    │                                      │
│                             │          │                                      │
└───────────┬─────────────────┘          └───────────┬───────────┬──────────────┘
            │                                        │           │
┌───────────▼─────────────────┐          ┌───────────▼──┐ ┌──────▼────────┐
│       Visualization         │          │   Symbolic   │ │   Numerical   │
│         Components          │          │   Module     │ │   Module      │
│     (Anime.js, React)       │          │   (SymPy)    │ │  (NumPy/SciPy)│
└─────────────────────────────┘          └──────┬───────┘ └───────┬───────┘
                                                │                 │
                                         ┌──────▼─────────────────▼──────┐
                                         │   Coordinate System &         │
                                         │   Differential Operators      │
                                         │                               │
                                         └───────────────────────────────┘

Frontend Architecture

The frontend is a Next.js application written in TypeScript and React. It provides a modern, responsive interface for users to interact with iTensor's capabilities and visualize black hole physics.

Key Frontend Features

  • Interactive Forms: Input interfaces for tensor data, expressions, and black hole parameters
  • Result Visualization: Visual representation of computation results and physics simulations
  • Interactive Animations: Dynamic visualizations using Anime.js for tensor transformations and physical phenomena
  • Documentation: Comprehensive guides and API references
  • API Communication: Handles RESTful calls to the backend computation engine

The frontend operates as a static single-page application (SPA) that communicates with the backend via REST API calls. For documentation pages, Next.js handles server-side rendering for better SEO, while for interactive computations and visualizations, it functions as a React app making asynchronous API requests.

Visualization Layer

The visualization components are a critical part of the frontend architecture, particularly for the black hole physics platform:

Visualization Features

  • Anime.js Integration: Powers smooth animations that demonstrate matrix and tensor transformations in black hole environments
  • Static Displays: Show step-by-step breakdowns of computed quantities (e.g., gradients and Christoffel symbols)
  • MathJax/KaTeX Integration: Renders symbolic mathematical expressions in a readable format
  • Interactive Charts: Display numerical simulation results with user-controllable parameters
  • Shape Morphing: Visualizes how objects deform in curved spacetime
  • Motion Path Visualization: Shows particle trajectories and light paths near black holes
  • Timeline-based Animations: Illustrates dynamic processes like accretion disk evolution and gravitational redshift

Backend Architecture

The backend is a Python-based computation engine that houses the core logic for tensor operations, differential geometry, and physics simulations. It employs a modular design where functionality is organized into specialized components.

API Layer

The backend exposes several API endpoints to support various computation and visualization needs:

/api/tensors/symbolic/

Handles symbolic tensor operations using SymPy. Processes requests with symbolic variables and returns analytical results.

/api/tensors/numerical/

Manages numerical tensor operations using NumPy. Works with concrete numeric data and performs high-performance computations.

/api/blackhole/parameters/

Configures and retrieves black hole parameters (mass, spin, charge) for simulations and visualizations.

/api/blackhole/simulation/

Executes physics simulations including gravitational effects, particle trajectories, and accretion disk dynamics.

Computation Modules

Symbolic Module

The symbolic module leverages SymPy to handle algebraic tensor expressions symbolically. Key features include:

  • Parsing JSON representation of symbolic tensors into SymPy objects
  • Computing operations like addition, multiplication, and contraction symbolically
  • Symbolic differentiation and integration of tensor expressions
  • Deriving equations for curved spacetime and black hole physics
  • Converting results back to JSON-serializable format for API responses

Numerical Module

The numerical module uses NumPy and SciPy for high-performance computations. Its responsibilities include:

  • Converting JSON tensor data to NumPy arrays
  • Executing operations like matrix multiplication, tensor contraction, and element-wise functions
  • Numerical integration of differential equations for physics simulations
  • High-performance calculations for black hole physics (using optimized C/C++ extensions where needed)
  • Optimizing performance for large-scale tensor operations
  • Serializing calculation results back to JSON for API responses

Coordinate System & Differential Operators

This specialized module handles coordinate transformations and differential operations in curved spacetime:

  • Support for arbitrary curvilinear coordinate systems
  • Calculation of metric tensors and their inverses
  • Computation of Christoffel symbols, Riemann tensor, and other geometric quantities
  • Implementation of differential operators (gradient, divergence, curl, wave operators)
  • Transformations between different coordinate systems
  • Special handling for black hole coordinates (Schwarzschild, Kerr, etc.)

Shared Logic

Some functionality is common across multiple modules:

  • Input validation to ensure tensors have compatible shapes
  • Common utility functions and helpers
  • Error handling patterns to provide consistent API responses
  • Conversion between internal representations
  • Caching mechanisms for improved performance
  • Logging and diagnostics for debugging

Error Handling & Logging

The Django backend provides robust error handling and logging mechanisms:

Error Handling Strategy

  • Input Validation: Validates requests before processing to catch invalid parameters early
  • Error Responses: Returns descriptive error messages as JSON with appropriate HTTP status codes
  • Exception Handling: Catches and processes exceptions from computation modules
  • Graceful Degradation: Provides useful fallbacks when operations cannot be completed as requested

Common error scenarios handled by the API include:

  • Missing or invalid fields in the request
  • Incompatible tensor shapes for the requested operation
  • Unsupported operations or tensor types
  • Parsing errors in symbolic expressions
  • Runtime computation errors (like division by zero)

Database (Optional)

iTensor's core functionality is primarily computational and doesn't necessarily require persistent storage. However, the Django framework comes with database capabilities that can be utilized for certain features:

Potential Database Uses

  • Caching Results: Storing computation results for frequently used operations
  • User Sessions: Maintaining user state and history if authentication is implemented
  • Saved Tensors: Allowing users to save and retrieve tensors for future use
  • Usage Analytics: Tracking API usage patterns (with proper privacy considerations)

In the current implementation, iTensor may use Django's default SQLite database minimally or not at all, treating each request independently in a stateless manner. This simplifies the architecture while still providing the flexibility to add database-backed features in the future.

Frontend-Backend Integration

The communication between frontend and backend follows a standard RESTful pattern:

Communication Flow

  1. User Interaction: User fills a form to describe a tensor operation (e.g., adding two matrices) and submits the request.
  2. Frontend Processing: The Next.js app validates inputs, formats the data as JSON, and makes an asynchronous fetch call to the appropriate API endpoint.
  3. Backend Processing: The Django API receives the request, validates it, processes the operation using the appropriate module (symbolic or numerical), and prepares a response.
  4. Response Handling: The frontend receives the JSON response, updates the UI to display the result or any error messages, and enables further interaction.

Because the backend is separate from the frontend, the frontend must handle asynchronous responses and possible error conditions. The API is designed to provide clear error messages that can be displayed to users when operations fail.

Deployment Considerations

The monolithic architecture of iTensor influences its deployment strategy:

Deployment Options

  • Monolithic Deployment: The entire Django application is deployed as a single unit, typically behind a WSGI server like Gunicorn and a reverse proxy like Nginx.
  • Static Frontend: The Next.js frontend can be built as static assets and deployed separately to a CDN or static hosting service for optimal performance.
  • Scaling Strategy: For handling increased load, multiple instances of the Django application can be deployed behind a load balancer.

While currently monolithic, the architecture allows for future evolution:

  • Heavy numerical computations could be offloaded to dedicated services
  • Background job workers (e.g., Celery) could handle long-running calculations asynchronously
  • The API could be separated from the frontend completely for independent scaling

For more details on deployment, please refer to the Deployment Guide.

Monorepo vs. Separate Repositories

iTensor's code organization strategy affects development workflow and contribution:

Monorepo Approach

Keeps frontend and backend in one repository:

  • Easier issue tracking across components
  • Simplified version control and synchronization
  • Unified contribution workflow
  • Centralized documentation

Separate Repositories

Divides frontend and backend into different repos:

  • Independent release cycles
  • Specialized team ownership
  • Clearer separation of concerns
  • Potentially more focused contribution

iTensor's documentation suggests a unified project name, but either structure is possible. In a monorepo, you'd typically have directories like frontend/ and backend/. In separate repos, integration is managed through configuration and documented API contracts.