Giter Club home page Giter Club logo

pnnl / neuromancer Goto Github PK

View Code? Open in Web Editor NEW
765.0 26.0 100.0 371.89 MB

Pytorch-based framework for solving parametric constrained optimization problems, physics-informed system identification, and parametric model predictive control.

Home Page: https://pnnl.github.io/neuromancer/

License: Other

Python 76.72% C++ 8.37% Cuda 14.91%
constrained-optimization control-systems deep-learning differentiable-programming dynamical-systems pytorch differentiable-optimization nonlinear-dynamics nonlinear-optimization differentiable-control

neuromancer's Introduction

NeuroMANCER v1.5.0

Neural Modules with Adaptive Nonlinear Constraints and Efficient Regularizations (NeuroMANCER) is an open-source differentiable programming (DP) library for solving parametric constrained optimization problems, physics-informed system identification, and parametric model-based optimal control. NeuroMANCER is written in PyTorch and allows for systematic integration of machine learning with scientific computing for creating end-to-end differentiable models and algorithms embedded with prior knowledge and physics.

⭐ Now available on PyPi! ⭐

Static Badge PyPI - Version

New in v1.5.0

Lightning Now supports integration with PyTorch Lightning (https://lightning.ai/docs/pytorch/stable/), bringing:

  • User workflow simplifications: zero boilerplate code and increased modularity
  • Ability for user to define custom training logic easily
  • Easy support for distributed GPU training
  • Weights and Biases hyperparameter tuning

Please refer to the Lightning folder and its README.

New Colab Examples:

Various domain examples, such as system identification of building thermal dynamics, in NeuroMANCER

PyTorch lightning integration Examples

Features and Examples

Extensive set of tutorials can be found in the examples folder. Interactive notebook versions of examples are available on Google Colab! Test out NeuroMANCER functionality before cloning the repository and setting up an environment.

Intro to NeuroMANCER

  • Open In Colab Part 1: Linear regression in PyTorch vs NeuroMANCER.

  • Open In Colab Part 2: NeuroMANCER syntax tutorial: variables, constraints, and objectives.

  • Open In Colab Part 3: NeuroMANCER syntax tutorial: modules, Node, and System class.

Parametric Programming

  • Open In Colab Part 1: Learning to solve a constrained optimization problem.

  • Open In Colab Part 2: Learning to solve a quadratically-constrained optimization problem.

  • Open In Colab Part 3: Learning to solve a set of 2D constrained optimization problems.

  • Open In Colab Part 4: Learning to solve a constrained optimization problem with the projected gradient.

  • Open In Colab Part 5: Using Cvxpylayers for differentiable projection onto the polytopic feasible set.

Ordinary Differential Equations (ODEs)

  • Open In Colab Part 1: Neural Ordinary Differential Equations (NODEs)
  • Open In Colab Part 2: Parameter estimation of ODE system
  • Open In Colab Part 3: Universal Differential Equations (UDEs)
  • Open In Colab Part 4: NODEs with exogenous inputs
  • Open In Colab Part 5: Neural State Space Models (NSSMs) with exogenous inputs
  • Open In Colab Part 6: Data-driven modeling of resistance-capacitance (RC) network ODEs
  • Open In Colab Part 7: Deep Koopman operator
  • Open In Colab Part 8: control-oriented Deep Koopman operator

Physics-Informed Neural Networks (PINNs) for Partial Differential Equations (PDEs)

  • Open In Colab Part 1: Diffusion Equation
  • Open In Colab Part 2: Burgers' Equation
  • Open In Colab Part 3: Burgers' Equation w/ Parameter Estimation (Inverse Problem)

Control

  • Open In Colab Part 1: Learning to stabilize a linear dynamical system.
  • Open In Colab Part 2: Learning to stabilize a nonlinear differential equation.
  • Open In Colab Part 3: Learning to control a nonlinear differential equation.
  • Open In Colab Part 4: Learning neural ODE model and control policy for an unknown dynamical system.
  • Open In Colab Part 5: Learning neural Lyapunov function for a nonlinear dynamical system.

Domain Examples

  • Open In Colab Part 1: Learning to Control Indoor Air Temperature in Buildings.
  • Open In Colab Part 2: Learning to Control an Pumped-Hydroelectricity Energy Storage System.
  • Open In Colab Part 3: Learning Building Thermal Dynamics using Neural ODEs.
  • Open In Colab Part 4: Data-driven modeling of a Resistance-Capacitance network with Neural ODEs.
  • Open In Colab Part 5: Learning Swing Equation Dynamics using Neural ODEs.
  • Open In Colab Part 6: Learning Building Thermal Dynamics using Neural State Space Models.

Lightning Integration Examples

  • Open In Colab Part 1: Lightning Integration Basics.
  • Open In Colab Part 2: Lightning Advanced Features and Automatic GPU Support.
  • Open In Colab Part 3: Hyperparameter Tuning With Lightning & WandB
  • Open In Colab Part 4: Defining Custom Training Logic via Lightning Modularized Code.

Documentation

The documentation for the library can be found online. There is also an introduction video covering core features of the library.

# Neuromancer syntax example for constrained optimization
import neuromancer as nm
import torch 

# define neural architecture 
func = nm.modules.blocks.MLP(insize=1, outsize=2, 
                             linear_map=nm.slim.maps['linear'], 
                             nonlin=torch.nn.ReLU, hsizes=[80] * 4)
# wrap neural net into symbolic representation via the Node class: map(p) -> x
map = nm.system.Node(func, ['p'], ['x'], name='map')
    
# define decision variables
x = nm.constraint.variable("x")[:, [0]]
y = nm.constraint.variable("x")[:, [1]]
# problem parameters sampled in the dataset
p = nm.constraint.variable('p')

# define objective function
f = (1-x)**2 + (y-x**2)**2
obj = f.minimize(weight=1.0)

# define constraints
con_1 = 100.*(x >= y)
con_2 = 100.*(x**2+y**2 <= p**2)

# create penalty method-based loss function
loss = nm.loss.PenaltyLoss(objectives=[obj], constraints=[con_1, con_2])
# construct differentiable constrained optimization problem
problem = nm.problem.Problem(nodes=[map], loss=loss)

UML diagram UML diagram of NeuroMANCER classes.

Installation

PIP Install (recommended)

Consider using a dedicated virtual environment (conda or otherwise) with Python 3.9+ installed.

pip install neuromancer

Example usage:

import torch
from neuromancer.system import Node

fun_1 = lambda x1, x2: 2.*x1 - x2**2
node_3 = Node(fun_1, ['y1', 'y2'], ['y3'], name='quadratic')
# evaluate forward pass of the node with dictionary input dataset
print(node_3({'y1': torch.rand(2), 'y2': torch.rand(2)}))

Manual Install

First clone the neuromancer package. A dedicated virtual environment (conda or otherwise) is recommended.

Note: If you have a previous neuromancer env it would be best at this point to create a new environment given the following instructions.

git clone -b master https://github.com/pnnl/neuromancer.git --single-branch

Create and activate virtual environment

conda create -n neuromancer python=3.10.4
conda activate neuromancer

Install neuromancer and all dependencies.

From top level directory of cloned neuromancer run:

pip install -e.[docs,tests,examples]

OR, for zsh users:

pip install -e.'[docs,tests,examples]'

See the pyproject.toml file for reference.

[project.optional-dependencies]
tests = ["pytest", "hypothesis"]
examples = ["casadi", "cvxpy", "imageio", "cvxpylayers"]
docs = ["sphinx", "sphinx-rtd-theme"]

Note on pip install with examples on MacOS (Apple M1)

Before CVXPY can be installed on Apple M1, you must install cmake via Homebrew:

brew install cmake

See CVXPY installation instructions for more details.

Conda install

Conda install is recommended for GPU acceleration.

❗️Warning: linux_env.yml, windows_env.yml, and osxarm64_env.yml are out of date. Manual installation of dependencies is recommended for conda.

Create environment & install dependencies

Ubuntu
conda env create -f linux_env.yml
conda activate neuromancer
Windows
conda env create -f windows_env.yml
conda activate neuromancer
conda install -c defaults intel-openmp -f
MacOS (Apple M1)
conda env create -f osxarm64_env.yml
conda activate neuromancer
Other (manually install all dependencies)

!!! Pay attention to comments for non-Linux OS !!!

conda create -n neuromancer python=3.10.4
conda activate neuromancer
conda install pytorch pytorch-cuda=11.6 -c pytorch -c nvidia
## OR (for Mac): conda install pytorch -c pytorch
conda config --append channels conda-forge
conda install scipy numpy"<1.24.0" matplotlib scikit-learn pandas dill mlflow pydot=1.4.2 pyts numba
conda install networkx=3.0 plum-dispatch=1.7.3 
conda install -c anaconda pytest hypothesis
conda install cvxpy cvxopt casadi seaborn imageio
conda install tqdm torchdiffeq toml
conda install lightning wandb -c conda-forge
## (for Windows): conda install -c defaults intel-openmp -f

Install NeuroMANCER package

From the top level directory of cloned neuromancer (in the activated environment where the dependencies have been installed):

pip install -e . --no-deps

Test NeuroMANCER install

Run pytest on the tests folder. It should take about 2 minutes to run the tests on CPU. There will be a lot of warnings that you can safely ignore. These warnings will be cleaned up in a future release.

Community Information

We welcome contributions and feedback from the open-source community!

Contributions, Discussions, and Issues

Please read the Community Development Guidelines for further information on contributions, discussions, and Issues.

Release notes

See the Release notes documenting new features.

License

NeuroMANCER comes with BSD license. See the license for further details.

Publications

Cite as

@article{Neuromancer2023,
  title={{NeuroMANCER: Neural Modules with Adaptive Nonlinear Constraints and Efficient Regularizations}},
  author={Drgona, Jan and Tuor, Aaron and Koch, James and Shapiro, Madelyn and Vrabie, Draguna},
  Url= {https://github.com/pnnl/neuromancer}, 
  year={2023}
}

Development team

Lead developers: Jan Drgona, Aaron Tuor
Active core developers: Madelyn Shapiro, James Koch, Rahul Birmiwal
Scientific advisors: Draguna Vrabie
Notable contributors: Seth Briney, Bo Tang, Ethan King, Shrirang Abhyankar, Mia Skomski, Stefan Dernbach, Zhao Chen, Christian Møldrup Legaard

Open-source contributions made by:

Made with contrib.rocks.

Acknowledgments

This research was partially supported by the Mathematics for Artificial Reasoning in Science (MARS) and Data Model Convergence (DMC) initiatives via the Laboratory Directed Research and Development (LDRD) investments at Pacific Northwest National Laboratory (PNNL), by the U.S. Department of Energy, through the Office of Advanced Scientific Computing Research's “Data-Driven Decision Control for Complex Systems (DnC2S)” project, and through the Energy Efficiency and Renewable Energy, Building Technologies Office under the “Dynamic decarbonization through autonomous physics-centric deep learning and optimization of building operations” and the “Advancing Market-Ready Building Energy Management by Cost-Effective Differentiable Predictive Control” projects. PNNL is a multi-program national laboratory operated for the U.S. Department of Energy (DOE) by Battelle Memorial Institute under Contract No. DE-AC05-76RL0-1830.

neuromancer's People

Contributors

aaron-tuor avatar aarontuor avatar brunopjacob avatar donnavakalis avatar drgona avatar ethanking-pnnl avatar j-koch avatar l2late avatar lucasbotang avatar madelynshapiro avatar nandantumu avatar raahul-singh avatar rbirmiwal avatar seth1briney avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

neuromancer's Issues

How to create DPC problem with BlockSSM model

Hi there,

I was looking at the examples in the code and wanted to find something similar to what was done in this paper where you identified the system using a Neural Block SSM and then used this model in the DPC problem.
However, none of the provided examples deal with such a configuration and only with Linear SSMs.

In particular, I wanted to know how to load the state_dict for the estimator and the dynamics model.

Thanks a lot in advance !

ted

pip install options?

Is there any way to install neuromancer outside of the conda environment? As a general rule, I tend to not use conda...I was just planning on using venv, but quickly ran into dependencies that aren't hosted on pypi. Thanks

Perron-Frobenius Theorem for Non-square Matrix Constraints

Hello:

The Perron-Frobenius theorem constrains the eigenvalues of the matrix so that its spectral radius is within a certain range. In the code, the PFLinear class does not require the weight matrix to be a square matrix, but if the non-square matrix is processed by the PF theorem, does this non-square matrix still meet the stability requirements? If so, is there any theoretical basis? In the article "Spectral Analysis and Stability of Deep Neural Dynamics", it is mentioned that the spectrum of the singular value can be used to judge. However, in the experiment, setting sigma_min and sigma_max in the PFLinear class does not make the spectrum of the singular value within this range, nor does it meet the stability requirements.

Thank you!

M1 macbook - cannot create conda environment

Summary

Unable to create conda environment:

(base)
como@Corys-MacBook-Pro-2 [08:59:30] [~/repos/neuromancer] [master]
-> % conda env create -f env.yml
Collecting package metadata (repodata.json): done
Solving environment: failed

ResolvePackageNotFound:
  - libgd==2.3.3=h695aa2c_1
  - protobuf==3.20.1=py310hd8f1fbe_0
  - graphite2==1.3.14=h295c915_1
  - cvxpy==1.2.1=py310hff52083_0
  - ...lists all packages...

Solution Attempts

  • I'm no pro, but it seems strange to me that a prefix exists in the env.yml file: prefix: /home/tuor369/anaconda3/envs/neuromancer, although, even removing that line from the yml file and running: conda env create -f env.yml --prefix .envs/ didn't work.
  • Update conda
  • It may have to do with cross-platform package version resolution, see here: https://stackoverflow.com/a/58160918 and the link to the github issue

Details

  • macOS Ventura 13.1
  • Apple M1 Pro
  • conda info
     active environment : base
    active env location : /Applications/miniconda3
            shell level : 1
       user config file : /Users/como/.condarc
 populated config files : /Users/como/.condarc
          conda version : 22.11.1
    conda-build version : not installed
         python version : 3.10.8.final.0
       virtual packages : __archspec=1=arm64
                          __osx=13.1=0
                          __unix=0=0
       base environment : /Applications/miniconda3  (writable)
      conda av data dir : /Applications/miniconda3/etc/conda
  conda av metadata url : None
           channel URLs : https://conda.anaconda.org/conda-forge/osx-arm64
                          https://conda.anaconda.org/conda-forge/noarch
                          https://repo.anaconda.com/pkgs/main/osx-arm64
                          https://repo.anaconda.com/pkgs/main/noarch
                          https://repo.anaconda.com/pkgs/r/osx-arm64
                          https://repo.anaconda.com/pkgs/r/noarch
          package cache : /Applications/miniconda3/pkgs
                          /Users/como/.conda/pkgs
       envs directories : /Applications/miniconda3/envs
                          /Users/como/.conda/envs
               platform : osx-arm64
             user-agent : conda/22.11.1 requests/2.28.1 CPython/3.10.8 Darwin/22.2.0 OSX/13.1
                UID:GID : 501:20
             netrc file : None
           offline mode : False

Update Violation Energy for Projected Gradient

In the current implementation of GradientProjection, the constraints violation energy (modules/solvers.py#L45) is calculated once. Given that the energy remains constant during the gradient descent, its gradients will also be constant. Therefore, there's no need to update solution values in an iterative manner.

However, according to the DC3 paper Sec 3.2, it is not very clear but implies the operation for each gradient step that also recalculates the violation energy based on the new solution values.

Given this implication, our approach may need revision.

Error in matrix dimension mismatch

Hi @drgona,

I'm trying to design a DPC controller. However, I'm facing a runtime error message that indicates a mismatch in matrix dimensions. I'm trying to resolve it, unfortunately with no success so far. It would be very helpful if you could take a look at it. Here is a python file: magnet_DPC_LSSM_var_ref.zip.

Error message:

Traceback (most recent call last):
  File "neuromancer/examples/control/magnetoshield_DPC_LSSM_var_ref.py", line 351, in <module>
    trajectories = cl_sim.simulate(nsim=sim_steps, data_init=data_init, data_traj=data_traj)
  File "neuromancer/neuromancer/simulator.py", line 103, in simulate
    data_step = self.step(data)
  File "neuromancer/neuromancer/simulator.py", line 111, in step
    output_dict = component.step(input_dict)
  File "neuromancer/neuromancer/simulator.py", line 56, in step
    data = self._forward_step(data)
  File "neuromancer/neuromancer/simulator.py", line 588, in _forward_step
    u = self.eval_policy(features)
  File "neuromancer/neuromancer/simulator.py", line 652, in eval_policy
    u = self.policy(xi)
  File "anaconda3/envs/neuromancer/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "neuromancer/neuromancer/blocks.py", line 133, in forward
    x = nlin(lin(x))
  File "anaconda3/envs/neuromancer/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "slim/slim/linear.py", line 115, in forward
    return self.linear(x)
  File "anaconda3/envs/neuromancer/lib/python3.10/site-packages/torch/nn/modules/module.py", line 1130, in _call_impl
    return forward_call(*input, **kwargs)
  File "anaconda3/envs/neuromancer/lib/python3.10/site-packages/torch/nn/modules/linear.py", line 114, in forward
    return F.linear(input, self.weight, self.bias)
RuntimeError: mat1 and mat2 shapes cannot be multiplied (1x4 and 13x20)

get_q in BuildingEnvelope Disconnects Gradients

When I pass tensors with gradients into the forward function of sys (an object of class BuildingEnvelope), the gradients get removed at the point where get_q is called. This happens even if sys is instantiated with the kwargs backend='torch', requires_grad=True. This affects any system which uses BuildingEnvelope, as in the following setup, the gradients from loss computed with 'yn' cannot propagate back to policy (a blocks.MLP_bounds).

    policy_node = Node(policy, ['yn', 'D', 'UB', 'LB'], ['U'], name='policy')
    system_node = Node(sys, ['xn', 'U', 'Dhidden'], ['xn', 'yn'], name='system')

    cl_system = System([policy_node, system_node], nsteps=args.nsteps, name='cl_system')

The cause of this issue seems to be that BuildingEnvelope.get_q is wrapped by @cast_backend, which calls torch.tensor(return_tensor, dtype=torch.float32) on the tensor returned by get_q, which removes its gradient. If this line is removed, the gradients are able to propagate and the policy can be trained normally.

Stability Analysis of Actual Cases

Hello!
I modeled multiple datasets using the decoupled neurodynamic model presented in the paper 'Physics-constrained Deep Learning of Multi-zone Building Thermal Dynamics'. After analyzing the eigenvalues of fx, I found that in my case all models are stable, that is, the spectrum of eigenvalues is less than 1. In this case, do the stability constraints proposed in the paper 'Spectral Analysis and Stability of Deep Neural Dynamics' make sense?

Terminology Issue with Saving Models in trainer.py

When trainer.py calls self.logger.log_artifacts, "best_model_state_dict.pth" is a deepcopy of the state dict at the time of the model's best dev performance, but "best_model.pth" is the pickled version of self.model at the end of training, not at the best dev loss. This could be confusing to new users of the library.

[Test Failure] test_ode.py::test_random_network

Description:

./tests/test_ode.py::test_random_network Failed: [undefined]TypeError: GeneralNetworkedODE.ode_equations() missing 1 required positional argument: 'u'

Full Testing Log

TestFailureMessage (click to expand)

./tests/test_ode.py::test_random_network Failed: [undefined]TypeError: GeneralNetworkedODE.ode_equations() missing 1 required positional argument: 'u'
Falsifying example: test_random_network(
    nAgents=1,
    nCouplings=0,
    nu=0,
    batchsize=1,
    bias='additive',
    system=neuromancer.dynamics.ode.GeneralNetworkedODE,
)
@given(st.integers(1, 100),
>          st.integers(0, 1000),
           st.integers(0, 100),
           st.integers(1, 500),
           st.sampled_from(bias),
           st.sampled_from(ode_networked_systems))

tests/test_ode.py:52: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 
tests/test_ode.py:80: in test_random_network
    y = ode(x)
.conda/lib/python3.10/site-packages/torch/nn/modules/module.py:1501: in _call_impl
    return forward_call(*args, **kwargs)
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ 

self = GeneralNetworkedODE(
  (agents): ModuleList(
    (0): SourceSink()
  )
  (couplings): ModuleList()
)
x = tensor([[0.3018]]), args = ()

    def forward(self, x, *args):
        assert len(x.shape) == 2
>       return self.ode_equations(x, *args)
E       TypeError: GeneralNetworkedODE.ode_equations() missing 1 required positional argument: 'u'
E       Falsifying example: test_random_network(
E           nAgents=1,
E           nCouplings=0,
E           nu=0,
E           batchsize=1,
E           bias='additive',
E           system=neuromancer.dynamics.ode.GeneralNetworkedODE,
E       )

src/neuromancer/dynamics/ode.py:24: TypeError

Error in system_id rc_net.ipynb example case.

Hello,
I tried running the following notebook
examples/system_identification/rc_net.ipynb
and encountered following error. Tried few thing to overcome the error but was not able to fix it.
Looking forward for any inputs to resolving the issue.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[24], line 1
----> 1 best_model = trainer.train()

File [~/Library/CloudStorage/OneDrive-PNNL/Documents/WORK/Project_BTONeuroMancer/PACKAGE/neuromancer/src/neuromancer/trainer.py:105](https://file+.vscode-resource.vscode-cdn.net/Users/shar306/Library/CloudStorage/OneDrive-PNNL/Documents/WORK/Project_BTONeuroMancer/PACKAGE/neuromancer/examples/system_identification/~/Library/CloudStorage/OneDrive-PNNL/Documents/WORK/Project_BTONeuroMancer/PACKAGE/neuromancer/src/neuromancer/trainer.py:105), in Trainer.train(self)
    103 t_batch['epoch'] = i
    104 t_batch = move_batch_to_device(t_batch, self.device)
--> 105 output = self.model(t_batch)
    106 self.optimizer.zero_grad()
    107 output[self.train_metric].backward()

File [/usr/local/Caskroom/miniconda/base/envs/neuromancer/lib/python3.10/site-packages/torch/nn/modules/module.py:1501](https://file+.vscode-resource.vscode-cdn.net/usr/local/Caskroom/miniconda/base/envs/neuromancer/lib/python3.10/site-packages/torch/nn/modules/module.py:1501), in Module._call_impl(self, *args, **kwargs)
   1496 # If we don't have any hooks, we want to skip the rest of the logic in
   1497 # this function, and just call forward.
   1498 if not (self._backward_hooks or self._backward_pre_hooks or self._forward_hooks or self._forward_pre_hooks
   1499         or _global_backward_pre_hooks or _global_backward_hooks
   1500         or _global_forward_hooks or _global_forward_pre_hooks):
-> 1501     return forward_call(*args, **kwargs)
   1502 # Do not call functions when jit is used
   1503 full_backward_hooks, non_full_backward_hooks = [], []

File [~/Library/CloudStorage/OneDrive-PNNL/Documents/WORK/Project_BTONeuroMancer/PACKAGE/neuromancer/src/neuromancer/problem.py:68](https://file+.vscode-resource.vscode-cdn.net/Users/shar306/Library/CloudStorage/OneDrive-PNNL/Documents/WORK/Project_BTONeuroMancer/PACKAGE/neuromancer/examples/system_identification/~/Library/CloudStorage/OneDrive-PNNL/Documents/WORK/Project_BTONeuroMancer/PACKAGE/neuromancer/src/neuromancer/problem.py:68), in Problem.forward(self, data)
     67 def forward(self, data: Dict[str, torch.Tensor]) -> Dict[str, torch.Tensor]:
---> 68     output_dict = self.step(data)
...
     20 def forward(self, x, *args):
     21     assert len(x.shape) == 2
---> 22     return self.ode_equations(x, *args)

TypeError: GeneralNetworkedODE.ode_equations() takes 2 positional arguments but 3 were given

Issue with installation

Hi,

I installed the Neuromancer by creating a conda with python 3.10.4. environment and pip install using Pycharm and when running pytest on the tests, they all pass. About the error: It is related to the plot (pltCL) step of the given examples in GitHub, as a reference I took Example 3 in the control section but I received very similar errors for every example. Please find attached to this mail screenshots of the error message:

pltCL(Y=trajectories['x'].detach().reshape(nsteps + 1, nx),
ValueError: only one element tensors can be converted to Python scalars

screen

Thank you very much in advance for considering this issue!

"Example Part_8_nonauto_DeepKoopman" Error

There might be some setting error in the symbolic Koopman model with control inputs
The original code is :
Koopman = Node(Koopman_control(K), ['x', 'u_latent'], ['x'], name='K')

But I think the proper one is:
Koopman = Node(Koopman_control(K), ['x_latent', 'u_latent'], ['x'], name='K')

Inconsistency naming of constraint module

Some of the example uses the constraint module like

import neuromancer as nm

# declare constraints 
x = nm.constraints.variable("x")[:, [0]]

Unless anaconda does something magical, I suspect this should be nm.constraint to match the name of the file.

PSL coupled_systems backend error

Hi,
The PSL coupled_systems.py is not intergrated with the neuromancer.psl . On an attempts on fixing the issue by modifying the psl __init__.py and adding cast_backend decorators to the methods of the coupled system following error is observed.

Traceback (most recent call last):
  File "/neuromancer/src/neuromancer/psl/coupled_systems.py", line 449, in <module>
    network = RC_Network.make_5_room(nsim=100)
  File "/neuromancer/src/neuromancer/psl/coupled_systems.py", line 275, in make_5_room
    return RC_Network(nsim=nsim, nx=5, adj=adj)
  File "/neuromancer/src/neuromancer/psl/coupled_systems.py", line 177, in __init__
    super().__init__(nsim, ninit, ts, adj, nx, seed)
  File "/neuromancer/src/neuromancer/psl/coupled_systems.py", line 128, in __init__
    super().__init__(nsim, ninit, ts, seed)
  File "/neuromancer/src/neuromancer/psl/base.py", line 118, in __init__
    self.B = Backend(backend)
  File "/neuromancer/src/neuromancer/psl/base.py", line 63, in __init__
    for k, v in Backend.backends[backend].items():
KeyError: 0

Cannot create Conda environment

I am using W10 with GTX 1050, installed Cuda 11.6.2 from https://developer.nvidia.com/cuda-11-6-2-download-archive
when I try to create an environment on conda with the command conda env create -f windows_env.yml just as instructed:
I face the following error:

Collecting package metadata (repodata.json): done
Solving environment: done

Downloading and Extracting Packages

Preparing transaction: done
Verifying transaction: done
Executing transaction: done
Installing pip dependencies: \ Ran pip subprocess with arguments:
['C:\\Users\\abdul\\anaconda3\\envs\\neuromancer\\python.exe', '-m', 'pip', 'install', '-U', '-r', 'C:\\Users\\abdul\\Development\\GithubPullLibraries\\neuromancer\\condaenv.72d89e9z.requirements.txt', '--exists-action=b']
Pip subprocess output:
Collecting torch-scatter==2.0.9
  Using cached torch_scatter-2.0.9.tar.gz (21 kB)
  Preparing metadata (setup.py): started
  Preparing metadata (setup.py): finished with status 'error'

Pip subprocess error:
  error: subprocess-exited-with-error

  × python setup.py egg_info did not run successfully.
  │ exit code: 1
  ╰─> [8 lines of output]
      Traceback (most recent call last):
        File "<string>", line 2, in <module>
        File "<pip-setuptools-caller>", line 34, in <module>
        File "C:\Users\abdul\AppData\Local\Temp\pip-install-qedr1lz1\torch-scatter_67744a4e9c9445c3827c6dce08510523\setup.py", line 8, in <module>
          import torch
        File "C:\Users\abdul\anaconda3\envs\neuromancer\lib\site-packages\torch\__init__.py", line 128, in <module>
          raise err
      OSError: [WinError 182] The operating system cannot run %1. Error loading "C:\Users\abdul\anaconda3\envs\neuromancer\lib\site-packages\torch\lib\shm.dll" or one of its dependencies.
      [end of output]

  note: This error originates from a subprocess, and is likely not a problem with pip.
error: metadata-generation-failed

× Encountered error while generating package metadata.
╰─> See above for output.

note: This is an issue with the package mentioned above, not pip.
hint: See above for details.

failed

CondaEnvException: Pip failed

Any help ? Thanks

.show() for Problem class

.show() method for instantiated Problem class will fail for nodes with an empty string as name.
TODO: fix this by adding default names to problem nodes

Submodule Import

Description:

Describe the bug

Python can't find an attribute or method directly in the module 'neuromancer' and 'neuromancer.modules'. The import statements need to be adjusted in the subpackages.

To Reproduce

Steps to reproduce the behavior:

Example 1

import neuromancer as nm
nm.modules.blocks
Error Message:

AttributeError: module 'neuromancer' has no attribute 'modules'

Example 2

from neuromancer import modules
modules.blocks.MLP
Error Message:

AttributeError: module 'neuromancer.modules' has no attribute 'blocks'

colab import failing

@madelynshapiro @aarontuor

After recent PR merge there is an error in importing neuromancer package in the colab notebooks.

`---------------------------------------------------------------------------
PydanticUserError Traceback (most recent call last)
in <cell line: 2>()
1 import torch
----> 2 from neuromancer.system import Node, System
3 from neuromancer.modules import blocks
4 from neuromancer.dataset import DictDataset
5 from neuromancer.constraint import variable

9 frames
/usr/local/lib/python3.10/dist-packages/pydantic/deprecated/class_validators.py in root_validator(pre, skip_on_failure, allow_reuse, *__args)
226 mode: Literal['before', 'after'] = 'before' if pre is True else 'after'
227 if pre is False and skip_on_failure is not True:
--> 228 raise PydanticUserError(
229 'If you use @root_validator with pre=False (the default) you MUST specify skip_on_failure=True.'
230 ' Note that @root_validator is deprecated and should be replaced with @model_validator.',

PydanticUserError: If you use @root_validator with pre=False (the default) you MUST specify skip_on_failure=True. Note that @root_validator is deprecated and should be replaced with @model_validator.

For further information visit https://errors.pydantic.dev/2.2/u/root-validator-pre-skip`

Suggesting to add the source code of the paper to the examples

Hi! developer:
I suggest that the source code of the paper using the framework can be added to the examples, such as the source code of the article physics-constrained deep learning of multi-zone building thermal dynamics. It's really difficult to understand the framework from scratch.

Using Neuromancer for Moving Horizon Estimation

Hi!

I would like to ask for some help in the following matter.
I am trying to use Neuromancer for learning-based/differenciable moving horizon estimation in a similar fashion as it is used for the DMPC.
However, though the optimization problem of the MHE is quite similar to the MPC's in its formalization, there are some differences: here the current value of the optimization variable - the estimated state vector (x_k) - is compared to its value at a different time step (see equations - w_k).

mhe

And this part is what I could not really implement/work out how to implement in Neuromancer, as I did not find such an example where an optimization variable is used in such a way. (Or maybe I have missed it...)
So my question is: is it possible to implement this using Neuromancer 'out-of-the-box' (so without extending the functionality of any of the existing classes)? And if it is possible, could you give me some help/suggestions how to do it?

Thanks in advance!

A model graph plot problem.

Thanks for the great work on such a flexible model based RL framwork.
Recently, I try to change the default input settings in dynamics.py from DEFAULT_INPUT_KEYS=["x0", "Yf"] to DEFAULT_INPUT_KEYS=["x0", "Yp"] and nsteps = data[self.input_key_map['Yp']].shape[1] in the "forward" method, and run example/system_identification/two_tank_neural_ssm.py successfully. However, after plotting the model graph, I find the connection Yf from dataset to Y_pred_dynamics_eq_Yf disappears, like below. They are the inputs to calculate the mse loss.

two_tank_neural_ssm_2

Is there anyone can help to find out the problem and fix this? Thanks!

documentation

Hey,
I might be interested in using this library for my masters thesis. On the documentation webpage you guys refer to a pdf file Documentation.pdf, but it is not there. Is this a mistake, or are its contents merged into the webpages already?
Thanks in advance,
Christiaan

Define Constraints on ODE System Parameters

Hello,
Is there a way to define a constraint on the custom ode system parameter?

lets assume simple system with single input and single state

dx = a x + b u

where the a is a constant that has to be positive a > 0 and we are dealing with a system identification problem. I create my dynamics using ODESystem class.

Thanks in advance.

Forward method of Node with multiple outputs not mapping the output when MLP is the operator

Hi y'all! I noticed that when we have an instance of a Node with multiple outputs and operating with a blocks.MLP, the mapping to the output variables doesn't follow the same behavior as when the operator is a function.

I tried to illustrate the issue in the snippet below: I create a block, a function and some data. Then, I create two nodes: one to illustrate the forward pass of the block, and the other to do the same with the function. Notice the multiple outputs in the node definitions.

import torch
import torch.nn as nn
from neuromancer.modules import blocks
from neuromancer.system import Node

test_block = blocks.MLP(insize=2, outsize=3,
                  bias=True,
                  nonlin=torch.nn.Tanh,
                  hsizes=[20] * 4)

def test_fun(x1,x2):
    return x1+x2, x1-x2, x1*x2

data = {'x1': torch.rand(10, 1), 'x2': torch.rand(10, 1)}

node_1 = Node(test_fun, ['x1','x2'], ['vx','vy','p'])
print(node_1(data).keys())
print(node_1(data)["vx"].shape)

node_2 = Node(test_block, ['x1','x2'], ['vx','vy','p'])
print(node_2(data).keys())
print(node_2(data)["vx"].shape)

The result from node_2 has shape [10,3], which shouldn't be the case; it seems to me that the issue is here:

output = self.callable(*inputs)
if not isinstance(output, tuple):
output = [output]

I think an easy solution for that is to do a .split on the output tensor after the forward method is called, after checking that the result is not a tuple (since that for the tuple case, i.e., function case, things work just fine).

output = self.callable(*inputs) 
if not isinstance(output, tuple):
   output = output.split(1, dim=1)

I did some tests and I guess that way the mapping would work 😸

Thanks!

psl examples

@aarontuor @aaron-tuor @madelynshapiro

The current toml file does not include all the dependencies necessary to run psl examples in:
https://github.com/pnnl/neuromancer/tree/master/examples/psl

there are broken notebook examples:

all psl examples lack proper documentation to guide the user through the functionality of the library

There are also broken psl examples in the test folder:
https://github.com/pnnl/neuromancer/blob/master/tests/psl/coupled_sys_test.ipynb

Missing dependencies:

  • pygame-menu
  • stable_baselines3

Failing tests in: psl\test_directory.py
assert os.path.normcase(nm_path1)==os.path.normcase(nm_path2), 'installed neuromancer root directory not the same as test root directory' AssertionError: installed neuromancer root directory not the same as test root directory

I am of strong opinion not to include all these psl_gym dependencies in our base environment.
the pygame visualisation should be a separate project independent of Neuromancer for now

Can't reproduce results in branch building_ctrl

It seems that I can not be able to reproduce the paper's results with this branch?

  1. which psl/slim version that this branch depends on?
  2. it seem that Y out's max is 40 while in paper it seems that it is 32, here is the debug screen shot:

image

Can you please give some guidances to see if we can reproduce the results from paper Deep Learning Explicit Di erentiable Predictive Control Laws for Buildings?

Many thanks.

Redundant or Incorrect Import: 'from neuromancer.component import Component' in modules.solvers

Description:

Describe the bug

Go to solvers.py line 5: from neuromancer.component import Component. However, the component class or module doesn't exist within the current neuromancer package, and it is being used in solvers.py.

To Reproduce

Steps to reproduce the behavior:

# import solvers
from neuromancer.modules import solvers

Error Message:

ModuleNotFoundError: No module named 'neuromancer.component'

Issue with Objective Function Leading to Program Failure in NeuroMANCER

Issue Description:

I am experiencing an issue with NeuroMANCER when using a complex objective function, where the program fails after running for a very long period. Specifically, the problem arises when the objective function is defined as sum(cov_matrix[i, j] * x[:, i] * x[:, j] for i in range(num_vars) for j in range(num_vars)). When I use this objective function, the nm.trainer.Trainer fails to run properly, and an error occurs at problem.state_dict(). However, the forward and backward passes of the model do not seem to have any issues.

Notably, when I switch to a simpler objective function, such as sum(cov_matrix[i, 0] * x[:, i] * x[:, 0] for i in range(num_vars)), the program runs without any errors. This leads me to believe that the issue may be related to the complexity of the objective function and its computational demands.

Error Message:

/tmp/tmpoa3dt7yw: line 3:  2300 Killed python /home/botang/.pycharm_helpers/pydev/pydevconsole.py --mode=client --host=127.0.0.1 --port=36623
ERROR conda.cli.main_run:execute(49): `conda run python /home/botang/.pycharm_helpers/pydev/pydevconsole.py --mode=client --host=127.0.0.1 --port=36623` failed. (See above for error)

Code Sample to Reproduce Issue:

import numpy as np
from torch import nn
import neuromancer as nm

num_vars = 5
# expected returns
exp_returns = np.random.uniform(0.002, 0.01, num_vars)
print("Expected Returns:")
print(exp_returns)
# covariance matrix
A = np.random.rand(num_vars, num_vars)
# positive semi-definite matrix
cov_matrix = A @ A.T / 1000
print("Covariance Matrix:")
print(cov_matrix)

# parameters
p = nm.constraint.variable("p")
# variables
x = nm.constraint.variable("x")

# constraints
constrs = []
# constr: 100 units
con = 100 * (sum(x[:, i] for i in range(num_vars)) == 1)
con.name = "c_units"
constrs.append(con)
# constr: expected return
con = 100 * (sum(exp_returns[i] * x[:, i] for i in range(num_vars)) >= p[:, 0])
con.name = "c_return"
constrs.append(con)

# define neural architecture for the solution map
func = nm.modules.blocks.MLP(insize=1, outsize=num_vars, bias=True,
                             linear_map=nm.slim.maps["linear"], nonlin=nn.ReLU, hsizes=[5]*4)
# solution map from model parameters: sol_map(p) -> x
sol_map = nm.system.Node(func, ["p"], ["x"], name="smap")
# trainable components
components = [sol_map]

# objective function
f = sum(cov_matrix[i, 0] * x[:, i] * x[:, 0] for i in range(num_vars))
obj = [f.minimize(weight=1.0, name="obj")]

# merit loss function
loss = nm.loss.PenaltyLoss(obj, constrs)
# problem
problem = nm.problem.Problem(components, loss)

# no error
print(problem.state_dict())

# objective function
f = sum(cov_matrix[i, j] * x[:, i] * x[:, j] for i in range(num_vars) for j in range(num_vars))
obj = [f.minimize(weight=1.0, name="obj")]

# merit loss function
loss = nm.loss.PenaltyLoss(obj, constrs)
# problem
problem = nm.problem.Problem(components, loss)

# get error
print(problem.state_dict())

Install does not work with pyproject.toml

→ pip install -e.[docs,tests,examples]
Obtaining file:///TrafficModeling/neuromancer
  Installing build dependencies ... done
  Checking if build backend supports build_editable ... done
ERROR: Project file:///TrafficModeling/neuromancer has a 'pyproject.toml' and its build backend is missing the 'build_editable' hook. Since it does not have a 'setup.py' nor a 'setup.cfg', it cannot be installed in editable mode. Consider using a build backend that supports PEP 660.

BUG

Hi,
In linear.py, LinearBase has a logic error when initializing bias. When the bias is set to False, a tensor that requires gradients is initialized. When the bias is set to True, the bias tensor cannot accept gradients, but Xavier initialization is performed.
7731698135041_ pic_hd

Two_tank_node

I tried to run the example but I always receive the attached error. I have windows 11 , Conda version: conda 23.3.1

error

Constraint weights saved as nan if set to 0.0

During the training process, if any of the constraint weights, Q_con_x, Q_dx, Q_fd, etc, are set to 0.0, the logger saves them as NaN values. When the trained model is reloaded to run further evaluation experiments, these NaN values end up producing NaN trajectories.

Current workaround: Use if statement to explicitly set these NaN parameters to 0.0 before running further training or testing.

Feature Request: Multiple Symbolic Inputs for blocks.MLP

When experimenting with control policies in the form of blocks.MLP(), it is often useful to be able to change the features passed to the MLP. Currently I must create a new Node in order to concatenate features before passing them to an MLP. This clutters the graph when using system.show(), and adds mental overhead for research.

I would request that the blocks.MLP class be adapted so as to internally stack an arbitrary number of inputs, defined when the input and output symbols of the MLP are defined.

Support of creating custom neural network structure

Hello,

Thanks for creating this awesome library. Here is my question:
I know there are already some customizations that can be applied when creating a NN. (

blocks = {
"mlp": MLP,
"mlp_dropout": MLPDropout,
"mlp_bounds": MLP_bounds,
"rnn": RNN,
"pytorch_rnn": PytorchRNN,
"linear": Linear,
"residual_mlp": ResMLP,
"basislinear": BasisLinear,
"poly2": Poly2,
"bilinear": BilinearTorch,
"icnn": InputConvexNN,
"pos_def": PosDef
}
)

Is there a way for me to create custom NN structures? For example, I want to bound the NN output using torch.clamp().

Koopman Operators imports

In Part_8_nonauto_DeepKoopman.ipynb the initial install cell for colab should be:

!pip install fastapi kaleido python-multipart uvicorn
!pip install lida
!pip install "neuromancer[examples] @ git+https://github.com/pnnl/neuromancer.git@master"

to resolve an import error for lida:

"""ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.
lida 0.0.10 requires fastapi, which is not installed.
lida 0.0.10 requires kaleido, which is not installed.
lida 0.0.10 requires python-multipart, which is not installed.
lida 0.0.10 requires uvicorn, which is not installed.

Can it run on GPU?

Hello, I have been trying the module out over the past few days, but I haven't been able to run in on GPU, even after installing the CUDA enabled version of PyTorch.
Is the module supposed to run on CPU only or have I misconfigured something in my environment?

Thank you :)

pip install vs conda install pytorch versioning

When installing using the PIP technique, PyTorch 2.0.1 is used, whereas both the osxarm64, and linux yaml conda installs use PyTorch < 2.0.

This is problematic for me because I use functorch, which is part of PyTorch from 2.x onwards, and is only available as a pip install for PyTorch < 2.0, which then interferes with the conda install of PyTorch as it will uninstall the conda pytorch, and reinstall a pip PyTorch, breaking cuda acceleration in the process.

This issue is then to ask the conda PyTorch installs to support the same version as the pip install.

Problem graph error - Neuromancer v1.4

Hello, I've stumbled upon an error when trying to plot problem graphics with 1.4 release.

For instance, when trying to run the following code:

from neuromancer.constraint import variable
from neuromancer.problem import Problem
from neuromancer.loss import PenaltyLoss

xpred = variable('xn')[:, :-1, :]
xtrue = variable('X')

loss = (xpred == xtrue) ^ 2
loss.update_name('loss')

obj = PenaltyLoss([loss], [])
problem = Problem([model], obj)
problem.show() # <-- causing an error

I get the following error:

"dot" with args ['-Tpng', '/tmp/tmpw1zopj92'] returned code: 1

stdout, stderr:
 b''
b"Error: /tmp/tmpw1zopj92: syntax error in line 6 near '['\n"

AssertionError                            Traceback (most recent call last)
[<ipython-input-6-bac50fe996f9>](https://localhost:8080/#) in <cell line: 15>()
     13 obj = PenaltyLoss([loss], [])
     14 problem = Problem([model], obj)
---> 15 problem.show()

3 frames
[/usr/local/lib/python3.10/dist-packages/neuromancer/problem.py](https://localhost:8080/#) in show(self, figname)
    133             plot_func[ext](figname)
    134         else:
--> 135             graph.write_png('problem_graph.png')
    136             img = mpimg.imread('problem_graph.png')
    137             os.remove('problem_graph.png')

[/usr/local/lib/python3.10/dist-packages/pydot.py](https://localhost:8080/#) in new_method(path, f, prog, encoding)
   1741                     encoding=None):
   1742                 """Refer to docstring of method `write.`"""
-> 1743                 self.write(
   1744                     path, format=f, prog=prog,
   1745                     encoding=encoding)

[/usr/local/lib/python3.10/dist-packages/pydot.py](https://localhost:8080/#) in write(self, path, prog, format, encoding)
   1826                 f.write(s)
   1827         else:
-> 1828             s = self.create(prog, format, encoding=encoding)
   1829             with io.open(path, mode='wb') as f:
   1830                 f.write(s)

[/usr/local/lib/python3.10/dist-packages/pydot.py](https://localhost:8080/#) in create(self, prog, format, encoding)
   1954             print(message)
   1955 
-> 1956         assert process.returncode == 0, (
   1957                 '"{prog}" with args {arguments} returned code: {code}'.format(
   1958                     prog=prog,

AssertionError: "dot" with args ['-Tpng', '/tmp/tmpw1zopj92'] returned code: 1

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.