We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Loading dataset PROTEINS leads to IndexError
## 🐛 Bug

<!-- A clear and concise description of what the bug is. -->
When loading dataset PROTEINS using function `LegacyTUDataset()`, raise `IndexError: too many indices for array`
## To Reproduce

Steps to reproduce the behavior:

```python
from dgl.data import LegacyTUDataset

dataset = LegacyTUDataset(name='PROTEINS')
 ```
The error message as following:
```
~/opt/anaconda3/lib/python3.7/site-packages/dgl/data/tu.py in __init__(self, name, use_pandas, hidden_size, max_allow_node)
     78                 self._file_path("node_attributes"), delimiter=",")
     79             for idxs, g in zip(node_idx_list, self.graph_lists):
---> 80                 g.ndata['feat'] = DS_node_attr[idxs, :]
     81             self.data_mode = "node_attr"
     82         except IOError:

IndexError: too many indices for array
```
<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->

## Expected behavior

<!-- A clear and concise description of what you expected to happen. -->
Successfully loading PROTEINS dataset
## Environment

 - DGL Version (e.g., 1.0): 0.4.2
 - Backend Library & Version (e.g., PyTorch 0.4.1, MXNet/Gluon 1.3): PyTorch
 - OS (e.g., Linux): MacOS X
 - How you installed DGL (`conda`, `pip`, source): pip
 - Build command you used (if compiling from source):
 - Python version: 3.7
 - CUDA/cuDNN version (if applicable):
 - GPU models and configuration (e.g. V100):
 - Any other relevant information:

## Additional context

