We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Complete engines.rst sphinx package reference


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `ignite/engines/engine.py`
Content:
```
1 import logging
2 import time
3 from enum import Enum
4 
5 from ignite._utils import _to_hours_mins_secs
6 
7 
8 class Events(Enum):
9     EPOCH_STARTED = "epoch_started"
10     EPOCH_COMPLETED = "epoch_completed"
11     STARTED = "started"
12     COMPLETED = "completed"
13     ITERATION_STARTED = "iteration_started"
14     ITERATION_COMPLETED = "iteration_completed"
15     EXCEPTION_RAISED = "exception_raised"
16 
17 
18 class State(object):
19     def __init__(self, **kwargs):
20         self.iteration = 0
21         self.output = None
22         self.batch = None
23         for k, v in kwargs.items():
24             setattr(self, k, v)
25 
26 
27 class Engine(object):
28     """Runs a given process_function over each batch of a dataset, emitting events as it goes.
29 
30     Args:
31         process_function (Callable): A function receiving a handle to the engine and the current batch
32             in each iteration, outputing data to be stored in the state
33 
34     """
35     def __init__(self, process_function):
36         self._event_handlers = {}
37         self._logger = logging.getLogger(__name__ + "." + self.__class__.__name__)
38         self._logger.addHandler(logging.NullHandler())
39         self._process_function = process_function
40         self.should_terminate = False
41         self.state = None
42 
43         if self._process_function is None:
44             raise ValueError("Engine must be given a processing function in order to run")
45 
46     def add_event_handler(self, event_name, handler, *args, **kwargs):
47         """Add an event handler to be executed when the specified event is fired
48 
49         Args:
50             event_name (Events): event from ignite.engines.Events to attach the handler to
51             handler (Callable): the callable event handler that should be invoked
52             *args: optional args to be passed to `handler`
53             **kwargs: optional keyword args to be passed to `handler`
54 
55         """
56         if event_name not in Events.__members__.values():
57             self._logger.error("attempt to add event handler to an invalid event %s ", event_name)
58             raise ValueError("Event {} is not a valid event for this Engine".format(event_name))
59 
60         if event_name not in self._event_handlers:
61             self._event_handlers[event_name] = []
62 
63         self._event_handlers[event_name].append((handler, args, kwargs))
64         self._logger.debug("added handler for event %s ", event_name)
65 
66     def on(self, event_name, *args, **kwargs):
67         """Decorator shortcut for add_event_handler
68 
69         Args:
70             event_name (Events): event to attach the handler to
71             *args: optional args to be passed to `handler`
72             **kwargs: optional keyword args to be passed to `handler`
73 
74         """
75         def decorator(f):
76             self.add_event_handler(event_name, f, *args, **kwargs)
77             return f
78         return decorator
79 
80     def _fire_event(self, event_name, *event_args):
81         if event_name in self._event_handlers.keys():
82             self._logger.debug("firing handlers for event %s ", event_name)
83             for func, args, kwargs in self._event_handlers[event_name]:
84                 func(self, *(event_args + args), **kwargs)
85 
86     def terminate(self):
87         """Sends terminate signal to the engine, so that it terminates after the current iteration
88         """
89         self._logger.info("Terminate signaled. Engine will stop after current iteration is finished")
90         self.should_terminate = True
91 
92     def _run_once_on_dataset(self):
93         try:
94             start_time = time.time()
95             for batch in self.state.dataloader:
96                 self.state.batch = batch
97                 self.state.iteration += 1
98                 self._fire_event(Events.ITERATION_STARTED)
99                 self.state.output = self._process_function(self, batch)
100                 self._fire_event(Events.ITERATION_COMPLETED)
101                 if self.should_terminate:
102                     break
103 
104             time_taken = time.time() - start_time
105             hours, mins, secs = _to_hours_mins_secs(time_taken)
106             return hours, mins, secs
107         except BaseException as e:
108             self._logger.error("Current run is terminating due to exception: %s", str(e))
109             self._handle_exception(e)
110 
111     def _handle_exception(self, e):
112         if Events.EXCEPTION_RAISED in self._event_handlers:
113             self._fire_event(Events.EXCEPTION_RAISED, e)
114         else:
115             raise e
116 
117     def run(self, data, max_epochs=1):
118         """Runs the process_function over the passed data.
119 
120         Args:
121             data (Iterable): Collection of batches allowing repeated iteration (e.g., list or DataLoader)
122             max_epochs (int, optional): max epochs to run for (default: 1)
123 
124         Returns:
125             State: output state
126         """
127         self.state = State(dataloader=data, epoch=0, max_epochs=max_epochs, metrics={})
128 
129         try:
130             self._logger.info("Training starting with max_epochs={}".format(max_epochs))
131             start_time = time.time()
132             self._fire_event(Events.STARTED)
133             while self.state.epoch < max_epochs and not self.should_terminate:
134                 self.state.epoch += 1
135                 self._fire_event(Events.EPOCH_STARTED)
136                 hours, mins, secs = self._run_once_on_dataset()
137                 self._logger.info("Epoch[%s] Complete. Time taken: %02d:%02d:%02d", self.state.epoch, hours, mins, secs)
138                 if self.should_terminate:
139                     break
140                 self._fire_event(Events.EPOCH_COMPLETED)
141 
142             self._fire_event(Events.COMPLETED)
143             time_taken = time.time() - start_time
144             hours, mins, secs = _to_hours_mins_secs(time_taken)
145             self._logger.info("Training complete. Time taken %02d:%02d:%02d" % (hours, mins, secs))
146 
147         except BaseException as e:
148             self._logger.error("Training is terminating due to exception: %s", str(e))
149             self._handle_exception(e)
150 
151         return self.state
152
```

