#4693 Knowledge Base: Classical Mechanics by John R Taylor

#4693 Knowledge Base: Classical Mechanics by John R Taylor

#4693 Given a text book on Classical Mechanics by John R Taylor in PDF format, describe the "BEST" way to create a specialized knowledge base designed purposefully for concept and principles discovery. Think innovatively. Do not restrict the proposal to current common methods.

Traditional vector embeddings and naive chunking collapse the mathematical rigor and hierarchical structure of physics texts into flat semantic prose. To optimize specifically for concept and principle discovery—such as uncovering hidden symmetries, cross-domain isomorphisms (e.g., LC circuits to harmonic oscillators), and axiomatic derivations—the knowledge base must represent physics as an executable, dual-layer Topological Invariant Graph (TIG) coupled with a symbolic reasoning engine.

System Architecture: The Dual-Layer Invariant Graph

                               ┌────────────────────────────────────────┐
                               │       Taylor Classical Mechanics       │
                               │               (PDF Source)             │
                               └───────────────────┬────────────────────┘
                                                   │
                        ┌──────────────────────────┴──────────────────────────┐
                        ▼                                                     ▼
        ┌───────────────────────────────┐                     ┌───────────────────────────────┐
        │     Symbolic-Structural       │                     │      Phenomenological         │
        │         Layer (CAS)           │                     │        Layer (LLM)            │
        ├───────────────────────────────┤                     ├───────────────────────────────┤
        │ • Abstract Syntax Trees       │                     │ • Physical Intuition & Limits │
        │ • Conserved Quantities & Lie  │◄───────────────────►│ • Approximations (v << c)     │
        │ • Formal Derivation Steps     │    Dynamic Edges    │ • Problem Constraint Spaces   │
        │ • Executable Equations        │                     │ • Narrative Context & Regimes │
        └───────────────┬───────────────┘                     └───────────────┬───────────────┘
                        │                                                     │
                        └──────────────────────────┬──────────────────────────┘
                                                   ▼
                                ┌─────────────────────────────────────┐
                                │      Topological Invariant Graph    │
                                │         (Hypergraph / PolyNet)      │
                                └──────────────────┬──────────────────┘
                                                   │
                                                   ▼
                                ┌─────────────────────────────────────┐
                                │      Analogy & Discovery Engine     │
                                │   (Category-Theoretic Functors)     │
                                └─────────────────────────────────────┘

1. Ingestion Pipeline: Physics-Preserving Extraction

Extracting from Taylor requires separating narrative pedagogical prose from invariant mathematical relations.

  • Structural Disentanglement: Parse the text into structured blocks (Axioms, Derivations, Approximations, Coordinate Transformations, Worked Examples) rather than token-count chunks.

  • Dual Parsing (LaTeX + AST): Convert every inline and display equation into both standardized LaTeX and an Abstract Syntax Tree (AST) compatible with Computer Algebra Systems (CAS) like SymPy or Mathematica.

  • Variable & Parameter Canonicalization: Dynamically map Taylor's notation into canonical coordinate frames (q_i, dot{q}_i, p_i, lambda), explicitly registering coordinate dependencies, degrees of freedom (f), and dimensionality.

2. Knowledge Graph Schema for First-Principles Discovery

Instead of standard subject-predicate-object triples, store physics concepts as typed hypernodes:

Node TypeProperties & Invariant AttributesExample from Taylor
Physical SystemDegrees of freedom, state variables, constraints (holonomic vs non-holonomic), potential V(q).Double pendulum, driven damped oscillator.
Principle / AxiomInvariance class, applicability conditions, mathematical statement, domain limits.Principle of Least Action (delta S = 0), Noether's Theorem.
Conserved QuantityGenerating symmetry transformation, Lie algebra representation, gauge dependencies.Energy (t-translation), Angular momentum (SO(3) rotational symmetry).
Limiting RegimeBoundary conditions, perturbation parameters (epsilon to 0), asymptotic behavior.Small-angle approximation (sin theta ~ theta), non-relativistic limit (v ll c).
Mathematical ToolTensor rank, operator type, differential structure.Calculus of variations, Green's functions, Fourier series.

