Skip to main content

nnodely

PyPI Documentation codecov Python 3.11 - 3.13 Keras 3: TensorFlow, PyTorch, JAX License: MIT

Neural Network Framework for Modelling, Control, and Estimation of Physical Systems

Modeling, control, and estimation of physical systems are central to many engineering disciplines. While data-driven methods like neural networks offer powerful tools, they often struggle to incorporate prior domain knowledge, limiting their interpretability, generalizability, and safety.

We present nnodely (where "nn" can be read as "m," forming Modely): a framework that facilitates the creation and deployment of Model-Structured Neural Networks (MS-NNs). MS-NNs combine the learning capabilities of neural networks with structural priors grounded in physics, control, and estimation theory, enabling:

  • Encoding Physics at the architectural level
  • Reduced training data requirements
  • Generalization to unseen scenarios
  • Real time deployment in real-world applications
  • Multi-backend TensorFlow, PyTorch or JAX.

In short:

nnodely is not a replacement for general-purpose deep learning frameworks: it is a structured layer on top of them, purpose-built for physical systems.

📖 Documentation • 🚀 Applications • 🤖 Guide for AI assistants

Install

pip install "nnodely[torch]"        # or [tensorflow], or [jax]

Each backend comes with what nnodely needs to export the model to ONNX.

pip install nnodely alone installs no backend: name one, as above.

Choose the backend with KERAS_BACKEND, before importing nnodely: it is read once, at the import, and kept until the process ends. Unset, nnodely runs on TensorFlow, the default of Keras, or on the backend installed when only one is. nnodely.get_backend() tells which.

export KERAS_BACKEND=torch      # or, at the top of a script: os.environ["KERAS_BACKEND"] = "torch"

nnodely computes on the CPU, where its small models run fastest. Set NNODELY_DEVICE=gpu, also before the import, for the accelerator of the backend: CUDA, or the Apple GPU with PyTorch. nnodely.get_device() tells which device it uses.

Hello, world

To check that nnodely is installed, teach it the Fibonacci rule: two parameters, x[t+1] = A x[t−1] + B x[t], trained until the next value is the sum of the last two, then run closed loop to generate the series.

import keras
import numpy as np
from nnodely import *

set_seed(42)

x = Input("x", tw=2)  # a window of two samples: [x[t-1], x[t]]
prev, cur = TimeSelect(0)(x), TimeSelect(1)(x)
# The next value, fed back into the window of x when the model runs closed loop
out = Output("out", x.feedback(Parameter("A") * prev + Parameter("B") * cur))

model = Modely("Fibonacci", inputs=[x], outputs=[out])
model.minimize("target", out, prev + cur)  # the next value is the sum of the last two
model.build()

data = DataLoader(model, source={"x": np.random.uniform(-1.0, 1.0, 200)})
model.train(data, epochs=50, batch_size=32, lr=0.05)  # learns A = B = 1

# Run it closed loop: each step feeds its value back into the window of x
generator = model.loop().build()
steps = np.zeros((1, 10, 2, 1))  # 10 steps of x: (batch, steps, tw, dim)
steps[:, 0] = [[0.0], [1.0]]  # x starts from [0, 1]: only its first step is read
result = generator({"x": steps})
print(keras.ops.convert_to_numpy(result["out"]).ravel())  # 1, 2, 3, 5, 8, ..., 89

generator.save("fibonacci_model")  # save the nnodely model

What's in the box

Blocks
Signals Input with a sequence and a sample window (tw), fed back with its next value (feedback), Output, Parameter, Constant, arithmetic on streams
Structured layers Fir [1], Linear, LocalModel [1] [3] [4] [5], Fuzzify [2], EquationLearner [6], Interpolation, BatchNorm
Calculus Gradient w.r.t. inputs, and DerivativeStep over a window and Derivative step by step w.r.t. time, for physics-informed [7] and Sobolev [8] training · IntegrateStep over a window, and Integrate step by step · Ode (Euler, midpoint, Heun, RK4)
Recurrence model.loop() for models declared one step at a time, their states fed back in one rollout, with Buffer for the window of a signal computed step by step · Loop for rollouts over whole trajectories
Data DataLoader from dicts, DataFrames or CSV folders, multiple simulations, sequences, masks
Workflow train with any Keras optimizer and loss · validate with system-identification metrics and plots · model composition · save/load, Keras and ONNX export, interactive HTML graphs

Every block has a reference page with runnable examples in the API Reference; the User Guide explains each step of the workflow, and the Tutorials teach them as Jupyter notebooks.

Structure of the repository
nnodely/
├── src/nnodely/
│   ├── core/       # Modely, DataLoader, streams, graph, validation
│   ├── layers/     # every block of the table above
│   └── utils/      # printers, plots, seeding
├── docs/           # documentation, built on Read the Docs
├── tests/          # unit and integration tests, run on all three backends
├── imgs/           # images used in the README and the documentation
└── NNODELY_AI_GUIDE.md  # reference for AI coding assistants

Writing nnodely code with an AI assistant

The repository ships NNODELY_AI_GUIDE.md, a reference written for LLMs and coding agents rather than for people. It is dense on purpose and covers what an assistant needs to produce working code on the first attempt:

  • the hard rules of the library: lifecycle order, how objectives and targets work, naming and weight sharing.
  • a table that maps physical concepts and equations to nnodely blocks;
  • the shape convention (batch, *seq, tw, *dim) and how windows and sequences are aligned by the DataLoader;
  • exact signatures of every block, of Modely and of DataLoader;
  • when to use model.loop(), Loop or Ode, and how to align their training data;
  • which models can be saved or exported to Keras and ONNX, on which backend;
  • common error messages with their fix, runnable recipes, and a checklist to review generated code.

