Wednesday, December 2, 2026

 Relative Ground Geometry Engine (RGGE).

The objective is:

Given a nadir drone video, construct a persistent ground-plane coordinate system spanning the entire flight path. Estimate relative distances, areas, and sizes in that coordinate system. Anchor the scale using known-size objects such as vehicles. Then allow an LLM/VLM to query the reconstructed geometry.

This is a lightweight photogrammetry system than an AI world model.


Desired output

Suppose the drone flies from:

Point A

  ->

Park

  ->

Shopping Center

  ->

Intersection

  ->

Point B

The engine should ultimately produce something like:

Reference coordinate system:

Origin:

(0,0) = first frame

Park centroid:

(525 m, 180 m)

Shopping center:

(1070 m, 220 m)

Intersection:

(1515 m, -35 m)

Then the LLM can answer:

How far was the park from the shopping center?

~547 meters

or

How large was the park?

~4.2 hectares

about 12 football fields

or

Was the park larger than the mall parking lot?

Park:

42,000 m²

Parking lot:

17,000 m²


The geometry representation

Everything is represented in a 2D ground plane.

Not pixels.

Not latitude/longitude.

Not camera coordinates.

Just:

class GroundEntity:

    id: str

    polygon_world

    area_m2

    centroid_x

    centroid_y

Everything becomes:

roads

parks

buildings

parking lots

sports fields

water bodies

represented as polygons in one continuous ground-plane map.


The smallest useful model

Should an LLM or VLM be extended?

Hypothesis:

Use a tiny VLM only for semantic labeling.

Example candidates:

Florence-2-base

DINOv2-small

SmolVLM

Qwen2.5-VL-3B

The geometry itself should not be learned by the model.

Geometry should be computed.

The model only identifies:

park

road

baseball field

shopping center

lake

building

Everything else comes from geometry.


Core pipeline

Stage 1

Extract video frames

video

  ->

1 fps

  ->

frames


Stage 2