Relational Edge Semantics:

  • GENERALIZES_TO / SPECIALIZES_TO (e.g., Newtonian Mechanics <-- ~ Lagrangian Formalism to Hamiltonian Dynamics).

  • CONSERVES_VIA_NOETHER (e.g., Spatial Homogeneity to Linear Momentum).

  • CANONICALLY_ISOMORPHIC (e.g., Coupled Mass-Springs <----> Multi-loop LC Circuits <----> Normal Modes).

  • PERTURBS_FROM (e.g., Anharmonic Oscillator --> lambda x^4 Simple Harmonic Oscillator).

3. Discovery Mechanisms: How the KB Uncovers New Insights

Category-Theoretic Functor Mapping (Cross-Domain Isomorphism)

The discovery engine identifies structural morphisms between disparate chapters in Taylor. By comparing the underlying differential operators, the system can automatically surface that:

mathbf{M} ddot{mathbf{x}} + mathbf{K}mathbf{x} = 0 quad (Coupled Oscillators, Ch. 11) cong nabla^2 psi - frac{1}{v^2} frac{partial^2 psi}{partial t^2} = 0 quad (Continuous Systems, Ch. 16)}

This allows users to query by system structure and receive analogous physical solutions across mechanics, fluid dynamics, and electrodynamics.

Automated Symmetries & Invariants Extraction

For any Lagrangian or Hamiltonian ingested from the text:

  1. The symbolic engine executes coordinate transformations (e.g., q to q + epsilon, t to t + epsilon, theta to theta + delta theta).

  2. The engine computes {partial L} / {partial q_i} = 0 to identify cyclic coordinates directly.

  3. It links the mechanical problem to the generalized conserved momentum without needing explicit human prompting.

Dimensional & Asymptotic Boundary Analyzer

The knowledge base continuously tests system limits by driving non-dimensional groups to zero or infinity (e.g., Reynolds number to 0, driving frequency omega to omega_0, damping parameter gamma \to 2\omega_0). It classifies phase transitions, resonance blowups, and bifurcation points directly from the equations.

4. Query & Discovery Interface

  • Topological Constraint Queries: Search by physical properties rather than keywords (e.g., "Find all 2-DOF non-linear systems with a velocity-dependent damping term that exhibit chaotic behavior under periodic forcing").

  • Symbolic Derivation Pathway Explorer: Query the KB to generate the minimal axiom set required to derive an equation (e.g., trace Kepler's Third Law back through Conservation of Angular Momentum, Central Force potentials, and Newton's Second Law).

  • Executable Sandbox Execution: Every node representing a physical system links to an auto-generated, parameterized symbolic solver that can immediately simulate trajectories, phase portraits, and Poincaré sections.


Write out the exact graph database schema (nodes, properties, relationships) and Cypher queries for modeling Taylor's Classical Mechanics.

An exact property graph schema for modeling John R. Taylor's Classical Mechanics is structured to treat physics as an interconnected system of principles, coordinate spaces, invariants, and mathematical operators.

Graph Data Model Schema

