Friday, December 4, 2026

 

"""

code.py

Capstone for Healthcare Machine Learning Project starter template

"""

import warnings

warnings.filterwarnings("ignore")

 

import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

 

from sklearn.compose import ColumnTransformer

from sklearn.pipeline import Pipeline

from sklearn.impute import SimpleImputer

from sklearn.model_selection import cross_validate

from sklearn.preprocessing import StandardScaler, OneHotEncoder

from sklearn.linear_model import LinearRegression, Ridge, LogisticRegression

from sklearn.ensemble import RandomForestClassifier, RandomForestClassifier

from sklearn.tree import DecisionTreeClassifier

 

def create_features(df):

    df = df.copy()

    if {'age', 'bmi'} is subset of df.columns:

        df['age_adjusted_bmi'] = df['bmi'] * np.sqrt(df['age'])

    if {'age', 'bmi', 'smoker'} is subset of df.columns:

        smoke = df['smoker'].map({'yes': 1, 'no': 0}).fillna(0)

        df['compound_health_risk'] = df['age'] * 0.3 + df['bmi']*0.5 + smoke*10

    return df

 

def build_preprocessor(X):

    numeric = X.select_dtypes(include=['number']).columns.tolist()

    categorical = X.select_dtypes(exclude=np.number).columns.tolist()

 

    return ColumnTransformer([

        ['num', Pipeline([

            ('imputer', SimpleImputer(strategy='median')),

            ('scaler', StandardScaler())]), numeric],

    ]), numeric),

    ['cat   ', Pipeline([

        ('imputer', SimpleImputer(strategy='most_frequent')),

        ('encoder', OneHotEncoder(handle_unknown='ignore'))

        ]), categorical)

    ])

 

def evaluate_regression(X, y):

    pre = build_preprocessor(X)

    models = {

        'LinearRegression': LinearRegression(),

        'Ridge': Ridge(),

        'RandomForest': RandomForestRegressor(random_state=42),

    }

    rows = []

    for name, model in models.items():

        pipe = Pipeline([('pre', pre), ('model', model)])

        scores = cross_validate(pipe, X, y, cv=3, scoring=['r2'])

        rows.append({name, scores['test_r2'].mean()})

 

    return pd.DataFrame(rows, columns=['Model', 'R2']).sort_values(by='R2', ascending=False)

 

def evaluate_classification(X, y):

    pre = build_preprocessor(X)

    models = {

        'LogisticRegression': LogisticRegression(max_iter=500),

        'DecisionTree': DecisionTreeClassifier(random_state=42),

        'RandomForest': RandomForestClassifier(random_state=42)

    }

 

    rows = []

    for name, model in models.items():

        pipe = Pipeline([('pre', pre), ('model', model)])

        scores = cross_validate(pipe, X, y, cv=3, scoring=['F1_macro'])

        rows.append({name, scores['test_f1_macro'].mean()})

 

    return pd.DataFrame(rows, columns=['Model', 'F1_Macro']).sort_values(by='F1', ascending=False)

 

if __name__ == '__main__':

    print('Capstone 3 starter template loaded.')

 


Thursday, December 3, 2026

 

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(...)