-
Notifications
You must be signed in to change notification settings - Fork 2.4k
/
parallel.py
148 lines (125 loc) · 5.99 KB
/
parallel.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
# This file is part of QuTiP: Quantum Toolbox in Python.
#
# Copyright (c) 2011 and later, Paul D. Nation and Robert J. Johansson.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the QuTiP: Quantum Toolbox in Python nor the names
# of its contributors may be used to endorse or promote products derived
# from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
# PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
###############################################################################
"""
Routines for running Python functions in parallel using process pools
from the multiprocessing library.
"""
import os
import platform
from concurrent.futures import ProcessPoolExecutor
from qiskit.exceptions import QiskitError
from qiskit.util import local_hardware_info
from qiskit.tools.events.pubsub import Publisher
# Set parallel flag
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
# Number of local physical cpus
CPU_COUNT = local_hardware_info()['cpus']
def _task_wrapper(param):
(task, value, task_args, task_kwargs) = param
return task(value, *task_args, **task_kwargs)
def parallel_map( # pylint: disable=dangerous-default-value
task, values, task_args=tuple(), task_kwargs={}, num_processes=CPU_COUNT):
"""
Parallel execution of a mapping of `values` to the function `task`. This
is functionally equivalent to::
result = [task(value, *task_args, **task_kwargs) for value in values]
On Windows this function defaults to a serial implementation to avoid the
overhead from spawning processes in Windows.
Args:
task (func): Function that is to be called for each value in ``values``.
values (array_like): List or array of values for which the ``task``
function is to be evaluated.
task_args (list): Optional additional arguments to the ``task`` function.
task_kwargs (dict): Optional additional keyword argument to the ``task`` function.
num_processes (int): Number of processes to spawn.
Returns:
result: The result list contains the value of
``task(value, *task_args, **task_kwargs)`` for
each value in ``values``.
Raises:
QiskitError: If user interrupts via keyboard.
Events:
terra.parallel.start: The collection of parallel tasks are about to start.
terra.parallel.update: One of the parallel task has finished.
terra.parallel.finish: All the parallel tasks have finished.
"""
if len(values) == 1:
return [task(values[0], *task_args, **task_kwargs)]
Publisher().publish("terra.parallel.start", len(values))
nfinished = [0]
def _callback(_):
nfinished[0] += 1
Publisher().publish("terra.parallel.done", nfinished[0])
# Run in parallel if not Win and not in parallel already
if platform.system() != 'Windows' and num_processes > 1 \
and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE':
os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'
try:
results = []
with ProcessPoolExecutor(max_workers=num_processes) as executor:
param = map(lambda value: (task, value, task_args, task_kwargs), values)
future = executor.map(_task_wrapper, param)
results = list(future)
Publisher().publish("terra.parallel.done", len(results))
except (KeyboardInterrupt, Exception) as error:
if isinstance(error, KeyboardInterrupt):
Publisher().publish("terra.parallel.finish")
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
raise QiskitError('Keyboard interrupt in parallel_map.')
# Otherwise just reset parallel flag and error
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
raise error
Publisher().publish("terra.parallel.finish")
os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'
return results
# Cannot do parallel on Windows , if another parallel_map is running in parallel,
# or len(values) == 1.
results = []
for _, value in enumerate(values):
result = task(value, *task_args, **task_kwargs)
results.append(result)
_callback(0)
Publisher().publish("terra.parallel.finish")
return results