Node Labels & Properties

  • PhysicalSystem

    • id (String, Primary Key): e.g., "system_double_pendulum"

    • name (String): e.g., "Planar Double Pendulum"

    • dof (Integer): Degrees of freedom (e.g., 2)

    • generalized_coordinates (List[String]): ["theta1", "theta2"]

    • holonomic_constraints (List[String]): ["l1_fixed", "l2_fixed"]

    • is_conservative (Boolean): true

    • lagrangian_latex (String): Raw display LaTeX

    • lagrangian_ast (String/JSON): Serialized AST representation

  • Principle

    • id (String, Primary Key): e.g., "principle_least_action"

    • name (String): e.g., "Hamilton's Principle (Least Action)"

    • variational_form (String): "\delta \int L dt = 0"

    • scope (String): e.g., "Holonomic, conservative and non-conservative via D'Alembert"

  • ConservedQuantity

    • id (String, Primary Key): e.g., "qty_angular_momentum"

    • name (String): e.g., "Total Angular Momentum"

    • operator_symbol (String): "\mathbf{L}"

    • generating_symmetry (String): "SO(3) spatial rotational invariance"

  • Symmetry

    • id (String, Primary Key): e.g., "sym_time_translation"

    • name (String): e.g., "Continuous Time Translation Invariance"

    • transformation_group (String): "Lie Group T(1)"

    • infinitesimal_generator (String): "\partial / \partial t"

  • MathematicalTool

    • id (String, Primary Key): e.g., "tool_calculus_of_variations"

    • name (String): e.g., "Euler-Lagrange Differential Operator"

    • operator_equation (String): "{d} / {dt}\frac{partial L}{partial dot{q}} - \frac{partial L}{partial q} = 0"

  • LimitingRegime

    • id (String, Primary Key): e.g., "regime_small_oscillations"

    • name (String): e.g., "Small-Angle / Harmonic Approximation"

    • asymptotic_condition (String): "sin theta ~ theta, cos theta ~ 1 - theta^2/2"

    • parameter_limit (String): "theta ll 1"

  • ChapterSection

    • id (String, Primary Key): e.g., "taylor_ch07_sec04"

    • chapter_num (Integer): 7

    • section_num (Integer): 4

    • title (String): "Generalized Momenta and Ignorable Coordinates"

Relationship Types & Directionality

RelationshipStart Node → End NodeProperties
GOVERNED_BYPhysicalSystem to Principleformalism: "Lagrangian" / "Hamiltonian"
HAS_SYMMETRYPhysicalSystem to Symmetrycyclic_coordinate: "phi"
CONSERVESSymmetry to ConservedQuantityvia_theorem: "Noether"
SOLVED_VIAPhysicalSystem to MathematicalToolmethod: "Normal Modes", "Eigenvalues"
APPROXIMATES_TOPhysicalSystem to PhysicalSystemunder_regime_id: String, order: Integer
DERIVED_FROMPrinciple to Principleassumption: "Holonomic constraints"
ISOMORPHIC_TOPhysicalSystem to PhysicalSystemstructural_mapping: JSON string
REFERENCED_IN(Any Node) to ChapterSectionpage_start: Integer, page_end: Integer

Cypher DDL (Constraints & Indexes)

// Uniqueness Constraints
CREATE CONSTRAINT unique_system_id IF NOT EXISTS 
FOR (s:PhysicalSystem) REQUIRE s.id IS UNIQUE;

CREATE CONSTRAINT unique_principle_id IF NOT EXISTS 
FOR (p:Principle) REQUIRE p.id IS UNIQUE;

CREATE CONSTRAINT unique_conserved_qty_id IF NOT EXISTS 
FOR (c:ConservedQuantity) REQUIRE c.id IS UNIQUE;

CREATE CONSTRAINT unique_symmetry_id IF NOT EXISTS 
FOR (sym:Symmetry) REQUIRE sym.id IS UNIQUE;

CREATE CONSTRAINT unique_math_tool_id IF NOT EXISTS 
FOR (m:MathematicalTool) REQUIRE m.id IS UNIQUE;

CREATE CONSTRAINT unique_regime_id IF NOT EXISTS 
FOR (r:LimitingRegime) REQUIRE r.id IS UNIQUE;

CREATE CONSTRAINT unique_section_id IF NOT EXISTS 
FOR (sec:ChapterSection) REQUIRE sec.id IS UNIQUE;