Path: `docs/source/conf.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 #
3 # Configuration file for the Sphinx documentation builder.
4 #
5 # This file does only contain a selection of the most common options. For a
6 # full list see the documentation:
7 # http://www.sphinx-doc.org/en/stable/config
8 
9 # -- Path setup --------------------------------------------------------------
10 
11 # If extensions (or modules to document with autodoc) are in another directory,
12 # add these directories to sys.path here. If the directory is relative to the
13 # documentation root, use os.path.abspath to make it absolute, like shown here.
14 #
15 # import os
16 # import sys
17 # sys.path.insert(0, os.path.abspath('.'))
18 import ignite
19 import sphinx_rtd_theme
20 
21 # -- Project information -----------------------------------------------------
22 
23 project = 'ignite'
24 copyright = '2018, Torch Contributors'
25 author = 'Torch Contributors'
26 
27 # The short X.Y version
28 version = 'master (' + ignite.__version__ + ' )'
29 # The full version, including alpha/beta/rc tags
30 release = 'master'
31 
32 
33 # -- General configuration ---------------------------------------------------
34 
35 # If your documentation needs a minimal Sphinx version, state it here.
36 #
37 # needs_sphinx = '1.0'
38 
39 # Add any Sphinx extension module names here, as strings. They can be
40 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
41 # ones.
42 extensions = [
43     'sphinx.ext.autodoc',
44     'sphinx.ext.doctest',
45     'sphinx.ext.intersphinx',
46     'sphinx.ext.todo',
47     'sphinx.ext.mathjax',
48     'sphinx.ext.viewcode',
49 ]
50 
51 # Add any paths that contain templates here, relative to this directory.
52 templates_path = ['_templates']
53 
54 # The suffix(es) of source filenames.
55 # You can specify multiple suffix as a list of string:
56 #
57 # source_suffix = ['.rst', '.md']
58 source_suffix = '.rst'
59 
60 # The master toctree document.
61 master_doc = 'index'
62 
63 # The language for content autogenerated by Sphinx. Refer to documentation
64 # for a list of supported languages.
65 #
66 # This is also used if you do content translation via gettext catalogs.
67 # Usually you set "language" from the command line for these cases.
68 language = None
69 
70 # List of patterns, relative to source directory, that match files and
71 # directories to ignore when looking for source files.
72 # This pattern also affects html_static_path and html_extra_path .
73 exclude_patterns = []
74 
75 # The name of the Pygments (syntax highlighting) style to use.
76 pygments_style = 'sphinx'
77 
78 
79 # -- Options for HTML output -------------------------------------------------
80 
81 # The theme to use for HTML and HTML Help pages.  See the documentation for
82 # a list of builtin themes.
83 #
84 html_theme = 'sphinx_rtd_theme'
85 html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
86 
87 html_theme_options = {
88     'collapse_navigation': False,
89     'display_version': True,
90     'logo_only': True,
91 }
92 
93 html_logo = '_static/img/pytorch-logo-dark.svg'
94 
95 # Theme options are theme-specific and customize the look and feel of a theme
96 # further.  For a list of options available for each theme, see the
97 # documentation.
98 #
99 # html_theme_options = {}
100 
101 # Add any paths that contain custom static files (such as style sheets) here,
102 # relative to this directory. They are copied after the builtin static files,
103 # so a file named "default.css" will overwrite the builtin "default.css".
104 html_static_path = ['_static']
105 
106 html_context = {
107     'css_files': [
108         'https://fonts.googleapis.com/css?family=Lato',
109         '_static/css/pytorch_theme.css'
110     ],
111 }
112 
113 
114 # -- Options for HTMLHelp output ---------------------------------------------
115 
116 # Output file base name for HTML help builder.
117 htmlhelp_basename = 'ignitedoc'
118 
119 
120 # -- Options for LaTeX output ------------------------------------------------
121 
122 latex_elements = {
123     # The paper size ('letterpaper' or 'a4paper').
124     #
125     # 'papersize': 'letterpaper',
126 
127     # The font size ('10pt', '11pt' or '12pt').
128     #
129     # 'pointsize': '10pt',
130 
131     # Additional stuff for the LaTeX preamble.
132     #
133     # 'preamble': '',
134 
135     # Latex figure (float) alignment
136     #
137     # 'figure_align': 'htbp',
138 }
139 
140 # Grouping the document tree into LaTeX files. List of tuples
141 # (source start file, target name, title,
142 #  author, documentclass [howto, manual, or own class]).
143 latex_documents = [
144     (master_doc, 'ignite.tex', 'ignite Documentation',
145      'Torch Contributors', 'manual'),
146 ]
147 
148 
149 # -- Options for manual page output ------------------------------------------
150 
151 # One entry per manual page. List of tuples
152 # (source start file, name, description, authors, manual section).
153 man_pages = [
154     (master_doc, 'ignite', 'ignite Documentation',
155      [author], 1)
156 ]
157 
158 
159 # -- Options for Texinfo output ----------------------------------------------
160 
161 # Grouping the document tree into Texinfo files. List of tuples
162 # (source start file, target name, title, author,
163 #  dir menu entry, description, category)
164 texinfo_documents = [
165     (master_doc, 'ignite', 'ignite Documentation',
166      author, 'ignite', 'One line description of project.',
167      'Miscellaneous'),
168 ]
169 
170 
171 # -- Extension configuration -------------------------------------------------
172 
173 # -- Options for intersphinx extension ---------------------------------------
174 
175 # Example configuration for intersphinx: refer to the Python standard library.
176 intersphinx_mapping = {'https://docs.python.org/': None}
177 
178 # -- Options for todo extension ----------------------------------------------
179 
180 # If true, `todo` and `todoList` produce output, else they produce nothing.
181 todo_include_todos = True
182
```
--- 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/docs/source/conf.py b/docs/source/conf.py
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -40,12 +40,14 @@
 # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
 # ones.
 extensions = [
-    'sphinx.ext.autodoc',
+    'sphinx.ext.autosummary',
     'sphinx.ext.doctest',
     'sphinx.ext.intersphinx',
     'sphinx.ext.todo',
+    'sphinx.ext.coverage',
     'sphinx.ext.mathjax',
-    'sphinx.ext.viewcode',
+    'sphinx.ext.napoleon',
+    'sphinx.ext.viewcode'
 ]
 
 # Add any paths that contain templates here, relative to this directory.