Estimate orthomosaic (https://github.com/ravibeta/dvsa-api/pull/32) or inter-frame homographies

Use:

ORB

SIFT

SuperPoint

LightGlue

For each pair:

Frame(t)

Frame(t+1)

compute:

H(t)


Stage 3 (prefer this to stage 2)

Build a global mosaic

Instead of using homographies independently:

Frame1

Frame2

Frame3

Frame4

compose them:

GlobalCoordinateSystem

This becomes:

World Mosaic

similar to drone orthomosaic software.

Not necessarily photo-realistic.

Geometry is what matters.


Stage 4

Semantic segmentation

Run a lightweight model:

park

road

building

parking lot

water

vegetation

Each detected region becomes:

polygon

inside the global mosaic.


The most important challenge

Scale

Homography-only reconstruction provides:

relative distance

but not:

meters

Scale recovery is needed. Vehicle-based approach works.


Scale anchor from vehicles

Suppose the model detects:

sedan

SUV

pickup

Known average lengths:

sedan:

4.5 m

SUV:

4.8 m

pickup:

5.4 m

Measure:

length_pixels

inside the mosaic.

Compute:

meters_per_pixel

For example:

4.8 m

--------

48 pixels

=

0.10 m/pixel

Repeat across hundreds of vehicles.

Use robust median estimation.

Now the entire mosaic acquires scale.


Better scale anchors

Vehicles should not be the only source.

Add:

basketball courts

tennis courts

soccer fields

baseball diamonds

road lane widths

crosswalk markings

parking spaces

These are geometric standards.

Examples:

lane width

≈ 3.6 m

parking stall

≈ 2.7 m

tennis court

≈ 23.77 m

The engine can fuse all of them.

Scale uncertainty drops dramatically.


The geometry engine model

A small model is preferable for this.

Instead of asking:

What is this object?

train an adapter to output:

{

  "type": "park",

  "polygon": [...],

  "confidence": 0.93

}

The model's purpose becomes:

semantic geometry extraction

rather than captioning.


Geometry database

Store:

class PolygonFeature:

    id

    category

    polygon

    area_m2

    perimeter_m

    centroid

Examples:

Park_A

Area:

41,220 m²

Centroid:

(511,221)

Bounds:

(...)

Now every query becomes computational geometry.

Not LLM reasoning.


Query layer

Then the LLM becomes extremely small.

When a user asks:

How far was the park from the baseball field?

the system executes:

distance(

    park.centroid,

    field.centroid

)

When asked:

How large was that building?

the system executes:

polygon_area(building)

When asked:

Compare the park to the Space Needle footprint.

the LLM only performs the comparison narrative after receiving the computed area.


Why this fits DVSA

The architecture aligns surprisingly well with DVSA's existing strengths:

Video

  ->

Frame extraction

  ->

Feature matching

  ->

Homography estimation

  ->

Global mosaic

  ->

Segmentation

  ->

Ground-plane geometry store

  ->

LLM query layer

The important point is that the geometry engine should be treated as a deterministic subsystem.

The model identifies semantic regions.

The geometry engine computes:

• areas

• lengths

• distances

• centroids

• boundaries

• relative positions

The LLM merely translates those measurements into human language.

This does not build "an LLM that learns geometry." This would build "a geometric map reconstruction engine that exposes geometry as tools to an LLM." For urban nadir drone videos, the hope is that this approach will be more accurate, easier to debug, and much easier to integrate into DVSA than training a new geometry-capable foundation model.



Tuesday, December 1, 2026

 While Anima Anandkumar’s work on neural operators popularized PDE-inspired learning for high-dimensional spatiotemporal predictions, UAV researchers have used PDEs more directly as mathematical tools to model drone trajectories, risk fields, and congestion dynamics. Partial differential equations (PDEs) have been applied to drone flight planning in both academic research and industrial contexts, particularly for trajectory optimization and shared airspace management.

In academic literature, one notable example is the work by Radmanesh, Kumar, and French at NASA JPL and the University of Cincinnati, who developed a PDE-based trajectory planning framework for multiple UAVs in dynamic and uncertain environments. Their approach modeled drone paths using analogies to fluid flow through porous media: risk factors such as obstacles or hostile zones were encoded as porosity values, and optimal trajectories emerged as streamlines of the PDE system. This method provided near-optimal paths with reduced computational cost compared to traditional optimization techniques, while still respecting UAV dynamics and constraints. A related study extended this idea to large-scale decentralized path planning in shared airspace, using PDE formulations to coordinate many UAVs simultaneously without centralized control, which is crucial for drone delivery networks operating in dense urban skies.

Industrial applications are emerging in logistics and delivery. For example, research on hybrid truck–drone delivery systems under aerial traffic congestion has explored PDE-inspired traffic flow models to capture congestion effects in drone swarms. By treating drone traffic as a continuous flow field, PDEs help predict bottlenecks and optimize routing strategies for delivery fleets, ensuring efficiency and safety in congested aerial corridors. This is conceptually similar to how PDEs are used in fluid dynamics or traffic engineering, but applied to aerial mobility.

PDE-based methods provide a physics-grounded framework for drone autonomy. Unlike purely heuristic or graph-based planners, PDEs allow drones to adapt trajectories in real time to dynamic environments, encode risk as continuous fields, and scale to multi-agent coordination. For drone delivery, this means safer navigation in urban airspace, better integration with manned aviation, and resilience against uncertainties like wind or GPS drift. While commercial platforms (e.g., Amazon Prime Air, Zipline) often rely on proprietary optimization and machine learning, the academic PDE-based approaches are laying the groundwork for scalable, mathematically rigorous flight planning systems.

While PDEs have already been applied to UAV trajectory planning, decentralized airspace coordination, and congestion-aware delivery logistics and they bridge the gap between physics-inspired modeling and operational autonomy, their integration with neural operators could further enhance predictive capabilities for full 3D + time flight planning. This suggests a convergence of neural operators and drone delivery research in the near future. 

Continuing from the PDE-based perspective, it’s useful to compare how these methods stack up against other dominant paradigms in drone flight planning: graph search algorithms and reinforcement learning.

Graph search algorithms such as A* and D* have long been the backbone of UAV path planning. They discretize the environment into nodes and edges, then compute shortest paths subject to constraints. Their strength lies in simplicity, guaranteed optimality (under certain heuristics), and ease of implementation. However, graph search struggles with scalability in continuous, high-dimensional spaces. For example, in 3D urban airspace with dynamic obstacles, discretization can become computationally expensive and brittle. PDE-based methods, by contrast, treat the environment as a continuous field, allowing drones to “flow” around obstacles in real time. This makes PDEs more naturally suited to continuous adaptation and multi-agent coordination.


Monday, November 30, 2026

 NVIDIA PhysicsNeMo could be in DVSA-API’s future because the project is already evolving beyond video indexing toward understanding how the physical world behaves. DVSA today ingests aerial video, extracts visual information, performs computer vision analysis, builds indexes, supports reasoning models, and exposes agentic workflows around drone observations. The next step would be physics-informed AI rather than only perception-driven AI.

PhysicsNeMo is fundamentally different from conventional neural inference systems. Instead of learning only statistical relationships, it learns physical constraints, governing equations, conservation rules, spatial dynamics, and system behavior. Similar to Intrinsic AI direction explored in earlier articles, where the objective is not merely predicting observations but discovering the latent mechanisms that generate them by seeking internal representations of causality, objects, forces, constraints, persistence, and world dynamics, PhysicsNeMo provides a practical framework for building such world models because it combines machine learning with physical laws.

For example, camera-motion-aware scene understanding is a primary use case. DVSA already reconstructs motion through homographies, trajectories, feature matching, and optical-flow analysis. A PhysicsNeMo model could learn a physical state representation of the drone, terrain, and observed objects rather than processing each frame independently. Instead of merely detecting that a vehicle moved, the system could estimate velocity, acceleration, future location, likely path, and interactions with surrounding structures. The result would be a transition from object detection toward physical state estimation. DVSA would become capable of reasoning over what is likely happening in the scene rather than simply what appears in the pixels.

A second opportunity is predictive video understanding. Today DVSA stores videos, extracts frames, indexes observations, performs retrieval, and supports chat-based questioning. A PhysicsNeMo world model could predict future scene evolution. After observing a drone survey of a parking lot, road network, harbor, construction site, or industrial facility, the system could estimate future occupancy, traffic flow, congestion, queue formation, equipment movement, or infrastructure changes. This would shift DVSA from a retrospective analytics system into a forecasting platform. The system would answer not only “What happened?” but also “What is likely to happen next?”

A third application is anomaly detection. Current anomaly detection often relies on deviations from previously observed patterns. PhysicsNeMo allows anomalies to be defined as violations of learned physical rules. For example, a vehicle moving against expected traffic flow, an aircraft behaving outside feasible flight envelopes, a vessel violating navigational constraints, or a construction process diverging from expected progression could all be identified using a learned physical model. Such anomalies are often more meaningful than purely visual differences because they represent violations of underlying system behavior rather than changes in appearance.

A fourth opportunity is geospatial digital twins. DVSA already contains Azure storage, indexing, retrieval, observability, agent frameworks, and batch-processing infrastructure. A PhysicsNeMo layer could continuously ingest aerial observations and update a latent simulation of the monitored environment. The simulation would persist across flights and across days. Instead of treating every incoming video as an isolated asset, DVSA would maintain a living model of the environment. New observations would update state estimates rather than create entirely new analyses. This would fit naturally with the project's architecture because DVSA already separates ingestion, analysis, indexing, reasoning, and orchestration into independent subsystems.

Among these, the proposed motion-compensated change-mask architecture holds the most promise. DVSA already recognizes that drone footage differs fundamentally from fixed-camera footage because camera motion causes almost every pixel to change. The current solution uses geometry and homographies to align frames before reasoning about change. PhysicsNeMo could learn the underlying dynamics that explain those observations. Instead of deciding whether pixels changed, it could estimate which physical entities changed state. Patch-pruning would become state-change pruning. Tokens would be preserved because a truck accelerated, a person entered a region, or an object changed trajectory, not merely because pixel values differed. That is a significant conceptual advancement beyond conventional video sampling.

PhysicsNeMo also complements DVSA's reasoning architecture. The platform already supports model selection, reasoning adapters, Azure Foundry integration, semantic aggregation, multi-agent missions, and MCP access. PhysicsNeMo could serve as a new reasoning backend specialized for physical systems. Rather than asking a language model to infer cause from observations, DVSA agents could query a physics-informed state model. A mission planner could ask why traffic backed up, why a vessel changed course, why equipment stopped moving, or what conditions are likely to produce future failures. The explanation would emerge from inferred system dynamics instead of linguistic pattern matching.

Longer term, PhysicsNeMo could become the foundation for an Intrinsic-AI version of DVSA. The current platform already possesses most of the required infrastructure: multimodal observations, temporal video sequences, reasoning models, observability events, agent orchestration, and cloud-scale indexing. What it lacks is a persistent world model. PhysicsNeMo offers a pathway toward that capability. Rather than storing detections, embeddings, and commentary alone, DVSA could maintain latent representations of objects, environments, flows, constraints, and causal interactions. Video would become evidence used to update the world model. Analytics would become estimation. Reasoning would become simulation. Retrieval would become querying the state of the modeled world. This direction aligns remarkably well with the stated evolution of DVSA from a video-analysis service into an extensible sensing, reasoning, and agentic intelligence platform.



#sample 

The example below illustrates a simplified workflow:

1. Extract objects from drone frames using DVSA detectors.

2. Convert detections into a spatial state tensor.

3. Learn urban dynamics.

4. Predict the next state of the scene.

5. Send predictions to DVSA reasoning and anomaly agents.

The scenario assumes nadir drone imagery over a city intersection. Vehicles occupy cells in a grid. PhysicsNeMo learns how traffic density evolves through time.

"""

Illustrative PhysicsNeMo + DVSA integration.


Goal:

Learn urban traffic dynamics from nadir drone observations and

predict future scene states.


This is an architectural example. API names may need adjustment

to match the PhysicsNeMo version you install.

"""


import numpy as np

import torch


# PhysicsNeMo imports

from physicsnemo.models.fno import FNO


DEVICE = "cuda" if torch.cuda.is_available() else "cpu"



# -----------------------------------------------------------

# STEP 1: Convert DVSA detections into a spatial state tensor

# -----------------------------------------------------------


GRID_H = 128

GRID_W = 128



def detections_to_state(detections):

    """

    detections:

    [

        {

            "label": "vehicle",

            "bbox": [x, y, w, h],

            "score": 0.92

        }

    ]


    Returns:

        occupancy grid

    """


    state = np.zeros((GRID_H, GRID_W), dtype=np.float32)


    for det in detections:


        if det["label"] != "vehicle":

            continue


        x, y, w, h = det["bbox"]


        cx = int((x + w / 2) * GRID_W)

        cy = int((y + h / 2) * GRID_H)


        cx = np.clip(cx, 0, GRID_W - 1)

        cy = np.clip(cy, 0, GRID_H - 1)


        state[cy, cx] += 1.0


    return state



# -----------------------------------------------------------

# STEP 2: Physics-informed world model

# -----------------------------------------------------------


model = FNO(

    in_channels=1,

    out_channels=1,

    latent_channels=64,

    num_fno_layers=4,

).to(DEVICE)



# -----------------------------------------------------------

# STEP 3: Historical drone observations

# -----------------------------------------------------------


sequence = []


for frame_id in range(20):


    detections = [

        {

            "label": "vehicle",

            "bbox": [

                np.random.rand() * 0.8,

                np.random.rand() * 0.8,

                0.05,

                0.05,

            ],

            "score": 0.95,

        }

        for _ in range(50)

    ]


    state = detections_to_state(detections)

    sequence.append(state)


sequence = np.stack(sequence)


input_states = (

    torch.tensor(sequence[:-1])

    .unsqueeze(1)

    .float()

    .to(DEVICE)

)


target_states = (

    torch.tensor(sequence[1:])

    .unsqueeze(1)

    .float()

    .to(DEVICE)

)


# -----------------------------------------------------------

# STEP 4: Learn state evolution

# -----------------------------------------------------------


optimizer = torch.optim.Adam(

    model.parameters(),

    lr=1e-4,

)


criterion = torch.nn.MSELoss()


for epoch in range(50):


    optimizer.zero_grad()


    prediction = model(input_states)


    loss = criterion(

        prediction,

        target_states,

    )


    loss.backward()

    optimizer.step()


    print(

        f"epoch={epoch} "

        f"loss={loss.item():.6f}"

    )



# -----------------------------------------------------------

# STEP 5: Forecast future urban state

# -----------------------------------------------------------


current_state = (

    torch.tensor(sequence[-1])

    .unsqueeze(0)

    .unsqueeze(0)

    .float()

    .to(DEVICE)

)


with torch.no_grad():


    future_state = model(current_state)


future_state = (

    future_state

    .cpu()

    .numpy()[0, 0]

)


print(

    "Predicted future traffic state:",

    future_state.shape

)



# -----------------------------------------------------------

# STEP 6: Generate DVSA anomaly events

# -----------------------------------------------------------


traffic_threshold = 5.0


anomaly_cells = np.argwhere(

    future_state > traffic_threshold

)


for row, col in anomaly_cells:


    print(

        f"Predicted congestion at "

        f"cell=({row},{col})"

    )


    # DVSA observability event

    # commentary.emit(...)

    #

    # DVSA agent task

    # planner.submit(...)

    #

    # Azure AI Search update

    # index.add(...)



Sunday, November 29, 2026

 

NVIDIA PhysicsNeMo could be in DVSA-API’s future because the project is already evolving beyond video indexing toward understanding how the physical world behaves. DVSA today ingests aerial video, extracts visual information, performs computer vision analysis, builds indexes, supports reasoning models, and exposes agentic workflows around drone observations. The next step would be physics-informed AI rather than only perception-driven AI.

PhysicsNeMo is fundamentally different from conventional neural inference systems. Instead of learning only statistical relationships, it learns physical constraints, governing equations, conservation rules, spatial dynamics, and system behavior. Similar to Intrinsic AI direction explored in earlier articles, where the objective is not merely predicting observations but discovering the latent mechanisms that generate them by seeking internal representations of causality, objects, forces, constraints, persistence, and world dynamics, PhysicsNeMo provides a practical framework for building such world models because it combines machine learning with physical laws.

For example, camera-motion-aware scene understanding is a primary use case. DVSA already reconstructs motion through homographies, trajectories, feature matching, and optical-flow analysis. A PhysicsNeMo model could learn a physical state representation of the drone, terrain, and observed objects rather than processing each frame independently. Instead of merely detecting that a vehicle moved, the system could estimate velocity, acceleration, future location, likely path, and interactions with surrounding structures. The result would be a transition from object detection toward physical state estimation. DVSA would become capable of reasoning over what is likely happening in the scene rather than simply what appears in the pixels.

A second opportunity is predictive video understanding. Today DVSA stores videos, extracts frames, indexes observations, performs retrieval, and supports chat-based questioning. A PhysicsNeMo world model could predict future scene evolution. After observing a drone survey of a parking lot, road network, harbor, construction site, or industrial facility, the system could estimate future occupancy, traffic flow, congestion, queue formation, equipment movement, or infrastructure changes. This would shift DVSA from a retrospective analytics system into a forecasting platform. The system would answer not only “What happened?” but also “What is likely to happen next?”

A third application is anomaly detection. Current anomaly detection often relies on deviations from previously observed patterns. PhysicsNeMo allows anomalies to be defined as violations of learned physical rules. For example, a vehicle moving against expected traffic flow, an aircraft behaving outside feasible flight envelopes, a vessel violating navigational constraints, or a construction process diverging from expected progression could all be identified using a learned physical model. Such anomalies are often more meaningful than purely visual differences because they represent violations of underlying system behavior rather than changes in appearance.

A fourth opportunity is geospatial digital twins. DVSA already contains Azure storage, indexing, retrieval, observability, agent frameworks, and batch-processing infrastructure. A PhysicsNeMo layer could continuously ingest aerial observations and update a latent simulation of the monitored environment. The simulation would persist across flights and across days. Instead of treating every incoming video as an isolated asset, DVSA would maintain a living model of the environment. New observations would update state estimates rather than create entirely new analyses. This would fit naturally with the project's architecture because DVSA already separates ingestion, analysis, indexing, reasoning, and orchestration into independent subsystems.

Among these, the proposed motion-compensated change-mask architecture holds the most promise. DVSA already recognizes that drone footage differs fundamentally from fixed-camera footage because camera motion causes almost every pixel to change. The current solution uses geometry and homographies to align frames before reasoning about change. PhysicsNeMo could learn the underlying dynamics that explain those observations. Instead of deciding whether pixels changed, it could estimate which physical entities changed state. Patch-pruning would become state-change pruning. Tokens would be preserved because a truck accelerated, a person entered a region, or an object changed trajectory, not merely because pixel values differed. That is a significant conceptual advancement beyond conventional video sampling.

PhysicsNeMo also complements DVSA's reasoning architecture. The platform already supports model selection, reasoning adapters, Azure Foundry integration, semantic aggregation, multi-agent missions, and MCP access. PhysicsNeMo could serve as a new reasoning backend specialized for physical systems. Rather than asking a language model to infer cause from observations, DVSA agents could query a physics-informed state model. A mission planner could ask why traffic backed up, why a vessel changed course, why equipment stopped moving, or what conditions are likely to produce future failures. The explanation would emerge from inferred system dynamics instead of linguistic pattern matching.

Longer term, PhysicsNeMo could become the foundation for an Intrinsic-AI version of DVSA. The current platform already possesses most of the required infrastructure: multimodal observations, temporal video sequences, reasoning models, observability events, agent orchestration, and cloud-scale indexing. What it lacks is a persistent world model. PhysicsNeMo offers a pathway toward that capability. Rather than storing detections, embeddings, and commentary alone, DVSA could maintain latent representations of objects, environments, flows, constraints, and causal interactions. Video would become evidence used to update the world model. Analytics would become estimation. Reasoning would become simulation. Retrieval would become querying the state of the modeled world. This direction aligns remarkably well with the stated evolution of DVSA from a video-analysis service into an extensible sensing, reasoning, and agentic intelligence platform.


#sample

The example below illustrates a simplified workflow:

  1. Extract objects from drone frames using DVSA detectors.
  2. Convert detections into a spatial state tensor.
  3. Learn urban dynamics.
  4. Predict the next state of the scene.
  5. Send predictions to DVSA reasoning and anomaly agents.

The scenario assumes nadir drone imagery over a city intersection. Vehicles occupy cells in a grid. PhysicsNeMo learns how traffic density evolves through time.

"""

Illustrative PhysicsNeMo + DVSA integration.

 

Goal:

Learn urban traffic dynamics from nadir drone observations and

predict future scene states.

 

This is an architectural example. API names may need adjustment

to match the PhysicsNeMo version you install.

"""

 

import numpy as np

import torch

 

# PhysicsNeMo imports

from physicsnemo.models.fno import FNO

 

DEVICE = "cuda" if torch.cuda.is_available() else "cpu"

 

 

# -----------------------------------------------------------

# STEP 1: Convert DVSA detections into a spatial state tensor

# -----------------------------------------------------------

 

GRID_H = 128

GRID_W = 128

 

 

def detections_to_state(detections):

    """

    detections:

    [

        {

            "label": "vehicle",

            "bbox": [x, y, w, h],

            "score": 0.92

        }

    ]

 

    Returns:

        occupancy grid

    """

 

    state = np.zeros((GRID_H, GRID_W), dtype=np.float32)

 

    for det in detections:

 

        if det["label"] != "vehicle":

            continue

 

        x, y, w, h = det["bbox"]

 

        cx = int((x + w / 2) * GRID_W)

        cy = int((y + h / 2) * GRID_H)

 

        cx = np.clip(cx, 0, GRID_W - 1)

        cy = np.clip(cy, 0, GRID_H - 1)

 

        state[cy, cx] += 1.0

 

    return state

 

 

# -----------------------------------------------------------

# STEP 2: Physics-informed world model

# -----------------------------------------------------------

 

model = FNO(

    in_channels=1,

    out_channels=1,

    latent_channels=64,

    num_fno_layers=4,

).to(DEVICE)

 

 

# -----------------------------------------------------------

# STEP 3: Historical drone observations

# -----------------------------------------------------------

 

sequence = []

 

for frame_id in range(20):

 

    detections = [

        {

            "label": "vehicle",

            "bbox": [

                np.random.rand() * 0.8,

                np.random.rand() * 0.8,

                0.05,

                0.05,

            ],

            "score": 0.95,

        }

        for _ in range(50)

    ]

 

    state = detections_to_state(detections)

    sequence.append(state)

 

sequence = np.stack(sequence)

 

input_states = (

    torch.tensor(sequence[:-1])

    .unsqueeze(1)

    .float()

    .to(DEVICE)

)

 

target_states = (

    torch.tensor(sequence[1:])

    .unsqueeze(1)

    .float()

    .to(DEVICE)

)

 

# -----------------------------------------------------------

# STEP 4: Learn state evolution

# -----------------------------------------------------------

 

optimizer = torch.optim.Adam(

    model.parameters(),

    lr=1e-4,

)

 

criterion = torch.nn.MSELoss()

 

for epoch in range(50):

 

    optimizer.zero_grad()

 

    prediction = model(input_states)

 

    loss = criterion(

        prediction,

        target_states,

    )

 

    loss.backward()

    optimizer.step()

 

    print(

        f"epoch={epoch} "

        f"loss={loss.item():.6f}"

    )

 

 

# -----------------------------------------------------------

# STEP 5: Forecast future urban state

# -----------------------------------------------------------

 

current_state = (

    torch.tensor(sequence[-1])

    .unsqueeze(0)

    .unsqueeze(0)

    .float()

    .to(DEVICE)

)

 

with torch.no_grad():

 

    future_state = model(current_state)

 

future_state = (

    future_state

    .cpu()

    .numpy()[0, 0]

)

 

print(

    "Predicted future traffic state:",

    future_state.shape

)

 

 

# -----------------------------------------------------------

# STEP 6: Generate DVSA anomaly events

# -----------------------------------------------------------

 

traffic_threshold = 5.0

 

anomaly_cells = np.argwhere(

    future_state > traffic_threshold

)

 

for row, col in anomaly_cells:

 

    print(

        f"Predicted congestion at "

        f"cell=({row},{col})"

    )

 

    # DVSA observability event

    # commentary.emit(...)

    #

    # DVSA agent task

    # planner.submit(...)

    #

    # Azure AI Search update

    # index.add(...)