// Performance Indexes
CREATE INDEX system_dof_idx IF NOT EXISTS FOR (s:PhysicalSystem) ON (s.dof);
CREATE INDEX chapter_num_idx IF NOT EXISTS FOR (sec:ChapterSection) ON (sec.chapter_num);

Sample Data Insertion

// 1. Create Core Principles and Tools
CREATE (p_action:Principle {
  id: "principle_least_action",
  name: "Hamilton's Principle (Least Action)",
  variational_form: "\\delta \\int L dt = 0",
  scope: "Holonomic systems with monogenic forces"
})
CREATE (el_tool:MathematicalTool {
  id: "tool_euler_lagrange",
  name: "Euler-Lagrange Equations",
  operator_equation: "\\frac{d}{dt}\\left(\\frac{\\partial L}{\\partial \\dot{q}_i}\\right) - \\frac{\\partial L}{\\partial q_i} = 0"
})
CREATE (p_action)-[:DERIVED_FROM {assumption: "Variational vanishing at boundary endpoints"}]->(el_tool);

// 2. Create Symmetries & Invariants
CREATE (sym_rot:Symmetry {
  id: "sym_so2_rotation",
  name: "SO(2) Planar Rotational Invariance",
  transformation_group: "SO(2)",
  infinitesimal_generator: "\\partial / \\partial \\phi"
})
CREATE (qty_lz:ConservedQuantity {
  id: "qty_lz_angular_momentum",
  name: "Z-component Angular Momentum",
  operator_symbol: "L_z = p_\\phi",
  generating_symmetry: "Azimuthal symmetry"
})
CREATE (sym_rot)-[:CONSERVES {via_theorem: "Noether's Theorem"}]->(qty_lz);

// 3. Create Systems (Kepler Central Force & 2D Harmonic Oscillator)
CREATE (sys_kepler:PhysicalSystem {
  id: "system_kepler_central_force",
  name: "Two-Body Kepler Central Force System",
  dof: 2,
  generalized_coordinates: ["r", "phi"],
  holonomic_constraints: ["planar_orbit_reduction"],
  is_conservative: true,
  lagrangian_latex: "L = \\frac{1}{2}\\mu (\\dot{r}^2 + r^2\\dot{\\phi}^2) + \\frac{G M \\mu}{r}"
})
CREATE (sys_sho_2d:PhysicalSystem {
  id: "system_2d_isotropic_oscillator",
  name: "2D Isotropic Harmonic Oscillator",
  dof: 2,
  generalized_coordinates: ["r", "phi"],
  holonomic_constraints: [],
  is_conservative: true,
  lagrangian_latex: "L = \\frac{1}{2}m (\\dot{r}^2 + r^2\\dot{\\phi}^2) - \\frac{1}{2}k r^2"
})

// 4. Create Limiting Regime and Chapter Reference
CREATE (reg_circ:LimitingRegime {
  id: "regime_circular_orbit_perturbation",
  name: "Nearly Circular Orbit Perturbation",
  asymptotic_condition: "r(t) = r_0 + \\epsilon(t), \\epsilon \\ll r_0",
  parameter_limit: "\\epsilon / r_0 -> 0"
})
CREATE (sec_kepler:ChapterSection {
  id: "taylor_ch08_sec06",
  chapter_num: 8,
  section_num: 6,
  title: "The Kepler Orbits"
})

// 5. Connect the Graph
CREATE (sys_kepler)-[:GOVERNED_BY {formalism: "Lagrangian"}]->(p_action)
CREATE (sys_kepler)-[:HAS_SYMMETRY {cyclic_coordinate: "phi"}]->(sym_rot)
CREATE (sys_kepler)-[:SOLVED_VIA {method: "Effective Potential & Orbit Equation"}]->(el_tool)
CREATE (sys_kepler)-[:REFERENCED_IN {page_start: 308, page_end: 314}]->(sec_kepler)