To use it, give the assistant the guide together with a description of the system you want to model:

<contents of NNODELY_AI_GUIDE.md>

Using nnodely, write a model of a DC motor: the angular velocity w follows
J dw/dt = K i - b w, with J, K and b unknown. I have CSV files with columns
time, current, omega sampled at 1 kHz. Identify J, K and b.

Agents that can read URLs can fetch the raw file directly from https://raw.githubusercontent.com/tonegas/nnodely/main/NNODELY_AI_GUIDE.md. Every behavior the guide marks as verified was checked against the code, so keep it in sync when the API changes.

Coming from nnodely 1.x

nnodely 2.0 is a rewrite on Keras 3: the model is a Modely built from its inputs and outputs, trained on a DataLoader, and runs on TensorFlow, PyTorch or JAX. The CHANGELOG maps every 1.x call to its 2.0 counterpart. Models saved with 1.x cannot be loaded by 2.0; to keep using them, pin pip install "nnodely<2".

Contributing

Contributions and collaborations are welcome: open an issue for questions and ideas, or a pull request for a new feature or a fix. See CONTRIBUTING.md to set up the development environment.

License

nnodely is released under the MIT License.

References

[1] Mauro Da Lio, Daniele Bortoluzzi, Gastone Pietro Rosati Papini. (2019). Modelling longitudinal vehicle dynamics with neural networks. Vehicle System Dynamics. https://doi.org/10.1080/00423114.2019.1638947 (see the [code])

[2] Alice Plebe, Mauro Da Lio, Daniele Bortoluzzi. (2019). On Reliable Neural Network Sensorimotor Control in Autonomous Vehicles. IEEE Transaction on Intelligent Transportation System. https://doi.org/10.1109/TITS.2019.2896375

[3] Mauro Da Lio, Riccardo Donà, Gastone Pietro Rosati Papini, Francesco Biral, Henrik Svensson. (2020). A Mental Simulation Approach for Learning Neural-Network Predictive Control (in Self-Driving Cars). IEEE Access. https://doi.org/10.1109/ACCESS.2020.3032780 (see the [code])

[4] Edoardo Pagot, Mattia Piccinini, Enrico Bertolazzi, Francesco Biral. (2023). Fast Planning and Tracking of Complex Autonomous Parking Maneuvers With Optimal Control and Pseudo-Neural Networks. IEEE Access. https://doi.org/10.1109/ACCESS.2023.3330431 (see the [code])

[5] Mattia Piccinini, Sebastiano Taddei, Matteo Larcher, Mattia Piazza, Francesco Biral. (2023). A Physics-Driven Artificial Agent for Online Time-Optimal Vehicle Motion Planning and Control. IEEE Access. https://doi.org/10.1109/ACCESS.2023.3274836 (look [code basic] and [code extended])

[6] Hector Perez-Villeda, Justus Piater, Matteo Saveriano. (2023). Learning and extrapolation of robotic skills using task-parameterized equation learner networks. Robotics and Autonomous Systems. https://doi.org/10.1016/j.robot.2022.104309 (see the [code])

[7] M. Raissi, P. Perdikaris, G.E. Karniadakis. (2019). Physics-informed neural networks: A deep learning framework for solving forward and inverse problems involving nonlinear partial differential equations Journal of Computational Physics. https://doi.org/10.1016/j.jcp.2018.10.045 (see the [example Burger's equation])

[8] Wojciech Marian Czarnecki, Simon Osindero, Max Jaderberg, Grzegorz Świrszcz, Razvan Pascanu. (2017). Sobolev Training for Neural Networks. arXiv. https://doi.org/10.48550/arXiv.1706.04859 (see the [code])

[9] Mattia Piccinini, Matteo Zumerle, Johannes Betz, Gastone Pietro Rosati Papini. (2025). A Road Friction-Aware Anti-Lock Braking System Based on Model-Structured Neural Networks. IEEE Open Journal of Intelligent Transportation Systems. https://doi.org/10.1109/OJITS.2025.3563347 (look at the [code])

[10] Mauro Da Lio, Mattia Piccinini, Francesco Biral. (2023). Robust and Sample-Efficient Estimation of Vehicle Lateral Velocity Using Neural Networks With Explainable Structure Informed by Kinematic Principles. IEEE Transactions on Intelligent Transportation Systems. https://doi.org/10.1109/TITS.2023.3303776

(back to top)

Metadata

Release files for nnodely 2.0.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for nnodely 2.0.0
File Size Uploaded Provenance Actions
nnodely-2.0.0.tar.gz 322.3 kB Without provenance Details for nnodely-2.0.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for nnodely 2.0.0
File Interpreter ABI Platform Actions
nnodely-2.0.0-py3-none-any.whl Python 3 none any Details for nnodely-2.0.0-py3-none-any.whl

Total release size: 668.6 kB

Release files / nnodely-2.0.0.tar.gz

Download URL nnodely-2.0.0.tar.gz
Size 322.3 kB
Tags Source
SHA-256 checksum
How to use checksums
81c3d9a7219859bf87a471074881900167f264f35b052395747ebaa7e7a82732
BLAKE2b-256 checksum
How to use checksums
189ad450d721e98791769c264718948b5e311983ccfecd68bc39f107ca57f052
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / nnodely-2.0.0-py3-none-any.whl

Download URL nnodely-2.0.0-py3-none-any.whl
Size 346.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
d0734b3b1c0ed405e41b402ccec84aae933c9d4624f9617032be49e517a5ee97
BLAKE2b-256 checksum
How to use checksums
f6ff41f311e2457a2f4c2948b1cc31279415dc7fa84147829c28ad540e5b73c6
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via uv/0.13.9 {"installer":{"name":"uv","version":"0.13.9","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for nnodely 2.0.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

2.0.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page