diff --git a/ignite/engines/engine.py b/ignite/engines/engine.py
--- a/ignite/engines/engine.py
+++ b/ignite/engines/engine.py
@@ -6,6 +6,7 @@
 
 
 class Events(Enum):
+    """Events that are fired by the :class:`ignite.engines.Engine` during execution"""
     EPOCH_STARTED = "epoch_started"
     EPOCH_COMPLETED = "epoch_completed"
     STARTED = "started"
@@ -16,6 +17,7 @@
 
 
 class State(object):
+    """An object that is used to pass internal and user-defined state between event handlers"""
     def __init__(self, **kwargs):
         self.iteration = 0
         self.output = None

{"golden_diff": "diff --git a/docs/source/conf.py b/docs/source/conf.py\n--- a/docs/source/conf.py\n+++ b/docs/source/conf.py\n@@ -40,12 +40,14 @@\n # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n # ones.\n extensions = [\n-    'sphinx.ext.autodoc',\n+    'sphinx.ext.autosummary',\n     'sphinx.ext.doctest',\n     'sphinx.ext.intersphinx',\n     'sphinx.ext.todo',\n+    'sphinx.ext.coverage',\n     'sphinx.ext.mathjax',\n-    'sphinx.ext.viewcode',\n+    'sphinx.ext.napoleon',\n+    'sphinx.ext.viewcode'\n ]\n \n # Add any paths that contain templates here, relative to this directory.\ndiff --git a/ignite/engines/engine.py b/ignite/engines/engine.py\n--- a/ignite/engines/engine.py\n+++ b/ignite/engines/engine.py\n@@ -6,6 +6,7 @@\n \n \n class Events(Enum):\n+    \"\"\"Events that are fired by the :class:`ignite.engines.Engine` during execution\"\"\"\n     EPOCH_STARTED = \"epoch_started\"\n     EPOCH_COMPLETED = \"epoch_completed\"\n     STARTED = \"started\"\n@@ -16,6 +17,7 @@\n \n \n class State(object):\n+    \"\"\"An object that is used to pass internal and user-defined state between event handlers\"\"\"\n     def __init__(self, **kwargs):\n         self.iteration = 0\n         self.output = None\n", "issue": "Complete engines.rst sphinx package reference\n\n", "before_files": [{"content": "import logging\nimport time\nfrom enum import Enum\n\nfrom ignite._utils import _to_hours_mins_secs\n\n\nclass Events(Enum):\n    EPOCH_STARTED = \"epoch_started\"\n    EPOCH_COMPLETED = \"epoch_completed\"\n    STARTED = \"started\"\n    COMPLETED = \"completed\"\n    ITERATION_STARTED = \"iteration_started\"\n    ITERATION_COMPLETED = \"iteration_completed\"\n    EXCEPTION_RAISED = \"exception_raised\"\n\n\nclass State(object):\n    def __init__(self, **kwargs):\n        self.iteration = 0\n        self.output = None\n        self.batch = None\n        for k, v in kwargs.items():\n            setattr(self, k, v)\n\n\nclass Engine(object):\n    \"\"\"Runs a given process_function over each batch of a dataset, emitting events as it goes.\n\n    Args:\n        process_function (Callable): A function receiving a handle to the engine and the current batch\n            in each iteration, outputing data to be stored in the state\n\n    \"\"\"\n    def __init__(self, process_function):\n        self._event_handlers = {}\n        self._logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\n        self._logger.addHandler(logging.NullHandler())\n        self._process_function = process_function\n        self.should_terminate = False\n        self.state = None\n\n        if self._process_function is None:\n            raise ValueError(\"Engine must be given a processing function in order to run\")\n\n    def add_event_handler(self, event_name, handler, *args, **kwargs):\n        \"\"\"Add an event handler to be executed when the specified event is fired\n\n        Args:\n            event_name (Events): event from ignite.engines.Events to attach the handler to\n            handler (Callable): the callable event handler that should be invoked\n            *args: optional args to be passed to `handler`\n            **kwargs: optional keyword args to be passed to `handler`\n\n        \"\"\"\n        if event_name not in Events.__members__.values():\n            self._logger.error(\"attempt to add event handler to an invalid event %s \", event_name)\n            raise ValueError(\"Event {} is not a valid event for this Engine\".format(event_name))\n\n        if event_name not in self._event_handlers:\n            self._event_handlers[event_name] = []\n\n        self._event_handlers[event_name].append((handler, args, kwargs))\n        self._logger.debug(\"added handler for event %s \", event_name)\n\n    def on(self, event_name, *args, **kwargs):\n        \"\"\"Decorator shortcut for add_event_handler\n\n        Args:\n            event_name (Events): event to attach the handler to\n            *args: optional args to be passed to `handler`\n            **kwargs: optional keyword args to be passed to `handler`\n\n        \"\"\"\n        def decorator(f):\n            self.add_event_handler(event_name, f, *args, **kwargs)\n            return f\n        return decorator\n\n    def _fire_event(self, event_name, *event_args):\n        if event_name in self._event_handlers.keys():\n            self._logger.debug(\"firing handlers for event %s \", event_name)\n            for func, args, kwargs in self._event_handlers[event_name]:\n                func(self, *(event_args + args), **kwargs)\n\n    def terminate(self):\n        \"\"\"Sends terminate signal to the engine, so that it terminates after the current iteration\n        \"\"\"\n        self._logger.info(\"Terminate signaled. Engine will stop after current iteration is finished\")\n        self.should_terminate = True\n\n    def _run_once_on_dataset(self):\n        try:\n            start_time = time.time()\n            for batch in self.state.dataloader:\n                self.state.batch = batch\n                self.state.iteration += 1\n                self._fire_event(Events.ITERATION_STARTED)\n                self.state.output = self._process_function(self, batch)\n                self._fire_event(Events.ITERATION_COMPLETED)\n                if self.should_terminate:\n                    break\n\n            time_taken = time.time() - start_time\n            hours, mins, secs = _to_hours_mins_secs(time_taken)\n            return hours, mins, secs\n        except BaseException as e:\n            self._logger.error(\"Current run is terminating due to exception: %s\", str(e))\n            self._handle_exception(e)\n\n    def _handle_exception(self, e):\n        if Events.EXCEPTION_RAISED in self._event_handlers:\n            self._fire_event(Events.EXCEPTION_RAISED, e)\n        else:\n            raise e\n\n    def run(self, data, max_epochs=1):\n        \"\"\"Runs the process_function over the passed data.\n\n        Args:\n            data (Iterable): Collection of batches allowing repeated iteration (e.g., list or DataLoader)\n            max_epochs (int, optional): max epochs to run for (default: 1)\n\n        Returns:\n            State: output state\n        \"\"\"\n        self.state = State(dataloader=data, epoch=0, max_epochs=max_epochs, metrics={})\n\n        try:\n            self._logger.info(\"Training starting with max_epochs={}\".format(max_epochs))\n            start_time = time.time()\n            self._fire_event(Events.STARTED)\n            while self.state.epoch < max_epochs and not self.should_terminate:\n                self.state.epoch += 1\n                self._fire_event(Events.EPOCH_STARTED)\n                hours, mins, secs = self._run_once_on_dataset()\n                self._logger.info(\"Epoch[%s] Complete. Time taken: %02d:%02d:%02d\", self.state.epoch, hours, mins, secs)\n                if self.should_terminate:\n                    break\n                self._fire_event(Events.EPOCH_COMPLETED)\n\n            self._fire_event(Events.COMPLETED)\n            time_taken = time.time() - start_time\n            hours, mins, secs = _to_hours_mins_secs(time_taken)\n            self._logger.info(\"Training complete. Time taken %02d:%02d:%02d\" % (hours, mins, secs))\n\n        except BaseException as e:\n            self._logger.error(\"Training is terminating due to exception: %s\", str(e))\n            self._handle_exception(e)\n\n        return self.state\n", "path": "ignite/engines/engine.py"}, {"content": "# -*- coding: utf-8 -*-\n#\n# Configuration file for the Sphinx documentation builder.\n#\n# This file does only contain a selection of the most common options. For a\n# full list see the documentation:\n# http://www.sphinx-doc.org/en/stable/config\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\nimport ignite\nimport sphinx_rtd_theme\n\n# -- Project information -----------------------------------------------------\n\nproject = 'ignite'\ncopyright = '2018, Torch Contributors'\nauthor = 'Torch Contributors'\n\n# The short X.Y version\nversion = 'master (' + ignite.__version__ + ' )'\n# The full version, including alpha/beta/rc tags\nrelease = 'master'\n\n\n# -- General configuration ---------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n    'sphinx.ext.autodoc',\n    'sphinx.ext.doctest',\n    'sphinx.ext.intersphinx',\n    'sphinx.ext.todo',\n    'sphinx.ext.mathjax',\n    'sphinx.ext.viewcode',\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path .\nexclude_patterns = []\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'sphinx_rtd_theme'\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\nhtml_theme_options = {\n    'collapse_navigation': False,\n    'display_version': True,\n    'logo_only': True,\n}\n\nhtml_logo = '_static/img/pytorch-logo-dark.svg'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\nhtml_context = {\n    'css_files': [\n        'https://fonts.googleapis.com/css?family=Lato',\n        '_static/css/pytorch_theme.css'\n    ],\n}\n\n\n# -- Options for HTMLHelp output ---------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'ignitedoc'\n\n\n# -- Options for LaTeX output ------------------------------------------------\n\nlatex_elements = {\n    # The paper size ('letterpaper' or 'a4paper').\n    #\n    # 'papersize': 'letterpaper',\n\n    # The font size ('10pt', '11pt' or '12pt').\n    #\n    # 'pointsize': '10pt',\n\n    # Additional stuff for the LaTeX preamble.\n    #\n    # 'preamble': '',\n\n    # Latex figure (float) alignment\n    #\n    # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n    (master_doc, 'ignite.tex', 'ignite Documentation',\n     'Torch Contributors', 'manual'),\n]\n\n\n# -- Options for manual page output ------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n    (master_doc, 'ignite', 'ignite Documentation',\n     [author], 1)\n]\n\n\n# -- Options for Texinfo output ----------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n    (master_doc, 'ignite', 'ignite Documentation',\n     author, 'ignite', 'One line description of project.',\n     'Miscellaneous'),\n]\n\n\n# -- Extension configuration -------------------------------------------------\n\n# -- Options for intersphinx extension ---------------------------------------\n\n# Example configuration for intersphinx: refer to the Python standard library.\nintersphinx_mapping = {'https://docs.python.org/': None}\n\n# -- Options for todo extension ----------------------------------------------\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n", "path": "docs/source/conf.py"}], "after_files": [{"content": "import logging\nimport time\nfrom enum import Enum\n\nfrom ignite._utils import _to_hours_mins_secs\n\n\nclass Events(Enum):\n    \"\"\"Events that are fired by the :class:`ignite.engines.Engine` during execution\"\"\"\n    EPOCH_STARTED = \"epoch_started\"\n    EPOCH_COMPLETED = \"epoch_completed\"\n    STARTED = \"started\"\n    COMPLETED = \"completed\"\n    ITERATION_STARTED = \"iteration_started\"\n    ITERATION_COMPLETED = \"iteration_completed\"\n    EXCEPTION_RAISED = \"exception_raised\"\n\n\nclass State(object):\n    \"\"\"An object that is used to pass internal and user-defined state between event handlers\"\"\"\n    def __init__(self, **kwargs):\n        self.iteration = 0\n        self.output = None\n        self.batch = None\n        for k, v in kwargs.items():\n            setattr(self, k, v)\n\n\nclass Engine(object):\n    \"\"\"Runs a given process_function over each batch of a dataset, emitting events as it goes.\n\n    Args:\n        process_function (Callable): A function receiving a handle to the engine and the current batch\n            in each iteration, outputing data to be stored in the state\n\n    \"\"\"\n    def __init__(self, process_function):\n        self._event_handlers = {}\n        self._logger = logging.getLogger(__name__ + \".\" + self.__class__.__name__)\n        self._logger.addHandler(logging.NullHandler())\n        self._process_function = process_function\n        self.should_terminate = False\n        self.state = None\n\n        if self._process_function is None:\n            raise ValueError(\"Engine must be given a processing function in order to run\")\n\n    def add_event_handler(self, event_name, handler, *args, **kwargs):\n        \"\"\"Add an event handler to be executed when the specified event is fired\n\n        Args:\n            event_name (Events): event from ignite.engines.Events to attach the handler to\n            handler (Callable): the callable event handler that should be invoked\n            *args: optional args to be passed to `handler`\n            **kwargs: optional keyword args to be passed to `handler`\n\n        \"\"\"\n        if event_name not in Events.__members__.values():\n            self._logger.error(\"attempt to add event handler to an invalid event %s \", event_name)\n            raise ValueError(\"Event {} is not a valid event for this Engine\".format(event_name))\n\n        if event_name not in self._event_handlers:\n            self._event_handlers[event_name] = []\n\n        self._event_handlers[event_name].append((handler, args, kwargs))\n        self._logger.debug(\"added handler for event %s \", event_name)\n\n    def on(self, event_name, *args, **kwargs):\n        \"\"\"Decorator shortcut for add_event_handler\n\n        Args:\n            event_name (Events): event to attach the handler to\n            *args: optional args to be passed to `handler`\n            **kwargs: optional keyword args to be passed to `handler`\n\n        \"\"\"\n        def decorator(f):\n            self.add_event_handler(event_name, f, *args, **kwargs)\n            return f\n        return decorator\n\n    def _fire_event(self, event_name, *event_args):\n        if event_name in self._event_handlers.keys():\n            self._logger.debug(\"firing handlers for event %s \", event_name)\n            for func, args, kwargs in self._event_handlers[event_name]:\n                func(self, *(event_args + args), **kwargs)\n\n    def terminate(self):\n        \"\"\"Sends terminate signal to the engine, so that it terminates after the current iteration\n        \"\"\"\n        self._logger.info(\"Terminate signaled. Engine will stop after current iteration is finished\")\n        self.should_terminate = True\n\n    def _run_once_on_dataset(self):\n        try:\n            start_time = time.time()\n            for batch in self.state.dataloader:\n                self.state.batch = batch\n                self.state.iteration += 1\n                self._fire_event(Events.ITERATION_STARTED)\n                self.state.output = self._process_function(self, batch)\n                self._fire_event(Events.ITERATION_COMPLETED)\n                if self.should_terminate:\n                    break\n\n            time_taken = time.time() - start_time\n            hours, mins, secs = _to_hours_mins_secs(time_taken)\n            return hours, mins, secs\n        except BaseException as e:\n            self._logger.error(\"Current run is terminating due to exception: %s\", str(e))\n            self._handle_exception(e)\n\n    def _handle_exception(self, e):\n        if Events.EXCEPTION_RAISED in self._event_handlers:\n            self._fire_event(Events.EXCEPTION_RAISED, e)\n        else:\n            raise e\n\n    def run(self, data, max_epochs=1):\n        \"\"\"Runs the process_function over the passed data.\n\n        Args:\n            data (Iterable): Collection of batches allowing repeated iteration (e.g., list or DataLoader)\n            max_epochs (int, optional): max epochs to run for (default: 1)\n\n        Returns:\n            State: output state\n        \"\"\"\n        self.state = State(dataloader=data, epoch=0, max_epochs=max_epochs, metrics={})\n\n        try:\n            self._logger.info(\"Training starting with max_epochs={}\".format(max_epochs))\n            start_time = time.time()\n            self._fire_event(Events.STARTED)\n            while self.state.epoch < max_epochs and not self.should_terminate:\n                self.state.epoch += 1\n                self._fire_event(Events.EPOCH_STARTED)\n                hours, mins, secs = self._run_once_on_dataset()\n                self._logger.info(\"Epoch[%s] Complete. Time taken: %02d:%02d:%02d\", self.state.epoch, hours, mins, secs)\n                if self.should_terminate:\n                    break\n                self._fire_event(Events.EPOCH_COMPLETED)\n\n            self._fire_event(Events.COMPLETED)\n            time_taken = time.time() - start_time\n            hours, mins, secs = _to_hours_mins_secs(time_taken)\n            self._logger.info(\"Training complete. Time taken %02d:%02d:%02d\" % (hours, mins, secs))\n\n        except BaseException as e:\n            self._logger.error(\"Training is terminating due to exception: %s\", str(e))\n            self._handle_exception(e)\n\n        return self.state\n", "path": "ignite/engines/engine.py"}, {"content": "# -*- coding: utf-8 -*-\n#\n# Configuration file for the Sphinx documentation builder.\n#\n# This file does only contain a selection of the most common options. For a\n# full list see the documentation:\n# http://www.sphinx-doc.org/en/stable/config\n\n# -- Path setup --------------------------------------------------------------\n\n# If extensions (or modules to document with autodoc) are in another directory,\n# add these directories to sys.path here. If the directory is relative to the\n# documentation root, use os.path.abspath to make it absolute, like shown here.\n#\n# import os\n# import sys\n# sys.path.insert(0, os.path.abspath('.'))\nimport ignite\nimport sphinx_rtd_theme\n\n# -- Project information -----------------------------------------------------\n\nproject = 'ignite'\ncopyright = '2018, Torch Contributors'\nauthor = 'Torch Contributors'\n\n# The short X.Y version\nversion = 'master (' + ignite.__version__ + ' )'\n# The full version, including alpha/beta/rc tags\nrelease = 'master'\n\n\n# -- General configuration ---------------------------------------------------\n\n# If your documentation needs a minimal Sphinx version, state it here.\n#\n# needs_sphinx = '1.0'\n\n# Add any Sphinx extension module names here, as strings. They can be\n# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom\n# ones.\nextensions = [\n    'sphinx.ext.autosummary',\n    'sphinx.ext.doctest',\n    'sphinx.ext.intersphinx',\n    'sphinx.ext.todo',\n    'sphinx.ext.coverage',\n    'sphinx.ext.mathjax',\n    'sphinx.ext.napoleon',\n    'sphinx.ext.viewcode'\n]\n\n# Add any paths that contain templates here, relative to this directory.\ntemplates_path = ['_templates']\n\n# The suffix(es) of source filenames.\n# You can specify multiple suffix as a list of string:\n#\n# source_suffix = ['.rst', '.md']\nsource_suffix = '.rst'\n\n# The master toctree document.\nmaster_doc = 'index'\n\n# The language for content autogenerated by Sphinx. Refer to documentation\n# for a list of supported languages.\n#\n# This is also used if you do content translation via gettext catalogs.\n# Usually you set \"language\" from the command line for these cases.\nlanguage = None\n\n# List of patterns, relative to source directory, that match files and\n# directories to ignore when looking for source files.\n# This pattern also affects html_static_path and html_extra_path .\nexclude_patterns = []\n\n# The name of the Pygments (syntax highlighting) style to use.\npygments_style = 'sphinx'\n\n\n# -- Options for HTML output -------------------------------------------------\n\n# The theme to use for HTML and HTML Help pages.  See the documentation for\n# a list of builtin themes.\n#\nhtml_theme = 'sphinx_rtd_theme'\nhtml_theme_path = [sphinx_rtd_theme.get_html_theme_path()]\n\nhtml_theme_options = {\n    'collapse_navigation': False,\n    'display_version': True,\n    'logo_only': True,\n}\n\nhtml_logo = '_static/img/pytorch-logo-dark.svg'\n\n# Theme options are theme-specific and customize the look and feel of a theme\n# further.  For a list of options available for each theme, see the\n# documentation.\n#\n# html_theme_options = {}\n\n# Add any paths that contain custom static files (such as style sheets) here,\n# relative to this directory. They are copied after the builtin static files,\n# so a file named \"default.css\" will overwrite the builtin \"default.css\".\nhtml_static_path = ['_static']\n\nhtml_context = {\n    'css_files': [\n        'https://fonts.googleapis.com/css?family=Lato',\n        '_static/css/pytorch_theme.css'\n    ],\n}\n\n\n# -- Options for HTMLHelp output ---------------------------------------------\n\n# Output file base name for HTML help builder.\nhtmlhelp_basename = 'ignitedoc'\n\n\n# -- Options for LaTeX output ------------------------------------------------\n\nlatex_elements = {\n    # The paper size ('letterpaper' or 'a4paper').\n    #\n    # 'papersize': 'letterpaper',\n\n    # The font size ('10pt', '11pt' or '12pt').\n    #\n    # 'pointsize': '10pt',\n\n    # Additional stuff for the LaTeX preamble.\n    #\n    # 'preamble': '',\n\n    # Latex figure (float) alignment\n    #\n    # 'figure_align': 'htbp',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n#  author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n    (master_doc, 'ignite.tex', 'ignite Documentation',\n     'Torch Contributors', 'manual'),\n]\n\n\n# -- Options for manual page output ------------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n    (master_doc, 'ignite', 'ignite Documentation',\n     [author], 1)\n]\n\n\n# -- Options for Texinfo output ----------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n#  dir menu entry, description, category)\ntexinfo_documents = [\n    (master_doc, 'ignite', 'ignite Documentation',\n     author, 'ignite', 'One line description of project.',\n     'Miscellaneous'),\n]\n\n\n# -- Extension configuration -------------------------------------------------\n\n# -- Options for intersphinx extension ---------------------------------------\n\n# Example configuration for intersphinx: refer to the Python standard library.\nintersphinx_mapping = {'https://docs.python.org/': None}\n\n# -- Options for todo extension ----------------------------------------------\n\n# If true, `todo` and `todoList` produce output, else they produce nothing.\ntodo_include_todos = True\n", "path": "docs/source/conf.py"}]}