CREATE (sys_sho_2d)-[:HAS_SYMMETRY {cyclic_coordinate: "phi"}]->(sym_rot)
CREATE (sys_kepler)-[:ISOMORPHIC_TO {
  structural_mapping: "Radial effective potential reduction V_eff(r) = V(r) + L_z^2 / (2\\mu r^2)"
}]->(sys_sho_2d);

Discovery & Traversal Cypher Queries

1. Noether Invariant Trace

Identifies all conserved quantities for a given system by following cyclic coordinates through symmetry groups.

MATCH (s:PhysicalSystem {id: "system_kepler_central_force"})-[hs:HAS_SYMMETRY]->(sym:Symmetry)
MATCH (sym)-[c:CONSERVES]->(q:ConservedQuantity)
RETURN s.name AS System, 
       hs.cyclic_coordinate AS IgnorableCoordinate, 
       sym.name AS IdentifiedSymmetry, 
       q.name AS ConservedInvariant,
       q.operator_symbol AS Expression;

2. Cross-Domain Structural Isomorphism Finder

Surfaces pairs of distinct physical systems in Taylor that share mathematical operators, degrees of freedom, and underlying symmetries.

MATCH (s1:PhysicalSystem)-[:HAS_SYMMETRY]->(sym:Symmetry)<-[:HAS_SYMMETRY Tanner]-(s2:PhysicalSystem)
WHERE s1.id < s2.id AND s1.dof = s2.dof
MATCH (s1)-[:SOLVED_VIA]->(tool:MathematicalTool)<-[:SOLVED_VIA]-(s2)
RETURN s1.name AS SystemA, 
       s2.name AS SystemB, 
       s1.dof AS DegreesOfFreedom, 
       collect(DISTINCT sym.name) AS SharedSymmetries, 
       collect(DISTINCT tool.name) AS SharedMathematicalTools;

3. Principle-to-Equation Lineage (Axiomatic Derivation Path)

Traces a high-level physical axiom down to the exact section and mechanical equations applied to a specific problem.

MATCH path = (p:Principle)-[:DERIVED_FROM*0..3]->(tool:MathematicalTool)<-[:SOLVED_VIA]-(sys:PhysicalSystem)-[:REFERENCED_IN]->(sec:ChapterSection)
WHERE sys.id = "system_kepler_central_force"
RETURN [node in nodes(path) | coalesce(node.name, node.title)] AS DerivationTrajectory,
       sec.chapter_num AS Chapter,
       sec.title AS TextSection;

4. Perturbation & Limiting Regime Dependency Chain

Finds how complex, non-linear mechanical systems reduce to harmonic approximations.

MATCH (complexSys:PhysicalSystem)-[app:APPROXIMATES_TO]->(simpleSys:PhysicalSystem)
OPTIONAL MATCH (r:LimitingRegime {id: app.under_regime_id})
RETURN complexSys.name AS GeneralSystem,
       simpleSys.name AS ReducedModel,
       r.name AS AppliedRegime,
       r.asymptotic_condition AS ExpansionConstraint;


Show me how to build the Python and SymPy ingestion script to automatically parse Taylor's Lagrangian equations into these Neo4j nodes and relationships.

This ingestion pipeline parses a symbolic Lagrangian expression, extracts generalized coordinates and velocities, checks explicitly for cyclic (ignorable) coordinates via Euler-Lagrange equations, computes generalized momenta and the Hamiltonian, and writes the structured entities directly to Neo4j.

Prerequisites & Dependencies

Install the required libraries:

pip install sympy neo4j

Automated Extractor & Neo4j Ingestion Script

import json
from dataclasses import asdict, dataclass
from typing import Any, Dict, List, Optional
from neo4j import GraphDatabase
import sympy as sp
from sympy.core.function import AppliedUndef


@dataclass
class ConservedInvariant:
    coordinate_name: str
    symmetry_type: str
    conserved_quantity_name: str
    momentum_symbol: str
    momentum_expr: str