<!-- Add any other context about the problem here. -->


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `python/dgl/data/tu.py`
Content:
```
1 from __future__ import absolute_import
2 import numpy as np
3 import os
4 import random
5 
6 from .utils import download, extract_archive, get_download_dir, loadtxt
7 from ..graph import DGLGraph
8 
9 class LegacyTUDataset(object):
10     """
11     TUDataset contains lots of graph kernel datasets for graph classification.
12     Use provided node feature by default. If no feature provided, use one-hot node label instead.
13     If neither labels provided, use constant for node feature.
14 
15     :param name: Dataset Name, such as `ENZYMES`, `DD`, `COLLAB`
16     :param use_pandas: Default: False.
17         Numpy's file read function has performance issue when file is large,
18         using pandas can be faster.
19     :param hidden_size: Default 10. Some dataset doesn't contain features.
20         Use constant node features initialization instead, with hidden size as `hidden_size`.
21 
22     """
23 
24     _url = r"https://ls11-www.cs.tu-dortmund.de/people/morris/graphkerneldatasets/{}.zip"
25 
26     def __init__(self, name, use_pandas=False,
27                  hidden_size=10, max_allow_node=None):
28 
29         self.name = name
30         self.hidden_size = hidden_size
31         self.extract_dir = self._download()
32         self.data_mode = None
33         self.max_allow_node = max_allow_node
34 
35         if use_pandas:
36             import pandas as pd
37             DS_edge_list = self._idx_from_zero(
38                 pd.read_csv(self._file_path("A"), delimiter=",", dtype=int, header=None).values)
39         else:
40             DS_edge_list = self._idx_from_zero(
41                 np.genfromtxt(self._file_path("A"), delimiter=",", dtype=int))
42 
43         DS_indicator = self._idx_from_zero(
44             np.genfromtxt(self._file_path("graph_indicator"), dtype=int))
45         DS_graph_labels = self._idx_from_zero(
46             np.genfromtxt(self._file_path("graph_labels"), dtype=int))
47 
48         g = DGLGraph()
49         g.add_nodes(int(DS_edge_list.max()) + 1)
50         g.add_edges(DS_edge_list[:, 0], DS_edge_list[:, 1])
51 
52         node_idx_list = []
53         self.max_num_node = 0
54         for idx in range(np.max(DS_indicator) + 1):
55             node_idx = np.where(DS_indicator == idx)
56             node_idx_list.append(node_idx[0])
57             if len(node_idx[0]) > self.max_num_node:
58                 self.max_num_node = len(node_idx[0])
59 
60         self.graph_lists = g.subgraphs(node_idx_list)
61         self.num_labels = max(DS_graph_labels) + 1
62         self.graph_labels = DS_graph_labels
63 
64         try:
65             DS_node_labels = self._idx_from_zero(
66                 np.loadtxt(self._file_path("node_labels"), dtype=int))
67             g.ndata['node_label'] = DS_node_labels
68             one_hot_node_labels = self._to_onehot(DS_node_labels)
69             for idxs, g in zip(node_idx_list, self.graph_lists):
70                 g.ndata['feat'] = one_hot_node_labels[idxs, :]
71             self.data_mode = "node_label"
72         except IOError:
73             print("No Node Label Data")
74 
75         try:
76             DS_node_attr = np.loadtxt(
77                 self._file_path("node_attributes"), delimiter=",")
78             for idxs, g in zip(node_idx_list, self.graph_lists):
79                 g.ndata['feat'] = DS_node_attr[idxs, :]
80             self.data_mode = "node_attr"
81         except IOError:
82             print("No Node Attribute Data")
83 
84         if 'feat' not in g.ndata.keys():
85             for idxs, g in zip(node_idx_list, self.graph_lists):
86                 g.ndata['feat'] = np.ones((g.number_of_nodes(), hidden_size))
87             self.data_mode = "constant"
88             print(
89                 "Use Constant one as Feature with hidden size {}".format(hidden_size))
90 
91         # remove graphs that are too large by user given standard
92         # optional pre-processing steop in conformity with Rex Ying's original
93         # DiffPool implementation
94         if self.max_allow_node:
95             preserve_idx = []
96             print("original dataset length : ", len(self.graph_lists))
97             for (i, g) in enumerate(self.graph_lists):
98                 if g.number_of_nodes() <= self.max_allow_node:
99                     preserve_idx.append(i)
100             self.graph_lists = [self.graph_lists[i] for i in preserve_idx]
101             print(
102                 "after pruning graphs that are too big : ", len(
103                     self.graph_lists))
104             self.graph_labels = [self.graph_labels[i] for i in preserve_idx]
105             self.max_num_node = self.max_allow_node
106 
107     def __getitem__(self, idx):
108         """Get the i^th sample.
109         Paramters
110         ---------
111         idx : int
112             The sample index.
113         Returns
114         -------
115         (dgl.DGLGraph, int)
116             DGLGraph with node feature stored in `feat` field and node label in `node_label` if available.
117             And its label.
118         """
119         g = self.graph_lists[idx]
120         return g, self.graph_labels[idx]
121 
122     def __len__(self):
123         return len(self.graph_lists)
124 
125     def _download(self):
126         download_dir = get_download_dir()
127         zip_file_path = os.path.join(
128             download_dir,
129             "tu_{}.zip".format(
130                 self.name))
131         download(self._url.format(self.name), path=zip_file_path)
132         extract_dir = os.path.join(download_dir, "tu_{}".format(self.name))
133         extract_archive(zip_file_path, extract_dir)
134         return extract_dir
135 
136     def _file_path(self, category):
137         return os.path.join(self.extract_dir, self.name,
138                             "{}_{}.txt".format(self.name, category))
139 
140     @staticmethod
141     def _idx_from_zero(idx_tensor):
142         return idx_tensor - np.min(idx_tensor)
143 
144     @staticmethod
145     def _to_onehot(label_tensor):
146         label_num = label_tensor.shape[0]
147         assert np.min(label_tensor) == 0
148         one_hot_tensor = np.zeros((label_num, np.max(label_tensor) + 1))
149         one_hot_tensor[np.arange(label_num), label_tensor] = 1
150         return one_hot_tensor
151 
152     def statistics(self):
153         return self.graph_lists[0].ndata['feat'].shape[1],\
154             self.num_labels,\
155             self.max_num_node
156 
157 
158 class TUDataset(object):
159     """
160     TUDataset contains lots of graph kernel datasets for graph classification.
161     Graphs may have node labels, node attributes, edge labels, and edge attributes,
162     varing from different dataset.
163 
164     :param name: Dataset Name, such as `ENZYMES`, `DD`, `COLLAB`, `MUTAG`, can be the 
165     datasets name on https://ls11-www.cs.tu-dortmund.de/staff/morris/graphkerneldatasets.
166     """
167 
168     _url = r"https://ls11-www.cs.tu-dortmund.de/people/morris/graphkerneldatasets/{}.zip"
169 
170     def __init__(self, name):
171 
172         self.name = name
173         self.extract_dir = self._download()
174 
175         DS_edge_list = self._idx_from_zero(
176             loadtxt(self._file_path("A"), delimiter=",").astype(int))
177         DS_indicator = self._idx_from_zero(
178             loadtxt(self._file_path("graph_indicator"), delimiter=",").astype(int))
179         DS_graph_labels = self._idx_from_zero(
180             loadtxt(self._file_path("graph_labels"), delimiter=",").astype(int))
181 
182         g = DGLGraph()
183         g.add_nodes(int(DS_edge_list.max()) + 1)
184         g.add_edges(DS_edge_list[:, 0], DS_edge_list[:, 1])
185 
186         node_idx_list = []
187         self.max_num_node = 0
188         for idx in range(np.max(DS_indicator) + 1):
189             node_idx = np.where(DS_indicator == idx)
190             node_idx_list.append(node_idx[0])
191             if len(node_idx[0]) > self.max_num_node:
192                 self.max_num_node = len(node_idx[0])
193 
194         self.num_labels = max(DS_graph_labels) + 1
195         self.graph_labels = DS_graph_labels
196 
197         self.attr_dict = {
198             'node_labels': ('ndata', 'node_labels'),
199             'node_attributes': ('ndata', 'node_attr'),
200             'edge_labels': ('edata', 'edge_labels'),
201             'edge_attributes': ('edata', 'node_labels'),
202         }
203 
204         for filename, field_name in self.attr_dict.items():
205             try:
206                 data = loadtxt(self._file_path(filename),
207                                delimiter=',').astype(int)
208                 if 'label' in filename:
209                     data = self._idx_from_zero(data)
210                 getattr(g, field_name[0])[field_name[1]] = data
211             except IOError:
212                 pass
213 
214         self.graph_lists = g.subgraphs(node_idx_list)
215         for g in self.graph_lists:
216             g.copy_from_parent()
217 
218     def __getitem__(self, idx):
219         """Get the i^th sample.
220         Paramters
221         ---------
222         idx : int
223             The sample index.
224         Returns
225         -------
226         (dgl.DGLGraph, int)
227             DGLGraph with node feature stored in `feat` field and node label in `node_label` if available.
228             And its label.
229         """
230         g = self.graph_lists[idx]
231         return g, self.graph_labels[idx]
232 
233     def __len__(self):
234         return len(self.graph_lists)
235 
236     def _download(self):
237         download_dir = get_download_dir()
238         zip_file_path = os.path.join(
239             download_dir,
240             "tu_{}.zip".format(
241                 self.name))
242         download(self._url.format(self.name), path=zip_file_path)
243         extract_dir = os.path.join(download_dir, "tu_{}".format(self.name))
244         extract_archive(zip_file_path, extract_dir)
245         return extract_dir
246 
247     def _file_path(self, category):
248         return os.path.join(self.extract_dir, self.name,
249                             "{}_{}.txt".format(self.name, category))
250 
251     @staticmethod
252     def _idx_from_zero(idx_tensor):
253         return idx_tensor - np.min(idx_tensor)
254 
255     def statistics(self):
256         return self.graph_lists[0].ndata['feat'].shape[1], \
257             self.num_labels, \
258             self.max_num_node
259
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/python/dgl/data/tu.py b/python/dgl/data/tu.py
--- a/python/dgl/data/tu.py
+++ b/python/dgl/data/tu.py
@@ -75,6 +75,8 @@
         try:
             DS_node_attr = np.loadtxt(
                 self._file_path("node_attributes"), delimiter=",")
+            if DS_node_attr.ndim == 1:
+                DS_node_attr = np.expand_dims(DS_node_attr, -1)
             for idxs, g in zip(node_idx_list, self.graph_lists):
                 g.ndata['feat'] = DS_node_attr[idxs, :]
             self.data_mode = "node_attr"

{"golden_diff": "diff --git a/python/dgl/data/tu.py b/python/dgl/data/tu.py\n--- a/python/dgl/data/tu.py\n+++ b/python/dgl/data/tu.py\n@@ -75,6 +75,8 @@\n         try:\n             DS_node_attr = np.loadtxt(\n                 self._file_path(\"node_attributes\"), delimiter=\",\")\n+            if DS_node_attr.ndim == 1:\n+                DS_node_attr = np.expand_dims(DS_node_attr, -1)\n             for idxs, g in zip(node_idx_list, self.graph_lists):\n                 g.ndata['feat'] = DS_node_attr[idxs, :]\n             self.data_mode = \"node_attr\"\n", "issue": "Loading dataset PROTEINS leads to IndexError\n## \ud83d\udc1b Bug\r\n\r\n<!-- A clear and concise description of what the bug is. -->\r\nWhen loading dataset PROTEINS using function `LegacyTUDataset()`, raise `IndexError: too many indices for array`\r\n## To Reproduce\r\n\r\nSteps to reproduce the behavior:\r\n\r\n```python\r\nfrom dgl.data import LegacyTUDataset\r\n\r\ndataset = LegacyTUDataset(name='PROTEINS')\r\n ```\r\nThe error message as following:\r\n```\r\n~/opt/anaconda3/lib/python3.7/site-packages/dgl/data/tu.py in __init__(self, name, use_pandas, hidden_size, max_allow_node)\r\n     78                 self._file_path(\"node_attributes\"), delimiter=\",\")\r\n     79             for idxs, g in zip(node_idx_list, self.graph_lists):\r\n---> 80                 g.ndata['feat'] = DS_node_attr[idxs, :]\r\n     81             self.data_mode = \"node_attr\"\r\n     82         except IOError:\r\n\r\nIndexError: too many indices for array\r\n```\r\n<!-- If you have a code sample, error messages, stack traces, please provide it here as well -->\r\n\r\n## Expected behavior\r\n\r\n<!-- A clear and concise description of what you expected to happen. -->\r\nSuccessfully loading PROTEINS dataset\r\n## Environment\r\n\r\n - DGL Version (e.g., 1.0): 0.4.2\r\n - Backend Library & Version (e.g., PyTorch 0.4.1, MXNet/Gluon 1.3): PyTorch\r\n - OS (e.g., Linux): MacOS X\r\n - How you installed DGL (`conda`, `pip`, source): pip\r\n - Build command you used (if compiling from source):\r\n - Python version: 3.7\r\n - CUDA/cuDNN version (if applicable):\r\n - GPU models and configuration (e.g. V100):\r\n - Any other relevant information:\r\n\r\n## Additional context\r\n\r\n<!-- Add any other context about the problem here. -->\r\n\n", "before_files": [{"content": "from __future__ import absolute_import\nimport numpy as np\nimport os\nimport random\n\nfrom .utils import download, extract_archive, get_download_dir, loadtxt\nfrom ..graph import DGLGraph\n\nclass LegacyTUDataset(object):\n    \"\"\"\n    TUDataset contains lots of graph kernel datasets for graph classification.\n    Use provided node feature by default. If no feature provided, use one-hot node label instead.\n    If neither labels provided, use constant for node feature.\n\n    :param name: Dataset Name, such as `ENZYMES`, `DD`, `COLLAB`\n    :param use_pandas: Default: False.\n        Numpy's file read function has performance issue when file is large,\n        using pandas can be faster.\n    :param hidden_size: Default 10. Some dataset doesn't contain features.\n        Use constant node features initialization instead, with hidden size as `hidden_size`.\n\n    \"\"\"\n\n    _url = r\"https://ls11-www.cs.tu-dortmund.de/people/morris/graphkerneldatasets/{}.zip\"\n\n    def __init__(self, name, use_pandas=False,\n                 hidden_size=10, max_allow_node=None):\n\n        self.name = name\n        self.hidden_size = hidden_size\n        self.extract_dir = self._download()\n        self.data_mode = None\n        self.max_allow_node = max_allow_node\n\n        if use_pandas:\n            import pandas as pd\n            DS_edge_list = self._idx_from_zero(\n                pd.read_csv(self._file_path(\"A\"), delimiter=\",\", dtype=int, header=None).values)\n        else:\n            DS_edge_list = self._idx_from_zero(\n                np.genfromtxt(self._file_path(\"A\"), delimiter=\",\", dtype=int))\n\n        DS_indicator = self._idx_from_zero(\n            np.genfromtxt(self._file_path(\"graph_indicator\"), dtype=int))\n        DS_graph_labels = self._idx_from_zero(\n            np.genfromtxt(self._file_path(\"graph_labels\"), dtype=int))\n\n        g = DGLGraph()\n        g.add_nodes(int(DS_edge_list.max()) + 1)\n        g.add_edges(DS_edge_list[:, 0], DS_edge_list[:, 1])\n\n        node_idx_list = []\n        self.max_num_node = 0\n        for idx in range(np.max(DS_indicator) + 1):\n            node_idx = np.where(DS_indicator == idx)\n            node_idx_list.append(node_idx[0])\n            if len(node_idx[0]) > self.max_num_node:\n                self.max_num_node = len(node_idx[0])\n\n        self.graph_lists = g.subgraphs(node_idx_list)\n        self.num_labels = max(DS_graph_labels) + 1\n        self.graph_labels = DS_graph_labels\n\n        try:\n            DS_node_labels = self._idx_from_zero(\n                np.loadtxt(self._file_path(\"node_labels\"), dtype=int))\n            g.ndata['node_label'] = DS_node_labels\n            one_hot_node_labels = self._to_onehot(DS_node_labels)\n            for idxs, g in zip(node_idx_list, self.graph_lists):\n                g.ndata['feat'] = one_hot_node_labels[idxs, :]\n            self.data_mode = \"node_label\"\n        except IOError:\n            print(\"No Node Label Data\")\n\n        try:\n            DS_node_attr = np.loadtxt(\n                self._file_path(\"node_attributes\"), delimiter=\",\")\n            for idxs, g in zip(node_idx_list, self.graph_lists):\n                g.ndata['feat'] = DS_node_attr[idxs, :]\n            self.data_mode = \"node_attr\"\n        except IOError:\n            print(\"No Node Attribute Data\")\n\n        if 'feat' not in g.ndata.keys():\n            for idxs, g in zip(node_idx_list, self.graph_lists):\n                g.ndata['feat'] = np.ones((g.number_of_nodes(), hidden_size))\n            self.data_mode = \"constant\"\n            print(\n                \"Use Constant one as Feature with hidden size {}\".format(hidden_size))\n\n        # remove graphs that are too large by user given standard\n        # optional pre-processing steop in conformity with Rex Ying's original\n        # DiffPool implementation\n        if self.max_allow_node:\n            preserve_idx = []\n            print(\"original dataset length : \", len(self.graph_lists))\n            for (i, g) in enumerate(self.graph_lists):\n                if g.number_of_nodes() <= self.max_allow_node:\n                    preserve_idx.append(i)\n            self.graph_lists = [self.graph_lists[i] for i in preserve_idx]\n            print(\n                \"after pruning graphs that are too big : \", len(\n                    self.graph_lists))\n            self.graph_labels = [self.graph_labels[i] for i in preserve_idx]\n            self.max_num_node = self.max_allow_node\n\n    def __getitem__(self, idx):\n        \"\"\"Get the i^th sample.\n        Paramters\n        ---------\n        idx : int\n            The sample index.\n        Returns\n        -------\n        (dgl.DGLGraph, int)\n            DGLGraph with node feature stored in `feat` field and node label in `node_label` if available.\n            And its label.\n        \"\"\"\n        g = self.graph_lists[idx]\n        return g, self.graph_labels[idx]\n\n    def __len__(self):\n        return len(self.graph_lists)\n\n    def _download(self):\n        download_dir = get_download_dir()\n        zip_file_path = os.path.join(\n            download_dir,\n            \"tu_{}.zip\".format(\n                self.name))\n        download(self._url.format(self.name), path=zip_file_path)\n        extract_dir = os.path.join(download_dir, \"tu_{}\".format(self.name))\n        extract_archive(zip_file_path, extract_dir)\n        return extract_dir\n\n    def _file_path(self, category):\n        return os.path.join(self.extract_dir, self.name,\n                            \"{}_{}.txt\".format(self.name, category))\n\n    @staticmethod\n    def _idx_from_zero(idx_tensor):\n        return idx_tensor - np.min(idx_tensor)\n\n    @staticmethod\n    def _to_onehot(label_tensor):\n        label_num = label_tensor.shape[0]\n        assert np.min(label_tensor) == 0\n        one_hot_tensor = np.zeros((label_num, np.max(label_tensor) + 1))\n        one_hot_tensor[np.arange(label_num), label_tensor] = 1\n        return one_hot_tensor\n\n    def statistics(self):\n        return self.graph_lists[0].ndata['feat'].shape[1],\\\n            self.num_labels,\\\n            self.max_num_node\n\n\nclass TUDataset(object):\n    \"\"\"\n    TUDataset contains lots of graph kernel datasets for graph classification.\n    Graphs may have node labels, node attributes, edge labels, and edge attributes,\n    varing from different dataset.\n\n    :param name: Dataset Name, such as `ENZYMES`, `DD`, `COLLAB`, `MUTAG`, can be the \n    datasets name on https://ls11-www.cs.tu-dortmund.de/staff/morris/graphkerneldatasets.\n    \"\"\"\n\n    _url = r\"https://ls11-www.cs.tu-dortmund.de/people/morris/graphkerneldatasets/{}.zip\"\n\n    def __init__(self, name):\n\n        self.name = name\n        self.extract_dir = self._download()\n\n        DS_edge_list = self._idx_from_zero(\n            loadtxt(self._file_path(\"A\"), delimiter=\",\").astype(int))\n        DS_indicator = self._idx_from_zero(\n            loadtxt(self._file_path(\"graph_indicator\"), delimiter=\",\").astype(int))\n        DS_graph_labels = self._idx_from_zero(\n            loadtxt(self._file_path(\"graph_labels\"), delimiter=\",\").astype(int))\n\n        g = DGLGraph()\n        g.add_nodes(int(DS_edge_list.max()) + 1)\n        g.add_edges(DS_edge_list[:, 0], DS_edge_list[:, 1])\n\n        node_idx_list = []\n        self.max_num_node = 0\n        for idx in range(np.max(DS_indicator) + 1):\n            node_idx = np.where(DS_indicator == idx)\n            node_idx_list.append(node_idx[0])\n            if len(node_idx[0]) > self.max_num_node:\n                self.max_num_node = len(node_idx[0])\n\n        self.num_labels = max(DS_graph_labels) + 1\n        self.graph_labels = DS_graph_labels\n\n        self.attr_dict = {\n            'node_labels': ('ndata', 'node_labels'),\n            'node_attributes': ('ndata', 'node_attr'),\n            'edge_labels': ('edata', 'edge_labels'),\n            'edge_attributes': ('edata', 'node_labels'),\n        }\n\n        for filename, field_name in self.attr_dict.items():\n            try:\n                data = loadtxt(self._file_path(filename),\n                               delimiter=',').astype(int)\n                if 'label' in filename:\n                    data = self._idx_from_zero(data)\n                getattr(g, field_name[0])[field_name[1]] = data\n            except IOError:\n                pass\n\n        self.graph_lists = g.subgraphs(node_idx_list)\n        for g in self.graph_lists:\n            g.copy_from_parent()\n\n    def __getitem__(self, idx):\n        \"\"\"Get the i^th sample.\n        Paramters\n        ---------\n        idx : int\n            The sample index.\n        Returns\n        -------\n        (dgl.DGLGraph, int)\n            DGLGraph with node feature stored in `feat` field and node label in `node_label` if available.\n            And its label.\n        \"\"\"\n        g = self.graph_lists[idx]\n        return g, self.graph_labels[idx]\n\n    def __len__(self):\n        return len(self.graph_lists)\n\n    def _download(self):\n        download_dir = get_download_dir()\n        zip_file_path = os.path.join(\n            download_dir,\n            \"tu_{}.zip\".format(\n                self.name))\n        download(self._url.format(self.name), path=zip_file_path)\n        extract_dir = os.path.join(download_dir, \"tu_{}\".format(self.name))\n        extract_archive(zip_file_path, extract_dir)\n        return extract_dir\n\n    def _file_path(self, category):\n        return os.path.join(self.extract_dir, self.name,\n                            \"{}_{}.txt\".format(self.name, category))\n\n    @staticmethod\n    def _idx_from_zero(idx_tensor):\n        return idx_tensor - np.min(idx_tensor)\n\n    def statistics(self):\n        return self.graph_lists[0].ndata['feat'].shape[1], \\\n            self.num_labels, \\\n            self.max_num_node\n", "path": "python/dgl/data/tu.py"}], "after_files": [{"content": "from __future__ import absolute_import\nimport numpy as np\nimport os\nimport random\n\nfrom .utils import download, extract_archive, get_download_dir, loadtxt\nfrom ..graph import DGLGraph\n\nclass LegacyTUDataset(object):\n    \"\"\"\n    TUDataset contains lots of graph kernel datasets for graph classification.\n    Use provided node feature by default. If no feature provided, use one-hot node label instead.\n    If neither labels provided, use constant for node feature.\n\n    :param name: Dataset Name, such as `ENZYMES`, `DD`, `COLLAB`\n    :param use_pandas: Default: False.\n        Numpy's file read function has performance issue when file is large,\n        using pandas can be faster.\n    :param hidden_size: Default 10. Some dataset doesn't contain features.\n        Use constant node features initialization instead, with hidden size as `hidden_size`.\n\n    \"\"\"\n\n    _url = r\"https://ls11-www.cs.tu-dortmund.de/people/morris/graphkerneldatasets/{}.zip\"\n\n    def __init__(self, name, use_pandas=False,\n                 hidden_size=10, max_allow_node=None):\n\n        self.name = name\n        self.hidden_size = hidden_size\n        self.extract_dir = self._download()\n        self.data_mode = None\n        self.max_allow_node = max_allow_node\n\n        if use_pandas:\n            import pandas as pd\n            DS_edge_list = self._idx_from_zero(\n                pd.read_csv(self._file_path(\"A\"), delimiter=\",\", dtype=int, header=None).values)\n        else:\n            DS_edge_list = self._idx_from_zero(\n                np.genfromtxt(self._file_path(\"A\"), delimiter=\",\", dtype=int))\n\n        DS_indicator = self._idx_from_zero(\n            np.genfromtxt(self._file_path(\"graph_indicator\"), dtype=int))\n        DS_graph_labels = self._idx_from_zero(\n            np.genfromtxt(self._file_path(\"graph_labels\"), dtype=int))\n\n        g = DGLGraph()\n        g.add_nodes(int(DS_edge_list.max()) + 1)\n        g.add_edges(DS_edge_list[:, 0], DS_edge_list[:, 1])\n\n        node_idx_list = []\n        self.max_num_node = 0\n        for idx in range(np.max(DS_indicator) + 1):\n            node_idx = np.where(DS_indicator == idx)\n            node_idx_list.append(node_idx[0])\n            if len(node_idx[0]) > self.max_num_node:\n                self.max_num_node = len(node_idx[0])\n\n        self.graph_lists = g.subgraphs(node_idx_list)\n        self.num_labels = max(DS_graph_labels) + 1\n        self.graph_labels = DS_graph_labels\n\n        try:\n            DS_node_labels = self._idx_from_zero(\n                np.loadtxt(self._file_path(\"node_labels\"), dtype=int))\n            g.ndata['node_label'] = DS_node_labels\n            one_hot_node_labels = self._to_onehot(DS_node_labels)\n            for idxs, g in zip(node_idx_list, self.graph_lists):\n                g.ndata['feat'] = one_hot_node_labels[idxs, :]\n            self.data_mode = \"node_label\"\n        except IOError:\n            print(\"No Node Label Data\")\n\n        try:\n            DS_node_attr = np.loadtxt(\n                self._file_path(\"node_attributes\"), delimiter=\",\")\n            if DS_node_attr.ndim == 1:\n                DS_node_attr = np.expand_dims(DS_node_attr, -1)\n            for idxs, g in zip(node_idx_list, self.graph_lists):\n                g.ndata['feat'] = DS_node_attr[idxs, :]\n            self.data_mode = \"node_attr\"\n        except IOError:\n            print(\"No Node Attribute Data\")\n\n        if 'feat' not in g.ndata.keys():\n            for idxs, g in zip(node_idx_list, self.graph_lists):\n                g.ndata['feat'] = np.ones((g.number_of_nodes(), hidden_size))\n            self.data_mode = \"constant\"\n            print(\n                \"Use Constant one as Feature with hidden size {}\".format(hidden_size))\n\n        # remove graphs that are too large by user given standard\n        # optional pre-processing steop in conformity with Rex Ying's original\n        # DiffPool implementation\n        if self.max_allow_node:\n            preserve_idx = []\n            print(\"original dataset length : \", len(self.graph_lists))\n            for (i, g) in enumerate(self.graph_lists):\n                if g.number_of_nodes() <= self.max_allow_node:\n                    preserve_idx.append(i)\n            self.graph_lists = [self.graph_lists[i] for i in preserve_idx]\n            print(\n                \"after pruning graphs that are too big : \", len(\n                    self.graph_lists))\n            self.graph_labels = [self.graph_labels[i] for i in preserve_idx]\n            self.max_num_node = self.max_allow_node\n\n    def __getitem__(self, idx):\n        \"\"\"Get the i^th sample.\n        Paramters\n        ---------\n        idx : int\n            The sample index.\n        Returns\n        -------\n        (dgl.DGLGraph, int)\n            DGLGraph with node feature stored in `feat` field and node label in `node_label` if available.\n            And its label.\n        \"\"\"\n        g = self.graph_lists[idx]\n        return g, self.graph_labels[idx]\n\n    def __len__(self):\n        return len(self.graph_lists)\n\n    def _download(self):\n        download_dir = get_download_dir()\n        zip_file_path = os.path.join(\n            download_dir,\n            \"tu_{}.zip\".format(\n                self.name))\n        download(self._url.format(self.name), path=zip_file_path)\n        extract_dir = os.path.join(download_dir, \"tu_{}\".format(self.name))\n        extract_archive(zip_file_path, extract_dir)\n        return extract_dir\n\n    def _file_path(self, category):\n        return os.path.join(self.extract_dir, self.name,\n                            \"{}_{}.txt\".format(self.name, category))\n\n    @staticmethod\n    def _idx_from_zero(idx_tensor):\n        return idx_tensor - np.min(idx_tensor)\n\n    @staticmethod\n    def _to_onehot(label_tensor):\n        label_num = label_tensor.shape[0]\n        assert np.min(label_tensor) == 0\n        one_hot_tensor = np.zeros((label_num, np.max(label_tensor) + 1))\n        one_hot_tensor[np.arange(label_num), label_tensor] = 1\n        return one_hot_tensor\n\n    def statistics(self):\n        return self.graph_lists[0].ndata['feat'].shape[1],\\\n            self.num_labels,\\\n            self.max_num_node\n\n\nclass TUDataset(object):\n    \"\"\"\n    TUDataset contains lots of graph kernel datasets for graph classification.\n    Graphs may have node labels, node attributes, edge labels, and edge attributes,\n    varing from different dataset.\n\n    :param name: Dataset Name, such as `ENZYMES`, `DD`, `COLLAB`, `MUTAG`, can be the \n    datasets name on https://ls11-www.cs.tu-dortmund.de/staff/morris/graphkerneldatasets.\n    \"\"\"\n\n    _url = r\"https://ls11-www.cs.tu-dortmund.de/people/morris/graphkerneldatasets/{}.zip\"\n\n    def __init__(self, name):\n\n        self.name = name\n        self.extract_dir = self._download()\n\n        DS_edge_list = self._idx_from_zero(\n            loadtxt(self._file_path(\"A\"), delimiter=\",\").astype(int))\n        DS_indicator = self._idx_from_zero(\n            loadtxt(self._file_path(\"graph_indicator\"), delimiter=\",\").astype(int))\n        DS_graph_labels = self._idx_from_zero(\n            loadtxt(self._file_path(\"graph_labels\"), delimiter=\",\").astype(int))\n\n        g = DGLGraph()\n        g.add_nodes(int(DS_edge_list.max()) + 1)\n        g.add_edges(DS_edge_list[:, 0], DS_edge_list[:, 1])\n\n        node_idx_list = []\n        self.max_num_node = 0\n        for idx in range(np.max(DS_indicator) + 1):\n            node_idx = np.where(DS_indicator == idx)\n            node_idx_list.append(node_idx[0])\n            if len(node_idx[0]) > self.max_num_node:\n                self.max_num_node = len(node_idx[0])\n\n        self.num_labels = max(DS_graph_labels) + 1\n        self.graph_labels = DS_graph_labels\n\n        self.attr_dict = {\n            'node_labels': ('ndata', 'node_labels'),\n            'node_attributes': ('ndata', 'node_attr'),\n            'edge_labels': ('edata', 'edge_labels'),\n            'edge_attributes': ('edata', 'node_labels'),\n        }\n\n        for filename, field_name in self.attr_dict.items():\n            try:\n                data = loadtxt(self._file_path(filename),\n                               delimiter=',').astype(int)\n                if 'label' in filename:\n                    data = self._idx_from_zero(data)\n                getattr(g, field_name[0])[field_name[1]] = data\n            except IOError:\n                pass\n\n        self.graph_lists = g.subgraphs(node_idx_list)\n        for g in self.graph_lists:\n            g.copy_from_parent()\n\n    def __getitem__(self, idx):\n        \"\"\"Get the i^th sample.\n        Paramters\n        ---------\n        idx : int\n            The sample index.\n        Returns\n        -------\n        (dgl.DGLGraph, int)\n            DGLGraph with node feature stored in `feat` field and node label in `node_label` if available.\n            And its label.\n        \"\"\"\n        g = self.graph_lists[idx]\n        return g, self.graph_labels[idx]\n\n    def __len__(self):\n        return len(self.graph_lists)\n\n    def _download(self):\n        download_dir = get_download_dir()\n        zip_file_path = os.path.join(\n            download_dir,\n            \"tu_{}.zip\".format(\n                self.name))\n        download(self._url.format(self.name), path=zip_file_path)\n        extract_dir = os.path.join(download_dir, \"tu_{}\".format(self.name))\n        extract_archive(zip_file_path, extract_dir)\n        return extract_dir\n\n    def _file_path(self, category):\n        return os.path.join(self.extract_dir, self.name,\n                            \"{}_{}.txt\".format(self.name, category))\n\n    @staticmethod\n    def _idx_from_zero(idx_tensor):\n        return idx_tensor - np.min(idx_tensor)\n\n    def statistics(self):\n        return self.graph_lists[0].ndata['feat'].shape[1], \\\n            self.num_labels, \\\n            self.max_num_node\n", "path": "python/dgl/data/tu.py"}]}