diff --git a/.gitignore b/.gitignore index eb84af0..a6fc745 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ *.egg-info __pycache__ .ipynb_checkpoints +build +annfore/examples/*npz +annfore/examples/*gz diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..706d281 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [2022] [Indaco Biazzo and Fabio Mazza] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/README.md b/README.md index 62e70a4..4d2d60c 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,28 @@ -# ANNforEpi: Autoregressive neural networks for epidemics +# annfore: [a]utoregressive [n]eural [n]etworks [for] [e]pidemics inference problems + +The repository contains the code for an autoregressive neural network approach to solve epidemic inference problems on contact newtorks. The patient zero problems, risk assmement or the inference of the infectivity of class of individuals are important examples. + +Up until now annfore supports the SIR compartimental model on contact networks, more complicated compartimental model can be easly added. + +annfore can compute the probability to each individuals to be susceptible, infected or recovered at a given time from a list of contacts and partial observations. +At the same time, it can infer the parameters of the propagation model (like the probability of infection λ). + +The approach is based on the autoregressive probability apporoximation of the postieror probability of the inference problem. See [here](https://arxiv.org/abs/2111.03383) for more details. + +## Install the code + +Clone the repo and type: +``` +cd annfore +pip install . +``` + +## Examples to run + +See [example](./annfore/examples/first_example.ipynb) + +## Reference +If you use the repository, please cite: + +Biazzo, I., Braunstein, A., Dall'Asta, L. and Mazza, F., 2021. Epidemic inference through generative neural networks. arXiv preprint [arXiv:2111.03383](https://arxiv.org/abs/2111.03383). -This repository contains the code for the Autoregressive Neural Networks \ No newline at end of file diff --git a/annfore/examples/first_example.ipynb b/annfore/examples/first_example.ipynb new file mode 100644 index 0000000..fd01a69 --- /dev/null +++ b/annfore/examples/first_example.ipynb @@ -0,0 +1,204 @@ +{ + "cells": [ + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "import numpy as np\n", + "import annfore" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [], + "source": [ + "from annfore.net import nn_sir_path_obs\n", + "from annfore.models import sir_model_N_obs\n", + "from annfore.utils.graph import find_neighs\n", + "\n", + "from annfore.learn.opt import make_opt\n", + "from annfore.learn.losses import loss_fn_coeff\n", + "from annfore.learn.train import train_beta, make_training_step_local" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "device=\"cpu\"" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [], + "source": [ + "# contact array of with entries [time, node_i, node_j, lambda]\n", + "# ordered by time\n", + "contacts = np.array([\n", + " [0,1,0, 0.5],\n", + " [0,0,1, 0.5],\n", + " [0,2,0, 0.5],\n", + " [0,0,2, 0.5],\n", + " [2,3,0, 0.5],\n", + " [2,0,3, 0.5],\n", + " [3,1,0, 0.5],\n", + " [3,0,1, 0.5],\n", + "])\n", + "\n", + "# observations [node, state, time] -- state 0,1,2 for S,I,R\n", + "# ordered by time\n", + "\n", + "obs = [\n", + " [1,1,0],\n", + " [2,0,0],\n", + " [3,1,3],\n", + " ]\n", + "\n", + "N = int(max(contacts[:, 1]) + 1)\n", + "t_limit = int(max(contacts[:, 0]) + 1) # t_limit times || +1 obs after contacts\n", + "mu=0.1\n" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [], + "source": [ + "# SIR model\n", + "model = sir_model_N_obs.SirModel(contacts, \n", + " mu = mu,\n", + " device = device)\n", + "model.set_obs(obs)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [], + "source": [ + "# define the autoregressive neurla network\n", + "dependece_net = find_neighs(contacts,N=N,only_minor=True, next_near_neigh=True)\n", + "net = nn_sir_path_obs.SIRPathColdObs(dependece_net,\n", + " t_limit+1, # +1 for susceptible\n", + " obs_list=obs,\n", + " hidden_layer_spec=[1,1],\n", + " )" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [], + "source": [ + "# define the optimizer over the parameters of the net\n", + "optimizer = []\n", + "lr = 1e-3\n", + "for i in range(N):\n", + " if len(net.params_i[i]):\n", + " optimizer.append(make_opt(net.params_i[i], lr=lr))\n" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " 200 beta: 0.2000, loss: 100.355, std: 18.045, ener: 109.13, max_grad = 0.0, count_zero_pw = 141.00, num_I = 1.620, num_R = 0.1000 (T_obs=0) -- took 7 ms: sample: 1, log_prob: 0, trans_sample: 0, energy: 1, loss: 0, optim_step: 3, stats: 0 -- source: { 1:1.000, 3:0.440, 0:0.180, 2:0.000} - remain time: 5 s, 646 msdict_keys(['step', 'beta', 'energy', 'std_energy', 'loss', 'loss_std', 'S', 'I', 'R', 't_obs', 'num_source', 'sources', 'max_grad', 'num_zero_pw', 'N', 'T', 'p_source', 'p_sus', 'p_obs', 'p_w', 'mu', 'times'])\n", + " 400 beta: 0.4000, loss: 72.050, std: 10.798, ener: 76.83, max_grad = 0.0, count_zero_pw = 22.00, num_I = 1.370, num_R = 0.0100 (T_obs=0) -- took 7 ms: sample: 1, log_prob: 0, trans_sample: 0, energy: 1, loss: 0, optim_step: 3, stats: 0 -- source: { 1:1.000, 3:0.200, 0:0.170, 2:0.000} - remain time: 4 s, 232 msdict_keys(['step', 'beta', 'energy', 'std_energy', 'loss', 'loss_std', 'S', 'I', 'R', 't_obs', 'num_source', 'sources', 'max_grad', 'num_zero_pw', 'N', 'T', 'p_source', 'p_sus', 'p_obs', 'p_w', 'mu', 'times'])\n", + " 600 beta: 0.6000, loss: 64.515, std: 3.568, ener: 67.47, max_grad = 0.0, count_zero_pw = 2.00, num_I = 1.070, num_R = 0.0000 (T_obs=0) -- took 7 ms: sample: 1, log_prob: 0, trans_sample: 0, energy: 1, loss: 0, optim_step: 3, stats: 0 -- source: { 1:1.000, 0:0.040, 3:0.030, 2:0.000} - remain time: 2 s, 793 msdict_keys(['step', 'beta', 'energy', 'std_energy', 'loss', 'loss_std', 'S', 'I', 'R', 't_obs', 'num_source', 'sources', 'max_grad', 'num_zero_pw', 'N', 'T', 'p_source', 'p_sus', 'p_obs', 'p_w', 'mu', 'times'])\n", + " 800 beta: 0.8000, loss: 63.706, std: 1.930, ener: 66.11, max_grad = 0.0, count_zero_pw = 1.00, num_I = 1.010, num_R = 0.0000 (T_obs=0) -- took 7 ms: sample: 1, log_prob: 0, trans_sample: 0, energy: 2, loss: 0, optim_step: 3, stats: 0 -- source: { 1:1.000, 0:0.010, 2:0.000, 3:0.000} - remain time: 1 s, 393 msdict_keys(['step', 'beta', 'energy', 'std_energy', 'loss', 'loss_std', 'S', 'I', 'R', 't_obs', 'num_source', 'sources', 'max_grad', 'num_zero_pw', 'N', 'T', 'p_source', 'p_sus', 'p_obs', 'p_w', 'mu', 'times'])\n", + " 999 beta: 0.9990, loss: 64.039, std: 3.999, ener: 66.16, max_grad = 0.0, count_zero_pw = 3.00, num_I = 1.010, num_R = 0.0000 (T_obs=0) -- took 7 ms: sample: 1, log_prob: 0, trans_sample: 0, energy: 1, loss: 0, optim_step: 3, stats: 0 -- source: { 1:1.000, 0:0.010, 2:0.000, 3:0.000} - remain time: 0 msdict_keys(['step', 'beta', 'energy', 'std_energy', 'loss', 'loss_std', 'S', 'I', 'R', 't_obs', 'num_source', 'sources', 'max_grad', 'num_zero_pw', 'N', 'T', 'p_source', 'p_sus', 'p_obs', 'p_w', 'mu', 'times'])\n", + "\n" + ] + } + ], + "source": [ + "t_obs = 0\n", + "betas = np.arange(0,1, 1e-3)\n", + "num_samples = 100\n", + "results = train_beta(net, optimizer,\n", + " model, \"out.txt\",\n", + " loss_fn_coeff, t_obs,\n", + " num_samples=num_samples,\n", + " train_step = make_training_step_local,\n", + " betas=betas, save_every=200)" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "M = net.marginals()" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "tensor([0.0071, 1.0000, 0.0000, 0.0056])" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "M[:, 0,1] # marginal probability to be infected of nodes (0,1,2,3) at time t = 0" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + } + ], + "metadata": { + "interpreter": { + "hash": "63289e09a2577d8cfdd70b9f838bc057d3af83fa8d314fd25a511c3cad8291bb" + }, + "kernelspec": { + "display_name": "Python 3.8.12 64-bit ('annfore': conda)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.8.12" + }, + "orig_nbformat": 4 + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/annfore/net/deep_linear.py b/annfore/net/deep_linear.py index 9d11018..4346887 100644 --- a/annfore/net/deep_linear.py +++ b/annfore/net/deep_linear.py @@ -5,23 +5,25 @@ from torch.nn.parameter import Parameter from torch.nn import init + def calc_feat_power(dim_input, out_count, nlay, power=2): if dim_input == 0: # just bias features = [dim_input, out_count, out_count] else: - c = (dim_input-out_count)/(nlay**power) - x = np.linspace(0,nlay, nlay+2) - y = c*x**power + out_count + c = (dim_input - out_count) / (nlay ** power) + x = np.linspace(0, nlay, nlay + 2) + y = c * x ** power + out_count y[-1] = dim_input y[0] = out_count features = list(y.astype(int)[::-1]) return features + def weights_init_uniform_rule(m): classname = m.__class__.__name__ # for every Linear layer in a model.. - if classname.find('Linear') != -1: + if classname.find("Linear") != -1: # get the number of the inputs n = m.in_features y = 0.1 @@ -38,26 +40,25 @@ def reset_weights_on_net(mod, lin_r=None, bias_r=0.1, kind="uniform"): classname = mod.__class__.__name__ if isinstance(mod, ZeroLinear): mod.reset_parameters(bias_r) - elif classname.find('Linear') != -1: + elif classname.find("Linear") != -1: if kind == "uniform": if lin_r is None: n = mod.in_features - y = 1.0/np.sqrt(n) + y = 1.0 / np.sqrt(n) mod.weight.data.uniform_(-y, y) else: - mod.weight.data.uniform_(-1*lin_r, lin_r) - #low = 0.1 + mod.weight.data.uniform_(-1 * lin_r, lin_r) + # low = 0.1 if mod.bias is not None: mod.bias.data.uniform_(-bias_r, bias_r) - elif kind=="xavier": - gain = nn.init.calculate_gain('relu') + elif kind == "xavier": + gain = nn.init.calculate_gain("relu") nn.init.xavier_uniform_(mod.weight.data, gain=gain) if mod.bias is not None: mod.bias.data.uniform_(-bias_r, bias_r) - - elif classname.find('Embedding') != -1: - nn.init.normal_(mod.weight, 0., 1.) + elif classname.find("Embedding") != -1: + nn.init.normal_(mod.weight, 0.0, 1.0) class ZeroLinear(nn.Module): @@ -73,18 +74,20 @@ def __init__(self, out_features, bias): self.has_bias = False self.reset_parameters() - def reset_parameters(self,rang=0.1): + def reset_parameters(self, rang=0.1): if self.has_bias: - #if kind=="uniform": + # if kind=="uniform": init.uniform_(self.bias, -rang, rang) - #elif kind=="xavier": + # elif kind=="xavier": # nn.init.xavier_uniform_(self.bias, gain=nn.init.calculate_gain('relu')) def forward(self, x): return self.bias.repeat(x.shape[0], 1) def extra_repr(self): - return 'in_features=0, out_features={}, bias={}'.format(self.out_features, self.bias is not None) + return "in_features=0, out_features={}, bias={}".format( + self.out_features, self.bias is not None + ) def my_linear(in_feat, out_feat, bias): @@ -122,8 +125,14 @@ class deep_linear(nn.Module): Container class for layers """ - def __init__(self, features, bias, in_func=nn.ReLU(), - last_func=nn.Sigmoid(), layer_norm=False): + def __init__( + self, + features, + bias, + in_func=nn.ReLU(), + last_func=nn.Sigmoid(), + layer_norm=False, + ): super(deep_linear, self).__init__() layers = [] if features[-1] == 0: @@ -133,9 +142,9 @@ def __init__(self, features, bias, in_func=nn.ReLU(), in_feat = feat out_feat = features[feat_i + 1] - mbias = True if (in_feat==0 and out_feat > 0) else bias + mbias = True if (in_feat == 0 and out_feat > 0) else bias layers.append(my_linear(in_feat, out_feat, mbias)) - if layer_norm and in_feat > 0 and feat_i < len(features)-2: + if layer_norm and in_feat > 0 and feat_i < len(features) - 2: layers.append(nn.LayerNorm([out_feat])) # layers[-1].apply(weights_init_uniform_rule) @@ -145,13 +154,14 @@ def __init__(self, features, bias, in_func=nn.ReLU(), layers.pop() if last_func is None: print(layers) + self.net = nn.Sequential(*layers) ##init if "ReLU" in repr(in_func): try: slope = in_func.negative_slope - init_gain = nn.init.calculate_gain("leaky_relu",slope) + init_gain = nn.init.calculate_gain("leaky_relu", slope) except AttributeError: # we have a pure ReLU init_gain = nn.init.calculate_gain("relu") @@ -164,7 +174,7 @@ def forward(self, x): return self.net(x) def reset(self, range_weight=None, range_bias=0.1): - fun = lambda m : reset_weights_on_net(m, range_weight, range_bias) + fun = lambda m: reset_weights_on_net(m, range_weight, range_bias) self.net.apply(fun) @@ -178,8 +188,17 @@ class MaskedDeepLinear(deep_linear): hidden_feat: list, multiplier for the intermediate layers """ - def __init__(self, dim_input, hidden_feat, mask, bias, in_func=nn.ReLU(), - last_func=nn.Sigmoid(), scale_power=2., layer_norm=False): + def __init__( + self, + dim_input, + hidden_feat, + mask, + bias, + in_func=nn.ReLU(), + last_func=nn.Sigmoid(), + scale_power=2.0, + layer_norm=False, + ): """ mask is a 1D tensor """ @@ -200,14 +219,20 @@ def __init__(self, dim_input, hidden_feat, mask, bias, in_func=nn.ReLU(), else: self.no_out = False self.out_count = out_count - + feat_inp = np.array(hidden_feat) - if np.all(feat_inp < 0) or dim_input==0: + if np.all(feat_inp < 0) or dim_input == 0: n_lay_want = len(hidden_feat) - features = calc_feat_power(dim_input, out_count, n_lay_want, power=scale_power) + features = calc_feat_power( + dim_input, out_count, n_lay_want, power=scale_power + ) else: - features = [dim_input]+(feat_inp*dim_input).astype(int).tolist()+[out_count] - + features = ( + [dim_input] + + (feat_inp * dim_input).astype(int).tolist() + + [out_count] + ) + self.features = tuple(features) super().__init__(features, bias, in_func, last_func, layer_norm=layer_norm) @@ -216,7 +241,7 @@ def forward(self, x): Forward method without initializing sample index """ if self.no_out: - return torch.ones((x.shape[0],1), device=x.device, dtype=x.dtype) + return torch.ones((x.shape[0], 1), device=x.device, dtype=x.dtype) else: return self.net(x) @@ -232,8 +257,10 @@ def parameters(self, recurse: bool = True): def extra_repr(self): if not self.no_out: - return "first_v={}, last_v={}, ".format(self.index_out[0], self.index_out[-1])\ + return ( + "first_v={}, last_v={}, ".format(self.index_out[0], self.index_out[-1]) + super().extra_repr() + ) return "fixed_v={}".format(self.index_out[0]) @@ -247,8 +274,15 @@ class EmbedMaskDeepLinear(nn.Module): with embedding in input """ - def __init__(self, inputs_neighs,hidden_feat, mask, - bias=True, in_func=nn.ReLU(), last_func=nn.Sigmoid()): + def __init__( + self, + inputs_neighs, + hidden_feat, + mask, + bias=True, + in_func=nn.ReLU(), + last_func=nn.Sigmoid(), + ): """ mask is a 1D tensor """ @@ -269,7 +303,7 @@ def __init__(self, inputs_neighs,hidden_feat, mask, self.no_out = True self.out_count = 0 feat = [0] - self.features = (0,1) + self.features = (0, 1) else: self.no_out = False @@ -293,9 +327,12 @@ def make_layer(self, inputs_neighs, hidden_feat, in_func, last_func, bias): # the first layer is the number of outputs hidden_layers_1 = [int(v * base_dim) for v in hidden_feat] features_lin = hidden_layers_1 + [out_count] - self.embeds = nn.ModuleList([ - nn.Embedding(neigh_out, hidden_feat[0] * base_dim) for neigh_out in inputs_neighs - ]) + self.embeds = nn.ModuleList( + [ + nn.Embedding(neigh_out, hidden_feat[0] * base_dim) + for neigh_out in inputs_neighs + ] + ) self.mid_lay = in_func layers = make_lin_layers(features_lin, in_func, last_func, bias) @@ -307,28 +344,28 @@ def forward(self, x): Forward method """ if self.no_out: - return torch.ones((x.shape[0],1), device=x.device, dtype=x.dtype) + return torch.ones((x.shape[0], 1), device=x.device, dtype=x.dtype) elif self.dim_input == 0: return self.net(x) else: - outv = sum([ - self.embeds[i](x[:,i]) for i in range(len(self.embeds)) - ]) - + outv = sum([self.embeds[i](x[:, i]) for i in range(len(self.embeds))]) + return self.net(self.mid_lay(outv)) def reset(self, range_weight=None, range_bias=0.1): if not self.no_out: - fun = lambda m : reset_weights_on_net(m, range_weight, range_bias) + fun = lambda m: reset_weights_on_net(m, range_weight, range_bias) self.net.apply(fun) if self.dim_input > 0: self.embeds.apply(fun) def extra_repr(self): if not self.no_out: - return "first_v={}, last_v={}, ".format(self.index_out[0], self.index_out[-1])\ + return ( + "first_v={}, last_v={}, ".format(self.index_out[0], self.index_out[-1]) + super().extra_repr() + ) return "fixed_v={}".format(self.index_out[0]) @@ -340,18 +377,19 @@ class TwoNetCascade(nn.Module): x,y1 -> y2 """ - def __init__(self, features, bias, in_func=nn.ReLU(), - last_func=nn.Sigmoid()): + def __init__(self, features, bias, in_func=nn.ReLU(), last_func=nn.Sigmoid()): super(TwoNetCascade, self).__init__() self.feat_first = list(features) - self.first_net = deep_linear(features, bias, - in_func=in_func, last_func=last_func) + self.first_net = deep_linear( + features, bias, in_func=in_func, last_func=last_func + ) self.feat_second = list(features) self.feat_second[0] += self.feat_first[-1] - self.second_net = deep_linear(self.feat_second, bias, - in_func=in_func, last_func=last_func) + self.second_net = deep_linear( + self.feat_second, bias, in_func=in_func, last_func=last_func + ) self.device = "cpu" def forward(self, x): diff --git a/annfore/net/nn_sir_path_obs.py b/annfore/net/nn_sir_path_obs.py index 6e4c23c..c1e3787 100644 --- a/annfore/net/nn_sir_path_obs.py +++ b/annfore/net/nn_sir_path_obs.py @@ -14,67 +14,73 @@ def make_masks(observ, n, T): #order: time, node, value order: node_i, state/value, time """ - masks = np.full((n,2, T+1), True) - times = np.arange(T+1) + masks = np.full((n, 2, T + 1), True) + times = np.arange(T + 1) for line in observ: - #print(i,"\n",r) - mask_inf = np.zeros_like(times, dtype=np.bool)#masks[r.node,0] - mask_rec = np.zeros_like(times, dtype=np.bool)#masks[r.node,1] + # print(i,"\n",r) + mask_inf = np.zeros_like(times, dtype=np.bool) # masks[r.node,0] + mask_rec = np.zeros_like(times, dtype=np.bool) # masks[r.node,1] t_obs = line[2] idx_obs = line[0] val_obs = line[1] - if val_obs == 0: #susc + if val_obs == 0: # susc mask_inf[times > t_obs] = True mask_rec[times > t_obs] = True - elif val_obs == 1: # inf + elif val_obs == 1: # inf mask_inf[times <= t_obs] = True mask_rec[times > t_obs] = True - elif val_obs == 2: ##rec + elif val_obs == 2: ##rec mask_inf[times <= t_obs] = True mask_rec[times <= t_obs] = True - + else: raise ValueError("Invalid observation value") - #print(i, masks[r.node,0].view(np.int8), masks[r.node,1].view(np.int8)) - if np.all(mask_inf==False): + # print(i, masks[r.node,0].view(np.int8), masks[r.node,1].view(np.int8)) + if np.all(mask_inf == False): mask_inf[-1] = True - if np.all(mask_rec==False): + if np.all(mask_rec == False): mask_rec[-1] = True - masks[idx_obs,0] &= mask_inf - masks[idx_obs, 1]&= mask_rec - if len(observ) > 0: - print(masks[idx_obs,0].view(np.int8)) - print(masks[idx_obs,1].view(np.int8)) + masks[idx_obs, 0] &= mask_inf + masks[idx_obs, 1] &= mask_rec + if len(observ) > 0: + # print(masks[idx_obs,0].view(np.int8)) + # print(masks[idx_obs,1].view(np.int8)) + pass return masks + class SIRPathColdObs(common_net.Autoreg): """ Compact SI Path samples stored non-one-hot """ + q = 3 - def __init__(self, neighs, T:int, - obs_list:list, - hidden_layer_spec:list, - bias:bool =True, - min_value_prob=1e-40, - in_func=nn.ReLU(), - last_func=nn.Softmax(dim=1), - device="cpu", - dtype=torch.float, - lin_scale_power:float=2., - layer_norm:bool=False, - ): + def __init__( + self, + neighs, + T: int, + obs_list: list, + hidden_layer_spec: list, + bias: bool = True, + min_value_prob=1e-40, + in_func=nn.ReLU(), + last_func=nn.Softmax(dim=1), + device="cpu", + dtype=torch.float, + lin_scale_power: float = 2.0, + layer_norm: bool = False, + ): """ Observations have to be in a list of values (node_i, state/value as integer, time of obs) """ - super().__init__(device,dtype) + super().__init__(device, dtype) self.N = len(neighs) self.T = T - self.num_feat = T+1 + self.num_feat = T + 1 if isinstance(neighs, dict): self.true_neighs = [] self.nodes_labels = [] @@ -86,7 +92,6 @@ def __init__(self, neighs, T:int, self.true_neighs = [sorted(x) for x in neighs] self.nodes_labels = list(range(len(neighs))) - self.num_nets = self.N self.data_basic_shape = (self.N, 2) self.bias = bias @@ -96,37 +101,29 @@ def __init__(self, neighs, T:int, self.linear_net_scaling = lin_scale_power self.layer_norm = layer_norm - self.masks = torch.tensor( - make_masks(obs_list, self.N, self.T) - ) - #for i in range(self.N): + self.masks = torch.tensor(make_masks(obs_list, self.N, self.T)) + # for i in range(self.N): # print(self.masks[i].to(torch.int8)) - self.sublayers = [] n_digits = int(np.ceil(np.log10(self.num_nets))) # Build sublayers for n_i in range(self.num_nets): - layer = self.build_layer(n_i, - hidden_layer_spec, - bias, - in_func, - last_func, - lin_scale_power) + layer = self.build_layer( + n_i, hidden_layer_spec, bias, in_func, last_func, lin_scale_power + ) layer.to(device=device) self.sublayers.append(layer) - self.add_module("lay_{n:0{width}d}".format(n=n_i, width=n_digits),layer) + self.add_module("lay_{n:0{width}d}".format(n=n_i, width=n_digits), layer) self.params = [] for i in range(self.num_nets): - pars = filter(lambda p: p.requires_grad, - self.sublayers[i].parameters()) + pars = filter(lambda p: p.requires_grad, self.sublayers[i].parameters()) self.params.extend(pars) - #self.params = list(filter(lambda p: p.requires_grad, self.params)) - #self.params = list(self.params) + # self.params = list(filter(lambda p: p.requires_grad, self.params)) + # self.params = list(self.params) self.nparams = int(sum([np.prod(p.shape) for p in self.params])) - self.sample_dtype = torch.long """ self.sample_neighs =[] @@ -148,15 +145,16 @@ def __init__(self, neighs, T:int, self.bselect = None self.params_i = {} - + for i in range(self.num_nets): - self.params_i[i] = tuple( filter(lambda p: p.requires_grad, - self.sublayers[i].parameters()) ) - - #print(self.masks.to(int)) - #for n in self.sublayers: + self.params_i[i] = tuple( + filter(lambda p: p.requires_grad, self.sublayers[i].parameters()) + ) + + # print(self.masks.to(int)) + # for n in self.sublayers: # print((n[0].out_count, n[1].out_count)) - #print(self.dimensions()) + # print(self.dimensions()) def build_layer(self, idx, layer_spec, bias, in_func, last_func, scale_power): """ @@ -168,13 +166,21 @@ def build_layer(self, idx, layer_spec, bias, in_func, last_func, scale_power): n_input += self.sublayers[int(neig)][1].out_count kwargs = dict(scale_power=scale_power, layer_norm=self.layer_norm) - net_inf = deep_linear.MaskedDeepLinear(n_input, layer_spec, self.masks[idx][0], - bias, in_func, last_func, **kwargs) + net_inf = deep_linear.MaskedDeepLinear( + n_input, layer_spec, self.masks[idx][0], bias, in_func, last_func, **kwargs + ) n_input_rec = n_input + net_inf.out_count - net_rec = deep_linear.MaskedDeepLinear(n_input_rec, layer_spec, self.masks[idx][1], - bias, in_func, last_func, **kwargs) - - return nn.ModuleList((net_inf,net_rec)) + net_rec = deep_linear.MaskedDeepLinear( + n_input_rec, + layer_spec, + self.masks[idx][1], + bias, + in_func, + last_func, + **kwargs + ) + + return nn.ModuleList((net_inf, net_rec)) def init(self, method="uniform", lin_r=None, bias_r=0.1): for lay in self.sublayers: @@ -182,7 +188,9 @@ def init(self, method="uniform", lin_r=None, bias_r=0.1): if mskdeep.out_count == 0: continue for mod in mskdeep.net: - deep_linear.reset_weights_on_net(mod, lin_r=lin_r, bias_r=bias_r, kind=method) + deep_linear.reset_weights_on_net( + mod, lin_r=lin_r, bias_r=bias_r, kind=method + ) def dimensions(self, active_only=False): return [[nett.features for nett in lay] for lay in self.sublayers] @@ -197,18 +205,19 @@ def extract_idx_samples(self, samples_cold, net_i): indix = self.nodes_labels[net_i] n_samples = samples_cold.shape[0] avoid_samples = (self.sublayers[net_i][0].out_count == 0) and ( - self.sublayers[net_i][1].out_count == 0) + self.sublayers[net_i][1].out_count == 0 + ) if avoid_samples: samples_select = torch.zeros((n_samples, 0), device=self.device) - elif(len(neighs_i) > 0): + elif len(neighs_i) > 0: # get the times of the neighbors - times = samples_cold[:,neighs_i] + times = samples_cold[:, neighs_i] # select the masks of the neighbors and flatten them masks_sel = self.masks_sample[neighs_i].view(-1) # put the samples on onehot and apply masks samples_hot = F.one_hot(times, self.num_feat).view(n_samples, -1) - samples_select = samples_hot[:,masks_sel].to(self.dtype) - #print(samples_select.shape) + samples_select = samples_hot[:, masks_sel].to(self.dtype) + # print(samples_select.shape) del samples_hot, times, masks_sel else: # the input vector should have dimension zero @@ -217,76 +226,78 @@ def extract_idx_samples(self, samples_cold, net_i): def _log_prob(self, samples, probs): ## TODO: check - #print(samples.shape, self.data_basic_shape) + # print(samples.shape, self.data_basic_shape) assert samples.shape[1:] == self.data_basic_shape log_prob = torch.log(probs.clamp(min=self.min_value_prob)) - #print(log_prob.shape) + # print(log_prob.shape) return log_prob.sum(-1).sum(-1) def _get_trec_probs(self, i, samples_inf, inf_idx_times, batch_size): n_out_inf = self.sublayers[i][0].out_count if n_out_inf > 0: - t_inf_hot = F.one_hot(inf_idx_times,n_out_inf).view(batch_size, -1) + t_inf_hot = F.one_hot(inf_idx_times, n_out_inf).view(batch_size, -1) - t_rec_probs = self.sublayers[i][1](torch.cat((samples_inf, t_inf_hot.to(self.dtype)),dim=-1)) + t_rec_probs = self.sublayers[i][1]( + torch.cat((samples_inf, t_inf_hot.to(self.dtype)), dim=-1) + ) else: ### the infection time is fixed t_rec_probs = self.sublayers[i][1](samples_inf) return t_rec_probs - + def sample(self, batch_size): """ Sample the network, computing probabilities first and them sum them """ data_shape = (batch_size, self.N, 2) - samples = self.get_empty_matrix(data_shape,data_type=self.sample_dtype) + samples = self.get_empty_matrix(data_shape, data_type=self.sample_dtype) samples.requires_grad_(False) - #samples_hot = torch.zeros(num_s,N,2,T+1,device=device) + # samples_hot = torch.zeros(num_s,N,2,T+1,device=device) probs = self.get_empty_matrix(data_shape) - bselect = torch.arange( - batch_size, dtype=torch.long, device=self.device) + bselect = torch.arange(batch_size, dtype=torch.long, device=self.device) # print(samples_hot) for i in range(self.num_nets): - #print(f"Node {i} inf",end="\r") + # print(f"Node {i} inf",end="\r") with torch.no_grad(): indix, samples_select = self.extract_idx_samples(samples, i) # print(i,indix,samples_select) # Infection times - if self.sublayers[i][0].out_count ==0: + if self.sublayers[i][0].out_count == 0: ##avoid random draw with torch.no_grad(): idx_times = None samples[:, indix, 0] = self.sublayers[i][0].index_out[0] - probs[:,indix,0] = 1. + probs[:, indix, 0] = 1.0 else: t_inf_probs = self.sublayers[i][0](samples_select) with torch.no_grad(): ## sample tinf - idx_times = torch.multinomial(t_inf_probs, 1).squeeze()#.detach() - samples[:,indix,0] = idx_times + self.sublayers[i][0].index_out[0] - probs[:,indix,0] = t_inf_probs[bselect,idx_times] + idx_times = torch.multinomial(t_inf_probs, 1).squeeze() # .detach() + samples[:, indix, 0] = idx_times + self.sublayers[i][0].index_out[0] + probs[:, indix, 0] = t_inf_probs[bselect, idx_times] del t_inf_probs - #print(f"Node {i} rec", end="\r") + # print(f"Node {i} rec", end="\r") t_rec_probs = self._get_trec_probs(i, samples_select, idx_times, batch_size) ### don't do random draws when we are certain of the time - if self.sublayers[i][1].out_count ==0: + if self.sublayers[i][1].out_count == 0: with torch.no_grad(): - idx_times=torch.ones((batch_size, 1), device=self.device, dtype=samples.dtype) + idx_times = torch.ones( + (batch_size, 1), device=self.device, dtype=samples.dtype + ) samples[:, indix, 1] = self.sublayers[i][1].index_out[0] - probs[:,indix,1] = 1. + probs[:, indix, 1] = 1.0 else: with torch.no_grad(): ## sample tinf - idx_trec = torch.multinomial(t_rec_probs, 1).squeeze()#.detach() - samples[:,indix,1] = idx_trec + self.sublayers[i][1].index_out[0] - probs[:,indix,1] = t_rec_probs[bselect,idx_trec] + idx_trec = torch.multinomial(t_rec_probs, 1).squeeze() # .detach() + samples[:, indix, 1] = idx_trec + self.sublayers[i][1].index_out[0] + probs[:, indix, 1] = t_rec_probs[bselect, idx_trec] del idx_trec - - del indix, samples_select - #samples[bselect, indix, times] = 1 + del indix, samples_select + # samples[bselect, indix, times] = 1 return samples.detach(), probs @@ -296,21 +307,21 @@ def forward(self, x): """ batch_size = x.shape[0] shape = (batch_size, *self.data_basic_shape) - bselect = torch.arange( - batch_size, dtype=torch.long, device=self.device) + bselect = torch.arange(batch_size, dtype=torch.long, device=self.device) probs = self.get_empty_matrix(shape) for i in range(self.num_nets): indix, samples_select = self.extract_idx_samples(x, i) - t_inf_probs= self.sublayers[i][0](samples_select) - sam_indics = x[:,indix,0] - self.sublayers[i][0].index_out[0] - probs[:,indix, 0] = t_inf_probs[bselect, sam_indics] + t_inf_probs = self.sublayers[i][0](samples_select) + sam_indics = x[:, indix, 0] - self.sublayers[i][0].index_out[0] + probs[:, indix, 0] = t_inf_probs[bselect, sam_indics] - t_rec_probs = self._get_trec_probs(i, samples_select, sam_indics, batch_size) + t_rec_probs = self._get_trec_probs( + i, samples_select, sam_indics, batch_size + ) - sam_indics = x[:,indix,1] - self.sublayers[i][1].index_out[0] - probs[:,indix, 1] = t_rec_probs[bselect, sam_indics] + sam_indics = x[:, indix, 1] - self.sublayers[i][1].index_out[0] + probs[:, indix, 1] = t_rec_probs[bselect, sam_indics] - return probs def log_prob_i(self, node_i, samples): @@ -319,35 +330,38 @@ def log_prob_i(self, node_i, samples): """ batch_size = samples.shape[0] bselect = torch.arange( - batch_size, dtype=torch.long, device=self.device, requires_grad=False) + batch_size, dtype=torch.long, device=self.device, requires_grad=False + ) # get relevant samples indix, samples_select = self.extract_idx_samples(samples, node_i) - t_inf_probs= self.sublayers[node_i][0](samples_select) - sam_indics = samples[:,indix,0] - self.sublayers[node_i][0].index_out[0] + t_inf_probs = self.sublayers[node_i][0](samples_select) + sam_indics = samples[:, indix, 0] - self.sublayers[node_i][0].index_out[0] probs_i_sel = t_inf_probs[bselect, sam_indics] - - t_rec_probs = self._get_trec_probs(node_i, samples_select, sam_indics, batch_size) - sam_indics = samples[:,indix,1] - self.sublayers[node_i][1].index_out[0] + t_rec_probs = self._get_trec_probs( + node_i, samples_select, sam_indics, batch_size + ) + + sam_indics = samples[:, indix, 1] - self.sublayers[node_i][1].index_out[0] probs_r_sel = t_rec_probs[bselect, sam_indics] - log_prob_i = torch.log(probs_i_sel.clamp(min=self.min_value_prob)) + \ - torch.log(probs_r_sel.clamp(min=self.min_value_prob)) + log_prob_i = torch.log(probs_i_sel.clamp(min=self.min_value_prob)) + torch.log( + probs_r_sel.clamp(min=self.min_value_prob) + ) assert len(log_prob_i.shape) == 1 and log_prob_i.shape[0] == batch_size return log_prob_i - def transform_samples(self, samples): """ Transform samples to make them ready for SIR energy calculation - + This is valid for the non 1-hot energy calculation TODO: Check """ assert samples.shape[1:] == self.data_basic_shape return samples - def marginals_(self, samples, batch_size = 1000): + def marginals_(self, samples, batch_size=1000): """ Compute marginals transforming in one hot One batch at a time @@ -359,11 +373,10 @@ def marginals_(self, samples, batch_size = 1000): for mini_batch in view_batch: x_hot = c_utils.one_hot_conf_from_times(mini_batch, self.T) - marginals += x_hot.sum(dim=0) - return marginals/num_samples + return marginals / num_samples - def marginals(self, num_samples = 10000, batch_size = 100): + def marginals(self, num_samples=10000, batch_size=100): with torch.no_grad(): samples, prob = self.sample(num_samples) - return self.marginals_(samples, batch_size = batch_size) + return self.marginals_(samples, batch_size=batch_size) diff --git a/setup.py b/setup.py index 556b343..a8feae3 100644 --- a/setup.py +++ b/setup.py @@ -2,9 +2,9 @@ setup( - name="ANNforEpi", + name="ANNforE", version="0.1", - author="sibyl-team", + author="Indaco Biazzo, Fabio Mazza", packages=find_packages(), description="Epidemic inference with autoregressive neural networks", install_requires=[ @@ -13,4 +13,4 @@ "networkx", "torch" ] -) \ No newline at end of file +)