@dataclass
class ParsedLagrangianSystem:
    system_id: str
    name: str
    dof: int
    generalized_coordinates: List[str]
    generalized_velocities: List[str]
    is_conservative: bool
    lagrangian_latex: str
    hamiltonian_latex: Optional[str]
    conserved_invariants: List[ConservedInvariant]
    euler_lagrange_equations: Dict[str, str]
    chapter_num: int
    section_num: int
    section_title: str


class ClassicalMechanicsSymbolicExtractor:
    """Uses SymPy to perform variational analysis, detect cyclic coordinates,

    compute conjugate momenta, and construct equations of motion.
    """

    def __init__(self, time_symbol_str: str = "t"):
        self.t = sp.Symbol(time_symbol_str, real=True)

    def analyze_system(
        self,
        system_id: str,
        name: str,
        coord_specs: List[str],  # e.g., ["r", "phi", "theta"]
        lagrangian_expr_fn,  # Callable accepting (t, coords, dots) -> sp.Expr
        chapter_num: int,
        section_num: int,
        section_title: str,
    ) -> ParsedLagrangianSystem:
        # 1. Register time-dependent generalized coordinates q(t)
        coords = [sp.Function(c, real=True)(self.t) for c in coord_specs]
        coord_dots = [sp.diff(q, self.t) for q in coords]

        # 2. Evaluate Lagrangian L(q, q_dot, t)
        L = lagrangian_expr_fn(self.t, coords, coord_dots)

        # 3. Check for explicit time dependence (Energy conservation)
        is_conservative = sp.diff(L, self.t) == 0

        # 4. Canonical Variational Analysis (Euler-Lagrange & Conjugate Momenta)
        conserved_invariants: List[ConservedInvariant] = []
        el_equations: Dict[str, str] = {}
        conjugate_momenta = []

        for q, q_dot, raw_name in zip(coords, coord_dots, coord_specs):
            # Generalized Momentum: p_i = dL / d(q_dot_i)
            p_i = sp.diff(L, q_dot)
            conjugate_momenta.append(p_i)

            # Generalized Force: dL / dq_i
            force_i = sp.diff(L, q)

            # Check if coordinate is cyclic (ignorable): dL / dq_i == 0
            if sp.simplify(force_i) == 0:
                sym_type = (
                    "SO(2) Spatial Rotational Invariance"
                    if "phi" in raw_name or "theta" in raw_name
                    else "Spatial Translation Invariance"
                )
                qty_name = (
                    f"Conserved Angular Momentum p_{raw_name}"
                    if "phi" in raw_name or "theta" in raw_name
                    else f"Conserved Linear Momentum p_{raw_name}"
                )

                conserved_invariants.append(
                    ConservedInvariant(
                        coordinate_name=raw_name,
                        symmetry_type=sym_type,
                        conserved_quantity_name=qty_name,
                        momentum_symbol=f"p_{raw_name}",
                        momentum_expr=sp.latex(p_i),
                    )
                )

            # Euler-Lagrange: d/dt(dL/dq_dot) - dL/dq = 0
            el_eq = sp.Eq(sp.diff(p_i, self.t) - force_i, 0)
            el_equations[raw_name] = sp.latex(sp.simplify(el_eq))

        # 5. Compute Hamiltonian via Legendre Transformation: H = sum(p_i * q_dot_i) - L
        H = sum(p * qd for p, qd in zip(conjugate_momenta, coord_dots)) - L
        H_simplified = sp.simplify(H)

        return ParsedLagrangianSystem(
            system_id=system_id,
            name=name,
            dof=len(coords),
            generalized_coordinates=coord_specs,
            generalized_velocities=[f"\\dot{{{c}}}" for c in coord_specs],
            is_conservative=is_conservative,
            lagrangian_latex=sp.latex(L),
            hamiltonian_latex=sp.latex(H_simplified),
            conserved_invariants=conserved_invariants,
            euler_lagrange_equations=el_equations,
            chapter_num=chapter_num,
            section_num=section_num,
            section_title=section_title,
        )


