master-thesis/RecipeAnalysis/AdjacencyMatrix.ipynb
2019-09-05 12:03:01 +02:00

137 lines
3.7 KiB
Plaintext

{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Adjacency Matrix"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"\n",
"from scipy.sparse import csr_matrix, lil_matrix, coo_matrix"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"class adj_matrix(object):\n",
" def __init__(self, symmetric_indices=False):\n",
" \n",
" self._sym = symmetric_indices\n",
" if not symmetric_indices:\n",
" self._x_labels = []\n",
" self._y_labels = []\n",
"\n",
" self._x_label_index={}\n",
" self._y_label_index={}\n",
" \n",
" else:\n",
" self._labels = []\n",
" self._label_index={}\n",
" \n",
" self._x = []\n",
" self._y = []\n",
" self._data = []\n",
" \n",
" self._mat = None\n",
" \n",
" def _get_ix(self, label):\n",
" i = self._x_label_index.get(label)\n",
" if i is None:\n",
" i = len(self._x_labels)\n",
" self._x_labels.append(label)\n",
" self._x_label_index[label] = i\n",
" return i\n",
" \n",
" def _get_iy(self, label):\n",
" i = self._y_label_index.get(label)\n",
" if i is None:\n",
" i = len(self._y_labels)\n",
" self._y_labels.append(label)\n",
" self._y_label_index[label] = i\n",
" return i\n",
" \n",
" def _get_i(self, label):\n",
" i = self._label_index.get(label)\n",
" if i is None:\n",
" i = len(self._labels)\n",
" self._labels.append(label)\n",
" self._label_index[label] = i\n",
" return i\n",
" \n",
" def add_entry(self, x, y, data):\n",
" \n",
" if self._sym:\n",
" ix = self._get_i(x)\n",
" iy = self._get_i(y)\n",
" \n",
" else:\n",
" ix = self._get_ix(x)\n",
" iy = self._get_iy(y)\n",
" \n",
" self._x.append(ix)\n",
" self._y.append(iy)\n",
" self._data.append(data)\n",
" \n",
" \n",
" def compile_to_mat(self):\n",
" if self._sym:\n",
" sx = len(self._labels)\n",
" sy = len(self._labels)\n",
" else:\n",
" sx = len(self._x_labels)\n",
" sy = len(self._y_labels)\n",
" \n",
" self._mat = coo_matrix((self._data, (self._x, self._y)), shape=(sx,sy))\n",
" return self._mat\n",
" \n",
" def get_csr(self):\n",
" return self.compile_to_mat().tocsr()\n",
" \n",
" def get_labels(self):\n",
" if self._sym:\n",
" return self._labels\n",
" return self._x_labels, self._y_labels"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"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.7.3"
}
},
"nbformat": 4,
"nbformat_minor": 4
}