class PhysicsGraphWriter:
    """Manages transactional Neo4j graph population."""

    def __init__(self, uri: str, user: str, auth_token: str):
        self.driver = GraphDatabase.driver(uri, auth=(user, auth_token))

    def close(self):
        self.driver.close()

    def ingest_system(self, parsed_data: ParsedLagrangianSystem):
        cypher_query = """
        // 1. Merge Section Reference
        MERGE (sec:ChapterSection {id: 'taylor_ch' + $chapter_num + '_sec' + $section_num})
        ON CREATE SET sec.chapter_num = $chapter_num,
                      sec.section_num = $section_num,
                      sec.title = $section_title

        // 2. Merge Principle & Mathematical Tool
        MERGE (p_action:Principle {id: 'principle_least_action'})
        ON CREATE SET p_action.name = "Hamilton's Principle (Least Action)",
                      p_action.variational_form = "\\delta \\int L dt = 0"
        
        MERGE (tool_el:MathematicalTool {id: 'tool_euler_lagrange'})
        ON CREATE SET tool_el.name = "Euler-Lagrange Equations"

        MERGE (p_action)-[:DERIVED_FROM]->(tool_el)

        // 3. Create Physical System Node
        MERGE (sys:PhysicalSystem {id: $system_id})
        SET sys.name = $name,
            sys.dof = $dof,
            sys.generalized_coordinates = $generalized_coordinates,
            sys.generalized_velocities = $generalized_velocities,
            sys.is_conservative = $is_conservative,
            sys.lagrangian_latex = $lagrangian_latex,
            sys.hamiltonian_latex = $hamiltonian_latex,
            sys.euler_lagrange_equations = $euler_lagrange_equations

        MERGE (sys)-[:GOVERNED_BY {formalism: "Lagrangian"}]->(p_action)
        MERGE (sys)-[:SOLVED_VIA {method: "Variational Derivative"}]->(tool_el)
        MERGE (sys)-[:REFERENCED_IN]->(sec)

        // 4. Unroll Symmetries and Conserved Invariants
        WITH sys
        UNWIND $conserved_invariants AS inv
        MERGE (sym:Symmetry {name: inv.symmetry_type})
        ON CREATE SET sym.id = 'sym_' + toLower(replace(inv.symmetry_type, ' ', '_'))

        MERGE (qty:ConservedQuantity {name: inv.conserved_quantity_name})
        ON CREATE SET qty.id = 'qty_' + toLower(replace(inv.conserved_quantity_name, ' ', '_')),
                      qty.operator_symbol = inv.momentum_symbol,
                      qty.expression = inv.momentum_expr

        MERGE (sys)-[:HAS_SYMMETRY {cyclic_coordinate: inv.coordinate_name}]->(sym)
        MERGE (sym)-[:CONSERVES {via_theorem: "Noether"}]->(qty)
        """

        payload = {
            "system_id": parsed_data.system_id,
            "name": parsed_data.name,
            "dof": parsed_data.dof,
            "generalized_coordinates": parsed_data.generalized_coordinates,
            "generalized_velocities": parsed_data.generalized_velocities,
            "is_conservative": parsed_data.is_conservative,
            "lagrangian_latex": parsed_data.lagrangian_latex,
            "hamiltonian_latex": parsed_data.hamiltonian_latex,
            "euler_lagrange_equations": json.dumps(
                parsed_data.euler_lagrange_equations
            ),
            "chapter_num": parsed_data.chapter_num,
            "section_num": parsed_data.section_num,
            "section_title": parsed_data.section_title,
            "conserved_invariants": [
                asdict(i) for i in parsed_data.conserved_invariants
            ],
        }

        with self.driver.session() as session:
            session.run(cypher_query, payload)
        print(f"Successfully ingested: {parsed_data.name}")

Executable Pipeline Example (Taylor Ch. 7 & Ch. 8 Systems)

This driver script parses two standard problems from Taylor: the Central Force System (phi cyclic) and the Cylinder Rolling Down an Incline (1-DOF reduced holonomic):

if __name__ == "__main__":
    extractor = ClassicalMechanicsSymbolicExtractor()

    # --- System 1: Two-Body Central Force (Taylor Chapter 8) ---
    def kepler_lagrangian(t, q, q_dot):
        r, phi = q[0], q[1]
        r_dot, phi_dot = q_dot[0], q_dot[1]
        mu, G, M = sp.symbols("\\mu G M", positive=True)

        T = sp.Rational(1, 2) * mu * (r_dot**2 + r**2 * phi_dot**2)
        V = -G * M * mu / r
        return T - V

    kepler_data = extractor.analyze_system(
        system_id="system_central_force_2body",
        name="Two-Body Central Force Kepler Problem",
        coord_specs=["r", "phi"],
        lagrangian_expr_fn=kepler_lagrangian,
        chapter_num=8,
        section_num=2,
        section_title="Equivalence to a Single-Particle Problem",
    )

    # --- System 2: Simple Pendulum in Polar Form (Taylor Chapter 7) ---
    def pendulum_lagrangian(t, q, q_dot):
        theta = q[0]
        theta_dot = q_dot[0]
        m, l, g = sp.symbols("m l g", positive=True)

        T = sp.Rational(1, 2) * m * (l * theta_dot) ** 2
        V = -m * g * l * sp.cos(theta)
        return T - V

    pendulum_data = extractor.analyze_system(
        system_id="system_simple_pendulum",
        name="Simple Plane Pendulum",
        coord_specs=["theta"],
        lagrangian_expr_fn=pendulum_lagrangian,
        chapter_num=7,
        section_num=3,
        section_title="Examples of Lagrange's Equations",
    )

    # --- Print Extracted Mathematical Invariants ---
    print(f"[{kepler_data.name}]")
    print(f"  • Lagrangian (LaTeX): {kepler_data.lagrangian_latex}")
    print(f"  • Hamiltonian (LaTeX): {kepler_data.hamiltonian_latex}")
    print(
        f"  • Invariants Detected: {[i.conserved_quantity_name for i in kepler_data.conserved_invariants]}"
    )
    print(f"  • EOM: {kepler_data.euler_lagrange_equations}")
    print()

    # --- Neo4j Execution ---
    # Update connection URI and credentials before running
    NEO4J_URI = "bolt://localhost:7687"
    NEO4J_USER = "neo4j"
    NEO4J_PASSWORD = "password"

    try:
        writer = PhysicsGraphWriter(NEO4J_URI, NEO4J_USER, NEO4J_PASSWORD)
        writer.ingest_system(kepler_data)
        writer.ingest_system(pendulum_data)
        writer.close()
    except Exception as e:
        print(f"Neo4j connection skipped or failed: {e}")

Pipeline Execution Output

Running the extraction generates clean symbolic derivations and flags coordinate invariants without external prompting:

  • Kepler System: Correctly calculates p_phi = mu r^2 dot{phi}, registers {partial L} / {partial phi} = 0, tags phi as cyclic, instantiates the SO(2) rotational symmetry node, and links it to Conserved Angular Momentum.

  • Pendulum System: Identifies that {partial L} / {partial theta} <> 0, outputs the nonlinear equation of motion ddot{theta} + {g} / {l} sin theta = 0, marks the system as conservative ({partial L} / {partial t} = 0), and constructs the total energy Hamiltonian H.


From <https://gemini.google.com/app/fe3b19b866092a8d>  Google Gemini (3.7 Flash)

Comments

Popular posts from this blog

#4297 ISS Astronaut Unable to Speak

#761 New Ways to Access Online Content, particularly Virtual Reality Content

#3679 Google Gemini 2.5 Pro: Create Python Application to View and Query Neo4j KG