Datasets:
Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__init__.py +163 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_cloudpickle_wrapper.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_memmapping_reducer.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_multiprocessing_helpers.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_parallel_backends.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_store_backends.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_utils.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/backports.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/compressor.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/disk.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/executor.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/func_inspect.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/hashing.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/logger.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/memory.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/numpy_pickle.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/numpy_pickle_compat.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/numpy_pickle_utils.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/parallel.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/pool.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_cloudpickle_wrapper.py +18 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_dask.py +381 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_memmapping_reducer.py +715 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_multiprocessing_helpers.py +51 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_parallel_backends.py +753 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_store_backends.py +488 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_utils.py +83 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/backports.py +195 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/compressor.py +572 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/disk.py +131 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/executor.py +131 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/__init__.py +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/__init__.py +18 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/__pycache__/cloudpickle.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/cloudpickle.py +1545 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/cloudpickle_fast.py +14 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__init__.py +45 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/_base.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/cloudpickle_wrapper.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/initializers.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/process_executor.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/reusable_executor.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/_base.py +28 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/backend/__init__.py +14 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/backend/__pycache__/__init__.cpython-310.pyc +0 -0
- Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/backend/__pycache__/_posix_reduction.cpython-310.pyc +0 -0
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__init__.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Joblib is a set of tools to provide **lightweight pipelining in
|
| 2 |
+
Python**. In particular:
|
| 3 |
+
|
| 4 |
+
1. transparent disk-caching of functions and lazy re-evaluation
|
| 5 |
+
(memoize pattern)
|
| 6 |
+
|
| 7 |
+
2. easy simple parallel computing
|
| 8 |
+
|
| 9 |
+
Joblib is optimized to be **fast** and **robust** on large
|
| 10 |
+
data in particular and has specific optimizations for `numpy` arrays. It is
|
| 11 |
+
**BSD-licensed**.
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
==================== ===============================================
|
| 15 |
+
**Documentation:** https://joblib.readthedocs.io
|
| 16 |
+
|
| 17 |
+
**Download:** https://pypi.python.org/pypi/joblib#downloads
|
| 18 |
+
|
| 19 |
+
**Source code:** https://github.com/joblib/joblib
|
| 20 |
+
|
| 21 |
+
**Report issues:** https://github.com/joblib/joblib/issues
|
| 22 |
+
==================== ===============================================
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
Vision
|
| 26 |
+
--------
|
| 27 |
+
|
| 28 |
+
The vision is to provide tools to easily achieve better performance and
|
| 29 |
+
reproducibility when working with long running jobs.
|
| 30 |
+
|
| 31 |
+
* **Avoid computing the same thing twice**: code is often rerun again and
|
| 32 |
+
again, for instance when prototyping computational-heavy jobs (as in
|
| 33 |
+
scientific development), but hand-crafted solutions to alleviate this
|
| 34 |
+
issue are error-prone and often lead to unreproducible results.
|
| 35 |
+
|
| 36 |
+
* **Persist to disk transparently**: efficiently persisting
|
| 37 |
+
arbitrary objects containing large data is hard. Using
|
| 38 |
+
joblib's caching mechanism avoids hand-written persistence and
|
| 39 |
+
implicitly links the file on disk to the execution context of
|
| 40 |
+
the original Python object. As a result, joblib's persistence is
|
| 41 |
+
good for resuming an application status or computational job, eg
|
| 42 |
+
after a crash.
|
| 43 |
+
|
| 44 |
+
Joblib addresses these problems while **leaving your code and your flow
|
| 45 |
+
control as unmodified as possible** (no framework, no new paradigms).
|
| 46 |
+
|
| 47 |
+
Main features
|
| 48 |
+
------------------
|
| 49 |
+
|
| 50 |
+
1) **Transparent and fast disk-caching of output value:** a memoize or
|
| 51 |
+
make-like functionality for Python functions that works well for
|
| 52 |
+
arbitrary Python objects, including very large numpy arrays. Separate
|
| 53 |
+
persistence and flow-execution logic from domain logic or algorithmic
|
| 54 |
+
code by writing the operations as a set of steps with well-defined
|
| 55 |
+
inputs and outputs: Python functions. Joblib can save their
|
| 56 |
+
computation to disk and rerun it only if necessary::
|
| 57 |
+
|
| 58 |
+
>>> from joblib import Memory
|
| 59 |
+
>>> location = 'your_cache_dir_goes_here'
|
| 60 |
+
>>> mem = Memory(location, verbose=1)
|
| 61 |
+
>>> import numpy as np
|
| 62 |
+
>>> a = np.vander(np.arange(3)).astype(float)
|
| 63 |
+
>>> square = mem.cache(np.square)
|
| 64 |
+
>>> b = square(a) # doctest: +ELLIPSIS
|
| 65 |
+
______________________________________________________________________...
|
| 66 |
+
[Memory] Calling ...square...
|
| 67 |
+
square(array([[0., 0., 1.],
|
| 68 |
+
[1., 1., 1.],
|
| 69 |
+
[4., 2., 1.]]))
|
| 70 |
+
_________________________________________________...square - ...s, 0.0min
|
| 71 |
+
|
| 72 |
+
>>> c = square(a)
|
| 73 |
+
>>> # The above call did not trigger an evaluation
|
| 74 |
+
|
| 75 |
+
2) **Embarrassingly parallel helper:** to make it easy to write readable
|
| 76 |
+
parallel code and debug it quickly::
|
| 77 |
+
|
| 78 |
+
>>> from joblib import Parallel, delayed
|
| 79 |
+
>>> from math import sqrt
|
| 80 |
+
>>> Parallel(n_jobs=1)(delayed(sqrt)(i**2) for i in range(10))
|
| 81 |
+
[0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
3) **Fast compressed Persistence**: a replacement for pickle to work
|
| 85 |
+
efficiently on Python objects containing large data (
|
| 86 |
+
*joblib.dump* & *joblib.load* ).
|
| 87 |
+
|
| 88 |
+
..
|
| 89 |
+
>>> import shutil ; shutil.rmtree(location)
|
| 90 |
+
|
| 91 |
+
"""
|
| 92 |
+
|
| 93 |
+
# PEP0440 compatible formatted version, see:
|
| 94 |
+
# https://www.python.org/dev/peps/pep-0440/
|
| 95 |
+
#
|
| 96 |
+
# Generic release markers:
|
| 97 |
+
# X.Y
|
| 98 |
+
# X.Y.Z # For bugfix releases
|
| 99 |
+
#
|
| 100 |
+
# Admissible pre-release markers:
|
| 101 |
+
# X.YaN # Alpha release
|
| 102 |
+
# X.YbN # Beta release
|
| 103 |
+
# X.YrcN # Release Candidate
|
| 104 |
+
# X.Y # Final release
|
| 105 |
+
#
|
| 106 |
+
# Dev branch marker is: 'X.Y.dev' or 'X.Y.devN' where N is an integer.
|
| 107 |
+
# 'X.Y.dev0' is the canonical version of 'X.Y.dev'
|
| 108 |
+
#
|
| 109 |
+
__version__ = "1.5.1"
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
import os
|
| 113 |
+
|
| 114 |
+
from ._cloudpickle_wrapper import wrap_non_picklable_objects
|
| 115 |
+
from ._parallel_backends import ParallelBackendBase
|
| 116 |
+
from ._store_backends import StoreBackendBase
|
| 117 |
+
from .compressor import register_compressor
|
| 118 |
+
from .hashing import hash
|
| 119 |
+
from .logger import Logger, PrintTime
|
| 120 |
+
from .memory import MemorizedResult, Memory, expires_after, register_store_backend
|
| 121 |
+
from .numpy_pickle import dump, load
|
| 122 |
+
from .parallel import (
|
| 123 |
+
Parallel,
|
| 124 |
+
cpu_count,
|
| 125 |
+
delayed,
|
| 126 |
+
effective_n_jobs,
|
| 127 |
+
parallel_backend,
|
| 128 |
+
parallel_config,
|
| 129 |
+
register_parallel_backend,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
__all__ = [
|
| 133 |
+
# On-disk result caching
|
| 134 |
+
"Memory",
|
| 135 |
+
"MemorizedResult",
|
| 136 |
+
"expires_after",
|
| 137 |
+
# Parallel code execution
|
| 138 |
+
"Parallel",
|
| 139 |
+
"delayed",
|
| 140 |
+
"cpu_count",
|
| 141 |
+
"effective_n_jobs",
|
| 142 |
+
"wrap_non_picklable_objects",
|
| 143 |
+
# Context to change the backend globally
|
| 144 |
+
"parallel_config",
|
| 145 |
+
"parallel_backend",
|
| 146 |
+
# Helpers to define and register store/parallel backends
|
| 147 |
+
"ParallelBackendBase",
|
| 148 |
+
"StoreBackendBase",
|
| 149 |
+
"register_compressor",
|
| 150 |
+
"register_parallel_backend",
|
| 151 |
+
"register_store_backend",
|
| 152 |
+
# Helpers kept for backward compatibility
|
| 153 |
+
"PrintTime",
|
| 154 |
+
"Logger",
|
| 155 |
+
"hash",
|
| 156 |
+
"dump",
|
| 157 |
+
"load",
|
| 158 |
+
]
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
# Workaround issue discovered in intel-openmp 2019.5:
|
| 162 |
+
# https://github.com/ContinuumIO/anaconda-issues/issues/11294
|
| 163 |
+
os.environ.setdefault("KMP_INIT_AT_FORK", "FALSE")
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (4.69 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_cloudpickle_wrapper.cpython-310.pyc
ADDED
|
Binary file (647 Bytes). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_memmapping_reducer.cpython-310.pyc
ADDED
|
Binary file (15.7 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_multiprocessing_helpers.cpython-310.pyc
ADDED
|
Binary file (1.3 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_parallel_backends.cpython-310.pyc
ADDED
|
Binary file (22.4 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_store_backends.cpython-310.pyc
ADDED
|
Binary file (16 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/_utils.cpython-310.pyc
ADDED
|
Binary file (2.7 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/backports.cpython-310.pyc
ADDED
|
Binary file (5.44 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/compressor.cpython-310.pyc
ADDED
|
Binary file (16.7 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/disk.cpython-310.pyc
ADDED
|
Binary file (3.14 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/executor.cpython-310.pyc
ADDED
|
Binary file (3.26 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/func_inspect.cpython-310.pyc
ADDED
|
Binary file (8.77 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/hashing.cpython-310.pyc
ADDED
|
Binary file (6.48 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/logger.cpython-310.pyc
ADDED
|
Binary file (4.35 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/memory.cpython-310.pyc
ADDED
|
Binary file (32.8 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/numpy_pickle.cpython-310.pyc
ADDED
|
Binary file (18.2 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/numpy_pickle_compat.cpython-310.pyc
ADDED
|
Binary file (7.1 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/numpy_pickle_utils.cpython-310.pyc
ADDED
|
Binary file (6.92 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/parallel.cpython-310.pyc
ADDED
|
Binary file (56.3 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/__pycache__/pool.cpython-310.pyc
ADDED
|
Binary file (12.5 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_cloudpickle_wrapper.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Small shim of loky's cloudpickle_wrapper to avoid failure when
|
| 3 |
+
multiprocessing is not available.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
from ._multiprocessing_helpers import mp
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
def _my_wrap_non_picklable_objects(obj, keep_wrapper=True):
|
| 10 |
+
return obj
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
if mp is not None:
|
| 14 |
+
from .externals.loky import wrap_non_picklable_objects
|
| 15 |
+
else:
|
| 16 |
+
wrap_non_picklable_objects = _my_wrap_non_picklable_objects
|
| 17 |
+
|
| 18 |
+
__all__ = ["wrap_non_picklable_objects"]
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_dask.py
ADDED
|
@@ -0,0 +1,381 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
import contextlib
|
| 6 |
+
import time
|
| 7 |
+
import weakref
|
| 8 |
+
from uuid import uuid4
|
| 9 |
+
|
| 10 |
+
from ._utils import (
|
| 11 |
+
_retrieve_traceback_capturing_wrapped_call,
|
| 12 |
+
_TracebackCapturingWrapper,
|
| 13 |
+
)
|
| 14 |
+
from .parallel import AutoBatchingMixin, ParallelBackendBase, parallel_config
|
| 15 |
+
|
| 16 |
+
try:
|
| 17 |
+
import dask
|
| 18 |
+
import distributed
|
| 19 |
+
except ImportError:
|
| 20 |
+
dask = None
|
| 21 |
+
distributed = None
|
| 22 |
+
|
| 23 |
+
if dask is not None and distributed is not None:
|
| 24 |
+
from dask.distributed import (
|
| 25 |
+
Client,
|
| 26 |
+
as_completed,
|
| 27 |
+
get_client,
|
| 28 |
+
rejoin,
|
| 29 |
+
secede,
|
| 30 |
+
)
|
| 31 |
+
from dask.sizeof import sizeof
|
| 32 |
+
from dask.utils import funcname
|
| 33 |
+
from distributed.utils import thread_state
|
| 34 |
+
|
| 35 |
+
try:
|
| 36 |
+
# asyncio.TimeoutError, Python3-only error thrown by recent versions of
|
| 37 |
+
# distributed
|
| 38 |
+
from distributed.utils import TimeoutError as _TimeoutError
|
| 39 |
+
except ImportError:
|
| 40 |
+
from tornado.gen import TimeoutError as _TimeoutError
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def is_weakrefable(obj):
|
| 44 |
+
try:
|
| 45 |
+
weakref.ref(obj)
|
| 46 |
+
return True
|
| 47 |
+
except TypeError:
|
| 48 |
+
return False
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class _WeakKeyDictionary:
|
| 52 |
+
"""A variant of weakref.WeakKeyDictionary for unhashable objects.
|
| 53 |
+
|
| 54 |
+
This datastructure is used to store futures for broadcasted data objects
|
| 55 |
+
such as large numpy arrays or pandas dataframes that are not hashable and
|
| 56 |
+
therefore cannot be used as keys of traditional python dicts.
|
| 57 |
+
|
| 58 |
+
Furthermore using a dict with id(array) as key is not safe because the
|
| 59 |
+
Python is likely to reuse id of recently collected arrays.
|
| 60 |
+
"""
|
| 61 |
+
|
| 62 |
+
def __init__(self):
|
| 63 |
+
self._data = {}
|
| 64 |
+
|
| 65 |
+
def __getitem__(self, obj):
|
| 66 |
+
ref, val = self._data[id(obj)]
|
| 67 |
+
if ref() is not obj:
|
| 68 |
+
# In case of a race condition with on_destroy.
|
| 69 |
+
raise KeyError(obj)
|
| 70 |
+
return val
|
| 71 |
+
|
| 72 |
+
def __setitem__(self, obj, value):
|
| 73 |
+
key = id(obj)
|
| 74 |
+
try:
|
| 75 |
+
ref, _ = self._data[key]
|
| 76 |
+
if ref() is not obj:
|
| 77 |
+
# In case of race condition with on_destroy.
|
| 78 |
+
raise KeyError(obj)
|
| 79 |
+
except KeyError:
|
| 80 |
+
# Insert the new entry in the mapping along with a weakref
|
| 81 |
+
# callback to automatically delete the entry from the mapping
|
| 82 |
+
# as soon as the object used as key is garbage collected.
|
| 83 |
+
def on_destroy(_):
|
| 84 |
+
del self._data[key]
|
| 85 |
+
|
| 86 |
+
ref = weakref.ref(obj, on_destroy)
|
| 87 |
+
self._data[key] = ref, value
|
| 88 |
+
|
| 89 |
+
def __len__(self):
|
| 90 |
+
return len(self._data)
|
| 91 |
+
|
| 92 |
+
def clear(self):
|
| 93 |
+
self._data.clear()
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _funcname(x):
|
| 97 |
+
try:
|
| 98 |
+
if isinstance(x, list):
|
| 99 |
+
x = x[0][0]
|
| 100 |
+
except Exception:
|
| 101 |
+
pass
|
| 102 |
+
return funcname(x)
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _make_tasks_summary(tasks):
|
| 106 |
+
"""Summarize of list of (func, args, kwargs) function calls"""
|
| 107 |
+
unique_funcs = {func for func, args, kwargs in tasks}
|
| 108 |
+
|
| 109 |
+
if len(unique_funcs) == 1:
|
| 110 |
+
mixed = False
|
| 111 |
+
else:
|
| 112 |
+
mixed = True
|
| 113 |
+
return len(tasks), mixed, _funcname(tasks)
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class Batch:
|
| 117 |
+
"""dask-compatible wrapper that executes a batch of tasks"""
|
| 118 |
+
|
| 119 |
+
def __init__(self, tasks):
|
| 120 |
+
# collect some metadata from the tasks to ease Batch calls
|
| 121 |
+
# introspection when debugging
|
| 122 |
+
self._num_tasks, self._mixed, self._funcname = _make_tasks_summary(tasks)
|
| 123 |
+
|
| 124 |
+
def __call__(self, tasks=None):
|
| 125 |
+
results = []
|
| 126 |
+
with parallel_config(backend="dask"):
|
| 127 |
+
for func, args, kwargs in tasks:
|
| 128 |
+
results.append(func(*args, **kwargs))
|
| 129 |
+
return results
|
| 130 |
+
|
| 131 |
+
def __repr__(self):
|
| 132 |
+
descr = f"batch_of_{self._funcname}_{self._num_tasks}_calls"
|
| 133 |
+
if self._mixed:
|
| 134 |
+
descr = "mixed_" + descr
|
| 135 |
+
return descr
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _joblib_probe_task():
|
| 139 |
+
# Noop used by the joblib connector to probe when workers are ready.
|
| 140 |
+
pass
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class DaskDistributedBackend(AutoBatchingMixin, ParallelBackendBase):
|
| 144 |
+
MIN_IDEAL_BATCH_DURATION = 0.2
|
| 145 |
+
MAX_IDEAL_BATCH_DURATION = 1.0
|
| 146 |
+
supports_retrieve_callback = True
|
| 147 |
+
default_n_jobs = -1
|
| 148 |
+
|
| 149 |
+
def __init__(
|
| 150 |
+
self,
|
| 151 |
+
scheduler_host=None,
|
| 152 |
+
scatter=None,
|
| 153 |
+
client=None,
|
| 154 |
+
loop=None,
|
| 155 |
+
wait_for_workers_timeout=10,
|
| 156 |
+
**submit_kwargs,
|
| 157 |
+
):
|
| 158 |
+
super().__init__()
|
| 159 |
+
|
| 160 |
+
if distributed is None:
|
| 161 |
+
msg = (
|
| 162 |
+
"You are trying to use 'dask' as a joblib parallel backend "
|
| 163 |
+
"but dask is not installed. Please install dask "
|
| 164 |
+
"to fix this error."
|
| 165 |
+
)
|
| 166 |
+
raise ValueError(msg)
|
| 167 |
+
|
| 168 |
+
if client is None:
|
| 169 |
+
if scheduler_host:
|
| 170 |
+
client = Client(scheduler_host, loop=loop, set_as_default=False)
|
| 171 |
+
else:
|
| 172 |
+
try:
|
| 173 |
+
client = get_client()
|
| 174 |
+
except ValueError as e:
|
| 175 |
+
msg = (
|
| 176 |
+
"To use Joblib with Dask first create a Dask Client"
|
| 177 |
+
"\n\n"
|
| 178 |
+
" from dask.distributed import Client\n"
|
| 179 |
+
" client = Client()\n"
|
| 180 |
+
"or\n"
|
| 181 |
+
" client = Client('scheduler-address:8786')"
|
| 182 |
+
)
|
| 183 |
+
raise ValueError(msg) from e
|
| 184 |
+
|
| 185 |
+
self.client = client
|
| 186 |
+
|
| 187 |
+
if scatter is not None and not isinstance(scatter, (list, tuple)):
|
| 188 |
+
raise TypeError(
|
| 189 |
+
"scatter must be a list/tuple, got `%s`" % type(scatter).__name__
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
if scatter is not None and len(scatter) > 0:
|
| 193 |
+
# Keep a reference to the scattered data to keep the ids the same
|
| 194 |
+
self._scatter = list(scatter)
|
| 195 |
+
scattered = self.client.scatter(scatter, broadcast=True)
|
| 196 |
+
self.data_futures = {id(x): f for x, f in zip(scatter, scattered)}
|
| 197 |
+
else:
|
| 198 |
+
self._scatter = []
|
| 199 |
+
self.data_futures = {}
|
| 200 |
+
self.wait_for_workers_timeout = wait_for_workers_timeout
|
| 201 |
+
self.submit_kwargs = submit_kwargs
|
| 202 |
+
self.waiting_futures = as_completed(
|
| 203 |
+
[], loop=client.loop, with_results=True, raise_errors=False
|
| 204 |
+
)
|
| 205 |
+
self._results = {}
|
| 206 |
+
self._callbacks = {}
|
| 207 |
+
|
| 208 |
+
async def _collect(self):
|
| 209 |
+
while self._continue:
|
| 210 |
+
async for future, result in self.waiting_futures:
|
| 211 |
+
cf_future = self._results.pop(future)
|
| 212 |
+
callback = self._callbacks.pop(future)
|
| 213 |
+
if future.status == "error":
|
| 214 |
+
typ, exc, tb = result
|
| 215 |
+
cf_future.set_exception(exc)
|
| 216 |
+
else:
|
| 217 |
+
cf_future.set_result(result)
|
| 218 |
+
callback(result)
|
| 219 |
+
await asyncio.sleep(0.01)
|
| 220 |
+
|
| 221 |
+
def __reduce__(self):
|
| 222 |
+
return (DaskDistributedBackend, ())
|
| 223 |
+
|
| 224 |
+
def get_nested_backend(self):
|
| 225 |
+
return DaskDistributedBackend(client=self.client), -1
|
| 226 |
+
|
| 227 |
+
def configure(self, n_jobs=1, parallel=None, **backend_args):
|
| 228 |
+
self.parallel = parallel
|
| 229 |
+
return self.effective_n_jobs(n_jobs)
|
| 230 |
+
|
| 231 |
+
def start_call(self):
|
| 232 |
+
self._continue = True
|
| 233 |
+
self.client.loop.add_callback(self._collect)
|
| 234 |
+
self.call_data_futures = _WeakKeyDictionary()
|
| 235 |
+
|
| 236 |
+
def stop_call(self):
|
| 237 |
+
# The explicit call to clear is required to break a cycling reference
|
| 238 |
+
# to the futures.
|
| 239 |
+
self._continue = False
|
| 240 |
+
# wait for the future collection routine (self._backend._collect) to
|
| 241 |
+
# finish in order to limit asyncio warnings due to aborting _collect
|
| 242 |
+
# during a following backend termination call
|
| 243 |
+
time.sleep(0.01)
|
| 244 |
+
self.call_data_futures.clear()
|
| 245 |
+
|
| 246 |
+
def effective_n_jobs(self, n_jobs):
|
| 247 |
+
effective_n_jobs = sum(self.client.ncores().values())
|
| 248 |
+
if effective_n_jobs != 0 or not self.wait_for_workers_timeout:
|
| 249 |
+
return effective_n_jobs
|
| 250 |
+
|
| 251 |
+
# If there is no worker, schedule a probe task to wait for the workers
|
| 252 |
+
# to come up and be available. If the dask cluster is in adaptive mode
|
| 253 |
+
# task might cause the cluster to provision some workers.
|
| 254 |
+
try:
|
| 255 |
+
self.client.submit(_joblib_probe_task).result(
|
| 256 |
+
timeout=self.wait_for_workers_timeout
|
| 257 |
+
)
|
| 258 |
+
except _TimeoutError as e:
|
| 259 |
+
error_msg = (
|
| 260 |
+
"DaskDistributedBackend has no worker after {} seconds. "
|
| 261 |
+
"Make sure that workers are started and can properly connect "
|
| 262 |
+
"to the scheduler and increase the joblib/dask connection "
|
| 263 |
+
"timeout with:\n\n"
|
| 264 |
+
"parallel_config(backend='dask', wait_for_workers_timeout={})"
|
| 265 |
+
).format(
|
| 266 |
+
self.wait_for_workers_timeout,
|
| 267 |
+
max(10, 2 * self.wait_for_workers_timeout),
|
| 268 |
+
)
|
| 269 |
+
raise TimeoutError(error_msg) from e
|
| 270 |
+
return sum(self.client.ncores().values())
|
| 271 |
+
|
| 272 |
+
async def _to_func_args(self, func):
|
| 273 |
+
itemgetters = dict()
|
| 274 |
+
|
| 275 |
+
# Futures that are dynamically generated during a single call to
|
| 276 |
+
# Parallel.__call__.
|
| 277 |
+
call_data_futures = getattr(self, "call_data_futures", None)
|
| 278 |
+
|
| 279 |
+
async def maybe_to_futures(args):
|
| 280 |
+
out = []
|
| 281 |
+
for arg in args:
|
| 282 |
+
arg_id = id(arg)
|
| 283 |
+
if arg_id in itemgetters:
|
| 284 |
+
out.append(itemgetters[arg_id])
|
| 285 |
+
continue
|
| 286 |
+
|
| 287 |
+
f = self.data_futures.get(arg_id, None)
|
| 288 |
+
if f is None and call_data_futures is not None:
|
| 289 |
+
try:
|
| 290 |
+
f = await call_data_futures[arg]
|
| 291 |
+
except KeyError:
|
| 292 |
+
pass
|
| 293 |
+
if f is None:
|
| 294 |
+
if is_weakrefable(arg) and sizeof(arg) > 1e3:
|
| 295 |
+
# Automatically scatter large objects to some of
|
| 296 |
+
# the workers to avoid duplicated data transfers.
|
| 297 |
+
# Rely on automated inter-worker data stealing if
|
| 298 |
+
# more workers need to reuse this data
|
| 299 |
+
# concurrently.
|
| 300 |
+
# set hash=False - nested scatter calls (i.e
|
| 301 |
+
# calling client.scatter inside a dask worker)
|
| 302 |
+
# using hash=True often raise CancelledError,
|
| 303 |
+
# see dask/distributed#3703
|
| 304 |
+
_coro = self.client.scatter(
|
| 305 |
+
arg, asynchronous=True, hash=False
|
| 306 |
+
)
|
| 307 |
+
# Centralize the scattering of identical arguments
|
| 308 |
+
# between concurrent apply_async callbacks by
|
| 309 |
+
# exposing the running coroutine in
|
| 310 |
+
# call_data_futures before it completes.
|
| 311 |
+
t = asyncio.Task(_coro)
|
| 312 |
+
call_data_futures[arg] = t
|
| 313 |
+
|
| 314 |
+
f = await t
|
| 315 |
+
|
| 316 |
+
if f is not None:
|
| 317 |
+
out.append(f)
|
| 318 |
+
else:
|
| 319 |
+
out.append(arg)
|
| 320 |
+
return out
|
| 321 |
+
|
| 322 |
+
tasks = []
|
| 323 |
+
for f, args, kwargs in func.items:
|
| 324 |
+
args = list(await maybe_to_futures(args))
|
| 325 |
+
kwargs = dict(zip(kwargs.keys(), await maybe_to_futures(kwargs.values())))
|
| 326 |
+
tasks.append((f, args, kwargs))
|
| 327 |
+
|
| 328 |
+
return (Batch(tasks), tasks)
|
| 329 |
+
|
| 330 |
+
def apply_async(self, func, callback=None):
|
| 331 |
+
cf_future = concurrent.futures.Future()
|
| 332 |
+
cf_future.get = cf_future.result # achieve AsyncResult API
|
| 333 |
+
|
| 334 |
+
async def f(func, callback):
|
| 335 |
+
batch, tasks = await self._to_func_args(func)
|
| 336 |
+
key = f"{repr(batch)}-{uuid4().hex}"
|
| 337 |
+
|
| 338 |
+
dask_future = self.client.submit(
|
| 339 |
+
_TracebackCapturingWrapper(batch),
|
| 340 |
+
tasks=tasks,
|
| 341 |
+
key=key,
|
| 342 |
+
**self.submit_kwargs,
|
| 343 |
+
)
|
| 344 |
+
self.waiting_futures.add(dask_future)
|
| 345 |
+
self._callbacks[dask_future] = callback
|
| 346 |
+
self._results[dask_future] = cf_future
|
| 347 |
+
|
| 348 |
+
self.client.loop.add_callback(f, func, callback)
|
| 349 |
+
|
| 350 |
+
return cf_future
|
| 351 |
+
|
| 352 |
+
def retrieve_result_callback(self, out):
|
| 353 |
+
return _retrieve_traceback_capturing_wrapped_call(out)
|
| 354 |
+
|
| 355 |
+
def abort_everything(self, ensure_ready=True):
|
| 356 |
+
"""Tell the client to cancel any task submitted via this instance
|
| 357 |
+
|
| 358 |
+
joblib.Parallel will never access those results
|
| 359 |
+
"""
|
| 360 |
+
with self.waiting_futures.lock:
|
| 361 |
+
self.waiting_futures.futures.clear()
|
| 362 |
+
while not self.waiting_futures.queue.empty():
|
| 363 |
+
self.waiting_futures.queue.get()
|
| 364 |
+
|
| 365 |
+
@contextlib.contextmanager
|
| 366 |
+
def retrieval_context(self):
|
| 367 |
+
"""Override ParallelBackendBase.retrieval_context to avoid deadlocks.
|
| 368 |
+
|
| 369 |
+
This removes thread from the worker's thread pool (using 'secede').
|
| 370 |
+
Seceding avoids deadlock in nested parallelism settings.
|
| 371 |
+
"""
|
| 372 |
+
# See 'joblib.Parallel.__call__' and 'joblib.Parallel.retrieve' for how
|
| 373 |
+
# this is used.
|
| 374 |
+
if hasattr(thread_state, "execution_state"):
|
| 375 |
+
# we are in a worker. Secede to avoid deadlock.
|
| 376 |
+
secede()
|
| 377 |
+
|
| 378 |
+
yield
|
| 379 |
+
|
| 380 |
+
if hasattr(thread_state, "execution_state"):
|
| 381 |
+
rejoin()
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_memmapping_reducer.py
ADDED
|
@@ -0,0 +1,715 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
# Copyright: 2017, Thomas Moreau
|
| 6 |
+
# License: BSD 3 clause
|
| 7 |
+
|
| 8 |
+
import atexit
|
| 9 |
+
import errno
|
| 10 |
+
import os
|
| 11 |
+
import stat
|
| 12 |
+
import tempfile
|
| 13 |
+
import threading
|
| 14 |
+
import time
|
| 15 |
+
import warnings
|
| 16 |
+
import weakref
|
| 17 |
+
from mmap import mmap
|
| 18 |
+
from multiprocessing import util
|
| 19 |
+
from pickle import HIGHEST_PROTOCOL, PicklingError, dumps, loads, whichmodule
|
| 20 |
+
from uuid import uuid4
|
| 21 |
+
|
| 22 |
+
try:
|
| 23 |
+
WindowsError
|
| 24 |
+
except NameError:
|
| 25 |
+
WindowsError = type(None)
|
| 26 |
+
|
| 27 |
+
try:
|
| 28 |
+
import numpy as np
|
| 29 |
+
from numpy.lib.stride_tricks import as_strided
|
| 30 |
+
except ImportError:
|
| 31 |
+
np = None
|
| 32 |
+
|
| 33 |
+
from .backports import make_memmap
|
| 34 |
+
from .disk import delete_folder
|
| 35 |
+
from .externals.loky.backend import resource_tracker
|
| 36 |
+
from .numpy_pickle import dump, load, load_temporary_memmap
|
| 37 |
+
|
| 38 |
+
# Some system have a ramdisk mounted by default, we can use it instead of /tmp
|
| 39 |
+
# as the default folder to dump big arrays to share with subprocesses.
|
| 40 |
+
SYSTEM_SHARED_MEM_FS = "/dev/shm"
|
| 41 |
+
|
| 42 |
+
# Minimal number of bytes available on SYSTEM_SHARED_MEM_FS to consider using
|
| 43 |
+
# it as the default folder to dump big arrays to share with subprocesses.
|
| 44 |
+
SYSTEM_SHARED_MEM_FS_MIN_SIZE = int(2e9)
|
| 45 |
+
|
| 46 |
+
# Folder and file permissions to chmod temporary files generated by the
|
| 47 |
+
# memmapping pool. Only the owner of the Python process can access the
|
| 48 |
+
# temporary files and folder.
|
| 49 |
+
FOLDER_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR
|
| 50 |
+
FILE_PERMISSIONS = stat.S_IRUSR | stat.S_IWUSR
|
| 51 |
+
|
| 52 |
+
# Set used in joblib workers, referencing the filenames of temporary memmaps
|
| 53 |
+
# created by joblib to speed up data communication. In child processes, we add
|
| 54 |
+
# a finalizer to these memmaps that sends a maybe_unlink call to the
|
| 55 |
+
# resource_tracker, in order to free main memory as fast as possible.
|
| 56 |
+
JOBLIB_MMAPS = set()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _log_and_unlink(filename):
|
| 60 |
+
from .externals.loky.backend.resource_tracker import _resource_tracker
|
| 61 |
+
|
| 62 |
+
util.debug(
|
| 63 |
+
"[FINALIZER CALL] object mapping to {} about to be deleted,"
|
| 64 |
+
" decrementing the refcount of the file (pid: {})".format(
|
| 65 |
+
os.path.basename(filename), os.getpid()
|
| 66 |
+
)
|
| 67 |
+
)
|
| 68 |
+
_resource_tracker.maybe_unlink(filename, "file")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def add_maybe_unlink_finalizer(memmap):
|
| 72 |
+
util.debug(
|
| 73 |
+
"[FINALIZER ADD] adding finalizer to {} (id {}, filename {}, pid {})".format(
|
| 74 |
+
type(memmap), id(memmap), os.path.basename(memmap.filename), os.getpid()
|
| 75 |
+
)
|
| 76 |
+
)
|
| 77 |
+
weakref.finalize(memmap, _log_and_unlink, memmap.filename)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def unlink_file(filename):
|
| 81 |
+
"""Wrapper around os.unlink with a retry mechanism.
|
| 82 |
+
|
| 83 |
+
The retry mechanism has been implemented primarily to overcome a race
|
| 84 |
+
condition happening during the finalizer of a np.memmap: when a process
|
| 85 |
+
holding the last reference to a mmap-backed np.memmap/np.array is about to
|
| 86 |
+
delete this array (and close the reference), it sends a maybe_unlink
|
| 87 |
+
request to the resource_tracker. This request can be processed faster than
|
| 88 |
+
it takes for the last reference of the memmap to be closed, yielding (on
|
| 89 |
+
Windows) a PermissionError in the resource_tracker loop.
|
| 90 |
+
"""
|
| 91 |
+
NUM_RETRIES = 10
|
| 92 |
+
for retry_no in range(1, NUM_RETRIES + 1):
|
| 93 |
+
try:
|
| 94 |
+
os.unlink(filename)
|
| 95 |
+
break
|
| 96 |
+
except PermissionError:
|
| 97 |
+
util.debug(
|
| 98 |
+
"[ResourceTracker] tried to unlink {}, got PermissionError".format(
|
| 99 |
+
filename
|
| 100 |
+
)
|
| 101 |
+
)
|
| 102 |
+
if retry_no == NUM_RETRIES:
|
| 103 |
+
raise
|
| 104 |
+
else:
|
| 105 |
+
time.sleep(0.2)
|
| 106 |
+
except FileNotFoundError:
|
| 107 |
+
# In case of a race condition when deleting the temporary folder,
|
| 108 |
+
# avoid noisy FileNotFoundError exception in the resource tracker.
|
| 109 |
+
pass
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
resource_tracker._CLEANUP_FUNCS["file"] = unlink_file
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class _WeakArrayKeyMap:
|
| 116 |
+
"""A variant of weakref.WeakKeyDictionary for unhashable numpy arrays.
|
| 117 |
+
|
| 118 |
+
This datastructure will be used with numpy arrays as obj keys, therefore we
|
| 119 |
+
do not use the __get__ / __set__ methods to avoid any conflict with the
|
| 120 |
+
numpy fancy indexing syntax.
|
| 121 |
+
"""
|
| 122 |
+
|
| 123 |
+
def __init__(self):
|
| 124 |
+
self._data = {}
|
| 125 |
+
|
| 126 |
+
def get(self, obj):
|
| 127 |
+
ref, val = self._data[id(obj)]
|
| 128 |
+
if ref() is not obj:
|
| 129 |
+
# In case of race condition with on_destroy: could never be
|
| 130 |
+
# triggered by the joblib tests with CPython.
|
| 131 |
+
raise KeyError(obj)
|
| 132 |
+
return val
|
| 133 |
+
|
| 134 |
+
def set(self, obj, value):
|
| 135 |
+
key = id(obj)
|
| 136 |
+
try:
|
| 137 |
+
ref, _ = self._data[key]
|
| 138 |
+
if ref() is not obj:
|
| 139 |
+
# In case of race condition with on_destroy: could never be
|
| 140 |
+
# triggered by the joblib tests with CPython.
|
| 141 |
+
raise KeyError(obj)
|
| 142 |
+
except KeyError:
|
| 143 |
+
# Insert the new entry in the mapping along with a weakref
|
| 144 |
+
# callback to automatically delete the entry from the mapping
|
| 145 |
+
# as soon as the object used as key is garbage collected.
|
| 146 |
+
def on_destroy(_):
|
| 147 |
+
del self._data[key]
|
| 148 |
+
|
| 149 |
+
ref = weakref.ref(obj, on_destroy)
|
| 150 |
+
self._data[key] = ref, value
|
| 151 |
+
|
| 152 |
+
def __getstate__(self):
|
| 153 |
+
raise PicklingError("_WeakArrayKeyMap is not pickleable")
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
###############################################################################
|
| 157 |
+
# Support for efficient transient pickling of numpy data structures
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def _get_backing_memmap(a):
|
| 161 |
+
"""Recursively look up the original np.memmap instance base if any."""
|
| 162 |
+
b = getattr(a, "base", None)
|
| 163 |
+
if b is None:
|
| 164 |
+
# TODO: check scipy sparse datastructure if scipy is installed
|
| 165 |
+
# a nor its descendants do not have a memmap base
|
| 166 |
+
return None
|
| 167 |
+
|
| 168 |
+
elif isinstance(b, mmap):
|
| 169 |
+
# a is already a real memmap instance.
|
| 170 |
+
return a
|
| 171 |
+
|
| 172 |
+
else:
|
| 173 |
+
# Recursive exploration of the base ancestry
|
| 174 |
+
return _get_backing_memmap(b)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _get_temp_dir(pool_folder_name, temp_folder=None):
|
| 178 |
+
"""Get the full path to a subfolder inside the temporary folder.
|
| 179 |
+
|
| 180 |
+
Parameters
|
| 181 |
+
----------
|
| 182 |
+
pool_folder_name : str
|
| 183 |
+
Sub-folder name used for the serialization of a pool instance.
|
| 184 |
+
|
| 185 |
+
temp_folder: str, optional
|
| 186 |
+
Folder to be used by the pool for memmapping large arrays
|
| 187 |
+
for sharing memory with worker processes. If None, this will try in
|
| 188 |
+
order:
|
| 189 |
+
|
| 190 |
+
- a folder pointed by the JOBLIB_TEMP_FOLDER environment
|
| 191 |
+
variable,
|
| 192 |
+
- /dev/shm if the folder exists and is writable: this is a
|
| 193 |
+
RAMdisk filesystem available by default on modern Linux
|
| 194 |
+
distributions,
|
| 195 |
+
- the default system temporary folder that can be
|
| 196 |
+
overridden with TMP, TMPDIR or TEMP environment
|
| 197 |
+
variables, typically /tmp under Unix operating systems.
|
| 198 |
+
|
| 199 |
+
Returns
|
| 200 |
+
-------
|
| 201 |
+
pool_folder : str
|
| 202 |
+
full path to the temporary folder
|
| 203 |
+
use_shared_mem : bool
|
| 204 |
+
whether the temporary folder is written to the system shared memory
|
| 205 |
+
folder or some other temporary folder.
|
| 206 |
+
"""
|
| 207 |
+
use_shared_mem = False
|
| 208 |
+
if temp_folder is None:
|
| 209 |
+
temp_folder = os.environ.get("JOBLIB_TEMP_FOLDER", None)
|
| 210 |
+
if temp_folder is None:
|
| 211 |
+
if os.path.exists(SYSTEM_SHARED_MEM_FS) and hasattr(os, "statvfs"):
|
| 212 |
+
try:
|
| 213 |
+
shm_stats = os.statvfs(SYSTEM_SHARED_MEM_FS)
|
| 214 |
+
available_nbytes = shm_stats.f_bsize * shm_stats.f_bavail
|
| 215 |
+
if available_nbytes > SYSTEM_SHARED_MEM_FS_MIN_SIZE:
|
| 216 |
+
# Try to see if we have write access to the shared mem
|
| 217 |
+
# folder only if it is reasonably large (that is 2GB or
|
| 218 |
+
# more).
|
| 219 |
+
temp_folder = SYSTEM_SHARED_MEM_FS
|
| 220 |
+
pool_folder = os.path.join(temp_folder, pool_folder_name)
|
| 221 |
+
if not os.path.exists(pool_folder):
|
| 222 |
+
os.makedirs(pool_folder)
|
| 223 |
+
use_shared_mem = True
|
| 224 |
+
except (IOError, OSError):
|
| 225 |
+
# Missing rights in the /dev/shm partition, fallback to regular
|
| 226 |
+
# temp folder.
|
| 227 |
+
temp_folder = None
|
| 228 |
+
if temp_folder is None:
|
| 229 |
+
# Fallback to the default tmp folder, typically /tmp
|
| 230 |
+
temp_folder = tempfile.gettempdir()
|
| 231 |
+
temp_folder = os.path.abspath(os.path.expanduser(temp_folder))
|
| 232 |
+
pool_folder = os.path.join(temp_folder, pool_folder_name)
|
| 233 |
+
return pool_folder, use_shared_mem
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def has_shareable_memory(a):
|
| 237 |
+
"""Return True if a is backed by some mmap buffer directly or not."""
|
| 238 |
+
return _get_backing_memmap(a) is not None
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def _strided_from_memmap(
|
| 242 |
+
filename,
|
| 243 |
+
dtype,
|
| 244 |
+
mode,
|
| 245 |
+
offset,
|
| 246 |
+
order,
|
| 247 |
+
shape,
|
| 248 |
+
strides,
|
| 249 |
+
total_buffer_len,
|
| 250 |
+
unlink_on_gc_collect,
|
| 251 |
+
):
|
| 252 |
+
"""Reconstruct an array view on a memory mapped file."""
|
| 253 |
+
if mode == "w+":
|
| 254 |
+
# Do not zero the original data when unpickling
|
| 255 |
+
mode = "r+"
|
| 256 |
+
|
| 257 |
+
if strides is None:
|
| 258 |
+
# Simple, contiguous memmap
|
| 259 |
+
return make_memmap(
|
| 260 |
+
filename,
|
| 261 |
+
dtype=dtype,
|
| 262 |
+
shape=shape,
|
| 263 |
+
mode=mode,
|
| 264 |
+
offset=offset,
|
| 265 |
+
order=order,
|
| 266 |
+
unlink_on_gc_collect=unlink_on_gc_collect,
|
| 267 |
+
)
|
| 268 |
+
else:
|
| 269 |
+
# For non-contiguous data, memmap the total enclosing buffer and then
|
| 270 |
+
# extract the non-contiguous view with the stride-tricks API
|
| 271 |
+
base = make_memmap(
|
| 272 |
+
filename,
|
| 273 |
+
dtype=dtype,
|
| 274 |
+
shape=total_buffer_len,
|
| 275 |
+
offset=offset,
|
| 276 |
+
mode=mode,
|
| 277 |
+
order=order,
|
| 278 |
+
unlink_on_gc_collect=unlink_on_gc_collect,
|
| 279 |
+
)
|
| 280 |
+
return as_strided(base, shape=shape, strides=strides)
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def _reduce_memmap_backed(a, m):
|
| 284 |
+
"""Pickling reduction for memmap backed arrays.
|
| 285 |
+
|
| 286 |
+
a is expected to be an instance of np.ndarray (or np.memmap)
|
| 287 |
+
m is expected to be an instance of np.memmap on the top of the ``base``
|
| 288 |
+
attribute ancestry of a. ``m.base`` should be the real python mmap object.
|
| 289 |
+
"""
|
| 290 |
+
# offset that comes from the striding differences between a and m
|
| 291 |
+
util.debug(
|
| 292 |
+
"[MEMMAP REDUCE] reducing a memmap-backed array (shape, {}, pid: {})".format(
|
| 293 |
+
a.shape, os.getpid()
|
| 294 |
+
)
|
| 295 |
+
)
|
| 296 |
+
try:
|
| 297 |
+
from numpy.lib.array_utils import byte_bounds
|
| 298 |
+
except (ModuleNotFoundError, ImportError):
|
| 299 |
+
# Backward-compat for numpy < 2.0
|
| 300 |
+
from numpy import byte_bounds
|
| 301 |
+
a_start, a_end = byte_bounds(a)
|
| 302 |
+
m_start = byte_bounds(m)[0]
|
| 303 |
+
offset = a_start - m_start
|
| 304 |
+
|
| 305 |
+
# offset from the backing memmap
|
| 306 |
+
offset += m.offset
|
| 307 |
+
|
| 308 |
+
# 1D arrays are both F and C contiguous, so only set the flag in
|
| 309 |
+
# higher dimensions. See https://github.com/joblib/joblib/pull/1704.
|
| 310 |
+
if m.ndim > 1 and m.flags["F_CONTIGUOUS"]:
|
| 311 |
+
order = "F"
|
| 312 |
+
else:
|
| 313 |
+
# The backing memmap buffer is necessarily contiguous hence C if not
|
| 314 |
+
# Fortran
|
| 315 |
+
order = "C"
|
| 316 |
+
|
| 317 |
+
if a.flags["F_CONTIGUOUS"] or a.flags["C_CONTIGUOUS"]:
|
| 318 |
+
# If the array is a contiguous view, no need to pass the strides
|
| 319 |
+
strides = None
|
| 320 |
+
total_buffer_len = None
|
| 321 |
+
else:
|
| 322 |
+
# Compute the total number of items to map from which the strided
|
| 323 |
+
# view will be extracted.
|
| 324 |
+
strides = a.strides
|
| 325 |
+
total_buffer_len = (a_end - a_start) // a.itemsize
|
| 326 |
+
|
| 327 |
+
return (
|
| 328 |
+
_strided_from_memmap,
|
| 329 |
+
(
|
| 330 |
+
m.filename,
|
| 331 |
+
a.dtype,
|
| 332 |
+
m.mode,
|
| 333 |
+
offset,
|
| 334 |
+
order,
|
| 335 |
+
a.shape,
|
| 336 |
+
strides,
|
| 337 |
+
total_buffer_len,
|
| 338 |
+
False,
|
| 339 |
+
),
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def reduce_array_memmap_backward(a):
|
| 344 |
+
"""reduce a np.array or a np.memmap from a child process"""
|
| 345 |
+
m = _get_backing_memmap(a)
|
| 346 |
+
if isinstance(m, np.memmap) and m.filename not in JOBLIB_MMAPS:
|
| 347 |
+
# if a is backed by a memmaped file, reconstruct a using the
|
| 348 |
+
# memmaped file.
|
| 349 |
+
return _reduce_memmap_backed(a, m)
|
| 350 |
+
else:
|
| 351 |
+
# a is either a regular (not memmap-backed) numpy array, or an array
|
| 352 |
+
# backed by a shared temporary file created by joblib. In the latter
|
| 353 |
+
# case, in order to limit the lifespan of these temporary files, we
|
| 354 |
+
# serialize the memmap as a regular numpy array, and decref the
|
| 355 |
+
# file backing the memmap (done implicitly in a previously registered
|
| 356 |
+
# finalizer, see ``unlink_on_gc_collect`` for more details)
|
| 357 |
+
return (loads, (dumps(np.asarray(a), protocol=HIGHEST_PROTOCOL),))
|
| 358 |
+
|
| 359 |
+
|
| 360 |
+
class ArrayMemmapForwardReducer(object):
|
| 361 |
+
"""Reducer callable to dump large arrays to memmap files.
|
| 362 |
+
|
| 363 |
+
Parameters
|
| 364 |
+
----------
|
| 365 |
+
max_nbytes: int
|
| 366 |
+
Threshold to trigger memmapping of large arrays to files created
|
| 367 |
+
a folder.
|
| 368 |
+
temp_folder_resolver: callable
|
| 369 |
+
An callable in charge of resolving a temporary folder name where files
|
| 370 |
+
for backing memmapped arrays are created.
|
| 371 |
+
mmap_mode: 'r', 'r+' or 'c'
|
| 372 |
+
Mode for the created memmap datastructure. See the documentation of
|
| 373 |
+
numpy.memmap for more details. Note: 'w+' is coerced to 'r+'
|
| 374 |
+
automatically to avoid zeroing the data on unpickling.
|
| 375 |
+
verbose: int, optional, 0 by default
|
| 376 |
+
If verbose > 0, memmap creations are logged.
|
| 377 |
+
If verbose > 1, both memmap creations, reuse and array pickling are
|
| 378 |
+
logged.
|
| 379 |
+
prewarm: bool, optional, False by default.
|
| 380 |
+
Force a read on newly memmapped array to make sure that OS pre-cache it
|
| 381 |
+
memory. This can be useful to avoid concurrent disk access when the
|
| 382 |
+
same data array is passed to different worker processes.
|
| 383 |
+
"""
|
| 384 |
+
|
| 385 |
+
def __init__(
|
| 386 |
+
self,
|
| 387 |
+
max_nbytes,
|
| 388 |
+
temp_folder_resolver,
|
| 389 |
+
mmap_mode,
|
| 390 |
+
unlink_on_gc_collect,
|
| 391 |
+
verbose=0,
|
| 392 |
+
prewarm=True,
|
| 393 |
+
):
|
| 394 |
+
self._max_nbytes = max_nbytes
|
| 395 |
+
self._temp_folder_resolver = temp_folder_resolver
|
| 396 |
+
self._mmap_mode = mmap_mode
|
| 397 |
+
self.verbose = int(verbose)
|
| 398 |
+
if prewarm == "auto":
|
| 399 |
+
self._prewarm = not self._temp_folder.startswith(SYSTEM_SHARED_MEM_FS)
|
| 400 |
+
else:
|
| 401 |
+
self._prewarm = prewarm
|
| 402 |
+
self._prewarm = prewarm
|
| 403 |
+
self._memmaped_arrays = _WeakArrayKeyMap()
|
| 404 |
+
self._temporary_memmaped_filenames = set()
|
| 405 |
+
self._unlink_on_gc_collect = unlink_on_gc_collect
|
| 406 |
+
|
| 407 |
+
@property
|
| 408 |
+
def _temp_folder(self):
|
| 409 |
+
return self._temp_folder_resolver()
|
| 410 |
+
|
| 411 |
+
def __reduce__(self):
|
| 412 |
+
# The ArrayMemmapForwardReducer is passed to the children processes: it
|
| 413 |
+
# needs to be pickled but the _WeakArrayKeyMap need to be skipped as
|
| 414 |
+
# it's only guaranteed to be consistent with the parent process memory
|
| 415 |
+
# garbage collection.
|
| 416 |
+
# Although this reducer is pickled, it is not needed in its destination
|
| 417 |
+
# process (child processes), as we only use this reducer to send
|
| 418 |
+
# memmaps from the parent process to the children processes. For this
|
| 419 |
+
# reason, we can afford skipping the resolver, (which would otherwise
|
| 420 |
+
# be unpicklable), and pass it as None instead.
|
| 421 |
+
args = (self._max_nbytes, None, self._mmap_mode, self._unlink_on_gc_collect)
|
| 422 |
+
kwargs = {
|
| 423 |
+
"verbose": self.verbose,
|
| 424 |
+
"prewarm": self._prewarm,
|
| 425 |
+
}
|
| 426 |
+
return ArrayMemmapForwardReducer, args, kwargs
|
| 427 |
+
|
| 428 |
+
def __call__(self, a):
|
| 429 |
+
m = _get_backing_memmap(a)
|
| 430 |
+
if m is not None and isinstance(m, np.memmap):
|
| 431 |
+
# a is already backed by a memmap file, let's reuse it directly
|
| 432 |
+
return _reduce_memmap_backed(a, m)
|
| 433 |
+
|
| 434 |
+
if (
|
| 435 |
+
not a.dtype.hasobject
|
| 436 |
+
and self._max_nbytes is not None
|
| 437 |
+
and a.nbytes > self._max_nbytes
|
| 438 |
+
):
|
| 439 |
+
# check that the folder exists (lazily create the pool temp folder
|
| 440 |
+
# if required)
|
| 441 |
+
try:
|
| 442 |
+
os.makedirs(self._temp_folder)
|
| 443 |
+
os.chmod(self._temp_folder, FOLDER_PERMISSIONS)
|
| 444 |
+
except OSError as e:
|
| 445 |
+
if e.errno != errno.EEXIST:
|
| 446 |
+
raise e
|
| 447 |
+
|
| 448 |
+
try:
|
| 449 |
+
basename = self._memmaped_arrays.get(a)
|
| 450 |
+
except KeyError:
|
| 451 |
+
# Generate a new unique random filename. The process and thread
|
| 452 |
+
# ids are only useful for debugging purpose and to make it
|
| 453 |
+
# easier to cleanup orphaned files in case of hard process
|
| 454 |
+
# kill (e.g. by "kill -9" or segfault).
|
| 455 |
+
basename = "{}-{}-{}.pkl".format(
|
| 456 |
+
os.getpid(), id(threading.current_thread()), uuid4().hex
|
| 457 |
+
)
|
| 458 |
+
self._memmaped_arrays.set(a, basename)
|
| 459 |
+
filename = os.path.join(self._temp_folder, basename)
|
| 460 |
+
|
| 461 |
+
# In case the same array with the same content is passed several
|
| 462 |
+
# times to the pool subprocess children, serialize it only once
|
| 463 |
+
|
| 464 |
+
is_new_memmap = filename not in self._temporary_memmaped_filenames
|
| 465 |
+
|
| 466 |
+
# add the memmap to the list of temporary memmaps created by joblib
|
| 467 |
+
self._temporary_memmaped_filenames.add(filename)
|
| 468 |
+
|
| 469 |
+
if self._unlink_on_gc_collect:
|
| 470 |
+
# Bump reference count of the memmap by 1 to account for
|
| 471 |
+
# shared usage of the memmap by a child process. The
|
| 472 |
+
# corresponding decref call will be executed upon calling
|
| 473 |
+
# resource_tracker.maybe_unlink, registered as a finalizer in
|
| 474 |
+
# the child.
|
| 475 |
+
# the incref/decref calls here are only possible when the child
|
| 476 |
+
# and the parent share the same resource_tracker. It is not the
|
| 477 |
+
# case for the multiprocessing backend, but it does not matter
|
| 478 |
+
# because unlinking a memmap from a child process is only
|
| 479 |
+
# useful to control the memory usage of long-lasting child
|
| 480 |
+
# processes, while the multiprocessing-based pools terminate
|
| 481 |
+
# their workers at the end of a map() call.
|
| 482 |
+
resource_tracker.register(filename, "file")
|
| 483 |
+
|
| 484 |
+
if is_new_memmap:
|
| 485 |
+
# Incref each temporary memmap created by joblib one extra
|
| 486 |
+
# time. This means that these memmaps will only be deleted
|
| 487 |
+
# once an extra maybe_unlink() is called, which is done once
|
| 488 |
+
# all the jobs have completed (or been canceled) in the
|
| 489 |
+
# Parallel._terminate_backend() method.
|
| 490 |
+
resource_tracker.register(filename, "file")
|
| 491 |
+
|
| 492 |
+
if not os.path.exists(filename):
|
| 493 |
+
util.debug(
|
| 494 |
+
"[ARRAY DUMP] Pickling new array (shape={}, dtype={}) "
|
| 495 |
+
"creating a new memmap at {}".format(a.shape, a.dtype, filename)
|
| 496 |
+
)
|
| 497 |
+
for dumped_filename in dump(a, filename):
|
| 498 |
+
os.chmod(dumped_filename, FILE_PERMISSIONS)
|
| 499 |
+
|
| 500 |
+
if self._prewarm:
|
| 501 |
+
# Warm up the data by accessing it. This operation ensures
|
| 502 |
+
# that the disk access required to create the memmapping
|
| 503 |
+
# file are performed in the reducing process and avoids
|
| 504 |
+
# concurrent memmap creation in multiple children
|
| 505 |
+
# processes.
|
| 506 |
+
load(filename, mmap_mode=self._mmap_mode).max()
|
| 507 |
+
|
| 508 |
+
else:
|
| 509 |
+
util.debug(
|
| 510 |
+
"[ARRAY DUMP] Pickling known array (shape={}, dtype={}) "
|
| 511 |
+
"reusing memmap file: {}".format(
|
| 512 |
+
a.shape, a.dtype, os.path.basename(filename)
|
| 513 |
+
)
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
# The worker process will use joblib.load to memmap the data
|
| 517 |
+
return (
|
| 518 |
+
load_temporary_memmap,
|
| 519 |
+
(filename, self._mmap_mode, self._unlink_on_gc_collect),
|
| 520 |
+
)
|
| 521 |
+
else:
|
| 522 |
+
# do not convert a into memmap, let pickler do its usual copy with
|
| 523 |
+
# the default system pickler
|
| 524 |
+
util.debug(
|
| 525 |
+
"[ARRAY DUMP] Pickling array (NO MEMMAPPING) (shape={}, "
|
| 526 |
+
" dtype={}).".format(a.shape, a.dtype)
|
| 527 |
+
)
|
| 528 |
+
return (loads, (dumps(a, protocol=HIGHEST_PROTOCOL),))
|
| 529 |
+
|
| 530 |
+
|
| 531 |
+
def get_memmapping_reducers(
|
| 532 |
+
forward_reducers=None,
|
| 533 |
+
backward_reducers=None,
|
| 534 |
+
temp_folder_resolver=None,
|
| 535 |
+
max_nbytes=1e6,
|
| 536 |
+
mmap_mode="r",
|
| 537 |
+
verbose=0,
|
| 538 |
+
prewarm=False,
|
| 539 |
+
unlink_on_gc_collect=True,
|
| 540 |
+
**kwargs,
|
| 541 |
+
):
|
| 542 |
+
"""Construct a pair of memmapping reducer linked to a tmpdir.
|
| 543 |
+
|
| 544 |
+
This function manage the creation and the clean up of the temporary folders
|
| 545 |
+
underlying the memory maps and should be use to get the reducers necessary
|
| 546 |
+
to construct joblib pool or executor.
|
| 547 |
+
"""
|
| 548 |
+
if forward_reducers is None:
|
| 549 |
+
forward_reducers = dict()
|
| 550 |
+
if backward_reducers is None:
|
| 551 |
+
backward_reducers = dict()
|
| 552 |
+
|
| 553 |
+
if np is not None:
|
| 554 |
+
# Register smart numpy.ndarray reducers that detects memmap backed
|
| 555 |
+
# arrays and that is also able to dump to memmap large in-memory
|
| 556 |
+
# arrays over the max_nbytes threshold
|
| 557 |
+
forward_reduce_ndarray = ArrayMemmapForwardReducer(
|
| 558 |
+
max_nbytes,
|
| 559 |
+
temp_folder_resolver,
|
| 560 |
+
mmap_mode,
|
| 561 |
+
unlink_on_gc_collect,
|
| 562 |
+
verbose,
|
| 563 |
+
prewarm=prewarm,
|
| 564 |
+
)
|
| 565 |
+
forward_reducers[np.ndarray] = forward_reduce_ndarray
|
| 566 |
+
forward_reducers[np.memmap] = forward_reduce_ndarray
|
| 567 |
+
|
| 568 |
+
# Communication from child process to the parent process always
|
| 569 |
+
# pickles in-memory numpy.ndarray without dumping them as memmap
|
| 570 |
+
# to avoid confusing the caller and make it tricky to collect the
|
| 571 |
+
# temporary folder
|
| 572 |
+
backward_reducers[np.ndarray] = reduce_array_memmap_backward
|
| 573 |
+
backward_reducers[np.memmap] = reduce_array_memmap_backward
|
| 574 |
+
|
| 575 |
+
return forward_reducers, backward_reducers
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
class TemporaryResourcesManager(object):
|
| 579 |
+
"""Stateful object able to manage temporary folder and pickles
|
| 580 |
+
|
| 581 |
+
It exposes:
|
| 582 |
+
- a per-context folder name resolving API that memmap-based reducers will
|
| 583 |
+
rely on to know where to pickle the temporary memmaps
|
| 584 |
+
- a temporary file/folder management API that internally uses the
|
| 585 |
+
resource_tracker.
|
| 586 |
+
"""
|
| 587 |
+
|
| 588 |
+
def __init__(self, temp_folder_root=None, context_id=None):
|
| 589 |
+
self._current_temp_folder = None
|
| 590 |
+
self._temp_folder_root = temp_folder_root
|
| 591 |
+
self._use_shared_mem = None
|
| 592 |
+
self._cached_temp_folders = dict()
|
| 593 |
+
self._id = uuid4().hex
|
| 594 |
+
self._finalizers = {}
|
| 595 |
+
if context_id is None:
|
| 596 |
+
# It would be safer to not assign a default context id (less silent
|
| 597 |
+
# bugs), but doing this while maintaining backward compatibility
|
| 598 |
+
# with the previous, context-unaware version get_memmaping_executor
|
| 599 |
+
# exposes too many low-level details.
|
| 600 |
+
context_id = uuid4().hex
|
| 601 |
+
self.set_current_context(context_id)
|
| 602 |
+
|
| 603 |
+
def set_current_context(self, context_id):
|
| 604 |
+
self._current_context_id = context_id
|
| 605 |
+
self.register_new_context(context_id)
|
| 606 |
+
|
| 607 |
+
def register_new_context(self, context_id):
|
| 608 |
+
# Prepare a sub-folder name specific to a context (usually a unique id
|
| 609 |
+
# generated by each instance of the Parallel class). Do not create in
|
| 610 |
+
# advance to spare FS write access if no array is to be dumped).
|
| 611 |
+
if context_id in self._cached_temp_folders:
|
| 612 |
+
return
|
| 613 |
+
else:
|
| 614 |
+
# During its lifecycle, one Parallel object can have several
|
| 615 |
+
# executors associated to it (for instance, if a loky worker raises
|
| 616 |
+
# an exception, joblib shutdowns the executor and instantly
|
| 617 |
+
# recreates a new one before raising the error - see
|
| 618 |
+
# ``ensure_ready``. Because we don't want two executors tied to
|
| 619 |
+
# the same Parallel object (and thus the same context id) to
|
| 620 |
+
# register/use/delete the same folder, we also add an id specific
|
| 621 |
+
# to the current Manager (and thus specific to its associated
|
| 622 |
+
# executor) to the folder name.
|
| 623 |
+
new_folder_name = "joblib_memmapping_folder_{}_{}_{}".format(
|
| 624 |
+
os.getpid(), self._id, context_id
|
| 625 |
+
)
|
| 626 |
+
new_folder_path, _ = _get_temp_dir(new_folder_name, self._temp_folder_root)
|
| 627 |
+
self.register_folder_finalizer(new_folder_path, context_id)
|
| 628 |
+
self._cached_temp_folders[context_id] = new_folder_path
|
| 629 |
+
|
| 630 |
+
def resolve_temp_folder_name(self):
|
| 631 |
+
"""Return a folder name specific to the currently activated context"""
|
| 632 |
+
return self._cached_temp_folders[self._current_context_id]
|
| 633 |
+
|
| 634 |
+
# resource management API
|
| 635 |
+
|
| 636 |
+
def register_folder_finalizer(self, pool_subfolder, context_id):
|
| 637 |
+
# Register the garbage collector at program exit in case caller forgets
|
| 638 |
+
# to call terminate explicitly: note we do not pass any reference to
|
| 639 |
+
# ensure that this callback won't prevent garbage collection of
|
| 640 |
+
# parallel instance and related file handler resources such as POSIX
|
| 641 |
+
# semaphores and pipes
|
| 642 |
+
pool_module_name = whichmodule(delete_folder, "delete_folder")
|
| 643 |
+
resource_tracker.register(pool_subfolder, "folder")
|
| 644 |
+
|
| 645 |
+
def _cleanup():
|
| 646 |
+
# In some cases the Python runtime seems to set delete_folder to
|
| 647 |
+
# None just before exiting when accessing the delete_folder
|
| 648 |
+
# function from the closure namespace. So instead we reimport
|
| 649 |
+
# the delete_folder function explicitly.
|
| 650 |
+
# https://github.com/joblib/joblib/issues/328
|
| 651 |
+
# We cannot just use from 'joblib.pool import delete_folder'
|
| 652 |
+
# because joblib should only use relative imports to allow
|
| 653 |
+
# easy vendoring.
|
| 654 |
+
delete_folder = __import__(
|
| 655 |
+
pool_module_name, fromlist=["delete_folder"]
|
| 656 |
+
).delete_folder
|
| 657 |
+
try:
|
| 658 |
+
delete_folder(pool_subfolder, allow_non_empty=True)
|
| 659 |
+
resource_tracker.unregister(pool_subfolder, "folder")
|
| 660 |
+
except OSError:
|
| 661 |
+
warnings.warn(
|
| 662 |
+
"Failed to delete temporary folder: {}".format(pool_subfolder)
|
| 663 |
+
)
|
| 664 |
+
|
| 665 |
+
self._finalizers[context_id] = atexit.register(_cleanup)
|
| 666 |
+
|
| 667 |
+
def _clean_temporary_resources(
|
| 668 |
+
self, context_id=None, force=False, allow_non_empty=False
|
| 669 |
+
):
|
| 670 |
+
"""Clean temporary resources created by a process-based pool"""
|
| 671 |
+
if context_id is None:
|
| 672 |
+
# Iterates over a copy of the cache keys to avoid Error due to
|
| 673 |
+
# iterating over a changing size dictionary.
|
| 674 |
+
for context_id in list(self._cached_temp_folders):
|
| 675 |
+
self._clean_temporary_resources(
|
| 676 |
+
context_id, force=force, allow_non_empty=allow_non_empty
|
| 677 |
+
)
|
| 678 |
+
else:
|
| 679 |
+
temp_folder = self._cached_temp_folders.get(context_id)
|
| 680 |
+
if temp_folder and os.path.exists(temp_folder):
|
| 681 |
+
for filename in os.listdir(temp_folder):
|
| 682 |
+
if force:
|
| 683 |
+
# Some workers have failed and the ref counted might
|
| 684 |
+
# be off. The workers should have shut down by this
|
| 685 |
+
# time so forcefully clean up the files.
|
| 686 |
+
resource_tracker.unregister(
|
| 687 |
+
os.path.join(temp_folder, filename), "file"
|
| 688 |
+
)
|
| 689 |
+
else:
|
| 690 |
+
resource_tracker.maybe_unlink(
|
| 691 |
+
os.path.join(temp_folder, filename), "file"
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
# When forcing clean-up, try to delete the folder even if some
|
| 695 |
+
# files are still in it. Otherwise, try to delete the folder
|
| 696 |
+
allow_non_empty |= force
|
| 697 |
+
|
| 698 |
+
# Clean up the folder if possible, either if it is empty or
|
| 699 |
+
# if none of the files in it are in used and allow_non_empty.
|
| 700 |
+
try:
|
| 701 |
+
delete_folder(temp_folder, allow_non_empty=allow_non_empty)
|
| 702 |
+
# Forget the folder once it has been deleted
|
| 703 |
+
self._cached_temp_folders.pop(context_id, None)
|
| 704 |
+
resource_tracker.unregister(temp_folder, "folder")
|
| 705 |
+
|
| 706 |
+
# Also cancel the finalizers that gets triggered at gc.
|
| 707 |
+
finalizer = self._finalizers.pop(context_id, None)
|
| 708 |
+
if finalizer is not None:
|
| 709 |
+
atexit.unregister(finalizer)
|
| 710 |
+
|
| 711 |
+
except OSError:
|
| 712 |
+
# Temporary folder cannot be deleted right now.
|
| 713 |
+
# This folder will be cleaned up by an atexit
|
| 714 |
+
# finalizer registered by the memmapping_reducer.
|
| 715 |
+
pass
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_multiprocessing_helpers.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Helper module to factorize the conditional multiprocessing import logic
|
| 2 |
+
|
| 3 |
+
We use a distinct module to simplify import statements and avoid introducing
|
| 4 |
+
circular dependencies (for instance for the assert_spawning name).
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import os
|
| 8 |
+
import warnings
|
| 9 |
+
|
| 10 |
+
# Obtain possible configuration from the environment, assuming 1 (on)
|
| 11 |
+
# by default, upon 0 set to None. Should instructively fail if some non
|
| 12 |
+
# 0/1 value is set.
|
| 13 |
+
mp = int(os.environ.get("JOBLIB_MULTIPROCESSING", 1)) or None
|
| 14 |
+
if mp:
|
| 15 |
+
try:
|
| 16 |
+
import _multiprocessing # noqa
|
| 17 |
+
import multiprocessing as mp
|
| 18 |
+
except ImportError:
|
| 19 |
+
mp = None
|
| 20 |
+
|
| 21 |
+
# 2nd stage: validate that locking is available on the system and
|
| 22 |
+
# issue a warning if not
|
| 23 |
+
if mp is not None:
|
| 24 |
+
try:
|
| 25 |
+
# try to create a named semaphore using SemLock to make sure they are
|
| 26 |
+
# available on this platform. We use the low level object
|
| 27 |
+
# _multiprocessing.SemLock to avoid spawning a resource tracker on
|
| 28 |
+
# Unix system or changing the default backend.
|
| 29 |
+
import tempfile
|
| 30 |
+
from _multiprocessing import SemLock
|
| 31 |
+
|
| 32 |
+
_rand = tempfile._RandomNameSequence()
|
| 33 |
+
for i in range(100):
|
| 34 |
+
try:
|
| 35 |
+
name = "/joblib-{}-{}".format(os.getpid(), next(_rand))
|
| 36 |
+
_sem = SemLock(0, 0, 1, name=name, unlink=True)
|
| 37 |
+
del _sem # cleanup
|
| 38 |
+
break
|
| 39 |
+
except FileExistsError as e: # pragma: no cover
|
| 40 |
+
if i >= 99:
|
| 41 |
+
raise FileExistsError("cannot find name for semaphore") from e
|
| 42 |
+
except (FileExistsError, AttributeError, ImportError, OSError) as e:
|
| 43 |
+
mp = None
|
| 44 |
+
warnings.warn("%s. joblib will operate in serial mode" % (e,))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
# 3rd stage: backward compat for the assert_spawning helper
|
| 48 |
+
if mp is not None:
|
| 49 |
+
from multiprocessing.context import assert_spawning
|
| 50 |
+
else:
|
| 51 |
+
assert_spawning = None
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_parallel_backends.py
ADDED
|
@@ -0,0 +1,753 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import contextlib
|
| 6 |
+
import gc
|
| 7 |
+
import os
|
| 8 |
+
import threading
|
| 9 |
+
import warnings
|
| 10 |
+
from abc import ABCMeta, abstractmethod
|
| 11 |
+
|
| 12 |
+
from ._multiprocessing_helpers import mp
|
| 13 |
+
from ._utils import (
|
| 14 |
+
_retrieve_traceback_capturing_wrapped_call,
|
| 15 |
+
_TracebackCapturingWrapper,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
if mp is not None:
|
| 19 |
+
from multiprocessing.pool import ThreadPool
|
| 20 |
+
|
| 21 |
+
from .executor import get_memmapping_executor
|
| 22 |
+
|
| 23 |
+
# Import loky only if multiprocessing is present
|
| 24 |
+
from .externals.loky import cpu_count, process_executor
|
| 25 |
+
from .externals.loky.process_executor import ShutdownExecutorError
|
| 26 |
+
from .pool import MemmappingPool
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class ParallelBackendBase(metaclass=ABCMeta):
|
| 30 |
+
"""Helper abc which defines all methods a ParallelBackend must implement"""
|
| 31 |
+
|
| 32 |
+
default_n_jobs = 1
|
| 33 |
+
|
| 34 |
+
supports_inner_max_num_threads = False
|
| 35 |
+
|
| 36 |
+
# This flag was introduced for backward compatibility reasons.
|
| 37 |
+
# New backends should always set it to True and implement the
|
| 38 |
+
# `retrieve_result_callback` method.
|
| 39 |
+
supports_retrieve_callback = False
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def supports_return_generator(self):
|
| 43 |
+
return self.supports_retrieve_callback
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def supports_timeout(self):
|
| 47 |
+
return self.supports_retrieve_callback
|
| 48 |
+
|
| 49 |
+
nesting_level = None
|
| 50 |
+
|
| 51 |
+
def __init__(
|
| 52 |
+
self, nesting_level=None, inner_max_num_threads=None, **backend_kwargs
|
| 53 |
+
):
|
| 54 |
+
super().__init__()
|
| 55 |
+
self.nesting_level = nesting_level
|
| 56 |
+
self.inner_max_num_threads = inner_max_num_threads
|
| 57 |
+
self.backend_kwargs = backend_kwargs
|
| 58 |
+
|
| 59 |
+
MAX_NUM_THREADS_VARS = [
|
| 60 |
+
"OMP_NUM_THREADS",
|
| 61 |
+
"OPENBLAS_NUM_THREADS",
|
| 62 |
+
"MKL_NUM_THREADS",
|
| 63 |
+
"BLIS_NUM_THREADS",
|
| 64 |
+
"VECLIB_MAXIMUM_THREADS",
|
| 65 |
+
"NUMBA_NUM_THREADS",
|
| 66 |
+
"NUMEXPR_NUM_THREADS",
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
TBB_ENABLE_IPC_VAR = "ENABLE_IPC"
|
| 70 |
+
|
| 71 |
+
@abstractmethod
|
| 72 |
+
def effective_n_jobs(self, n_jobs):
|
| 73 |
+
"""Determine the number of jobs that can actually run in parallel
|
| 74 |
+
|
| 75 |
+
n_jobs is the number of workers requested by the callers. Passing
|
| 76 |
+
n_jobs=-1 means requesting all available workers for instance matching
|
| 77 |
+
the number of CPU cores on the worker host(s).
|
| 78 |
+
|
| 79 |
+
This method should return a guesstimate of the number of workers that
|
| 80 |
+
can actually perform work concurrently. The primary use case is to make
|
| 81 |
+
it possible for the caller to know in how many chunks to slice the
|
| 82 |
+
work.
|
| 83 |
+
|
| 84 |
+
In general working on larger data chunks is more efficient (less
|
| 85 |
+
scheduling overhead and better use of CPU cache prefetching heuristics)
|
| 86 |
+
as long as all the workers have enough work to do.
|
| 87 |
+
"""
|
| 88 |
+
|
| 89 |
+
def apply_async(self, func, callback=None):
|
| 90 |
+
"""Deprecated: implement `submit` instead."""
|
| 91 |
+
raise NotImplementedError("Implement `submit` instead.")
|
| 92 |
+
|
| 93 |
+
def submit(self, func, callback=None):
|
| 94 |
+
"""Schedule a function to be run and return a future-like object.
|
| 95 |
+
|
| 96 |
+
This method should return a future-like object that allow tracking
|
| 97 |
+
the progress of the task.
|
| 98 |
+
|
| 99 |
+
If ``supports_retrieve_callback`` is False, the return value of this
|
| 100 |
+
method is passed to ``retrieve_result`` instead of calling
|
| 101 |
+
``retrieve_result_callback``.
|
| 102 |
+
|
| 103 |
+
Parameters
|
| 104 |
+
----------
|
| 105 |
+
func: callable
|
| 106 |
+
The function to be run in parallel.
|
| 107 |
+
|
| 108 |
+
callback: callable
|
| 109 |
+
A callable that will be called when the task is completed. This callable
|
| 110 |
+
is a wrapper around ``retrieve_result_callback``. This should be added
|
| 111 |
+
to the future-like object returned by this method, so that the callback
|
| 112 |
+
is called when the task is completed.
|
| 113 |
+
|
| 114 |
+
For future-like backends, this can be achieved with something like
|
| 115 |
+
``future.add_done_callback(callback)``.
|
| 116 |
+
|
| 117 |
+
Returns
|
| 118 |
+
-------
|
| 119 |
+
future: future-like
|
| 120 |
+
A future-like object to track the execution of the submitted function.
|
| 121 |
+
"""
|
| 122 |
+
warnings.warn(
|
| 123 |
+
"`apply_async` is deprecated, implement and use `submit` instead.",
|
| 124 |
+
DeprecationWarning,
|
| 125 |
+
)
|
| 126 |
+
return self.apply_async(func, callback)
|
| 127 |
+
|
| 128 |
+
def retrieve_result_callback(self, out):
|
| 129 |
+
"""Called within the callback function passed to `submit`.
|
| 130 |
+
|
| 131 |
+
This method can customise how the result of the function is retrieved
|
| 132 |
+
from the future-like object.
|
| 133 |
+
|
| 134 |
+
Parameters
|
| 135 |
+
----------
|
| 136 |
+
future: future-like
|
| 137 |
+
The future-like object returned by the `submit` method.
|
| 138 |
+
|
| 139 |
+
Returns
|
| 140 |
+
-------
|
| 141 |
+
result: object
|
| 142 |
+
The result of the function executed in parallel.
|
| 143 |
+
"""
|
| 144 |
+
|
| 145 |
+
def retrieve_result(self, out, timeout=None):
|
| 146 |
+
"""Hook to retrieve the result when support_retrieve_callback=False.
|
| 147 |
+
|
| 148 |
+
The argument `out` is the result of the `submit` call. This method
|
| 149 |
+
should return the result of the computation or raise an exception if
|
| 150 |
+
the computation failed.
|
| 151 |
+
"""
|
| 152 |
+
if self.supports_timeout:
|
| 153 |
+
return out.get(timeout=timeout)
|
| 154 |
+
else:
|
| 155 |
+
return out.get()
|
| 156 |
+
|
| 157 |
+
def configure(
|
| 158 |
+
self, n_jobs=1, parallel=None, prefer=None, require=None, **backend_kwargs
|
| 159 |
+
):
|
| 160 |
+
"""Reconfigure the backend and return the number of workers.
|
| 161 |
+
|
| 162 |
+
This makes it possible to reuse an existing backend instance for
|
| 163 |
+
successive independent calls to Parallel with different parameters.
|
| 164 |
+
"""
|
| 165 |
+
self.parallel = parallel
|
| 166 |
+
return self.effective_n_jobs(n_jobs)
|
| 167 |
+
|
| 168 |
+
def start_call(self):
|
| 169 |
+
"""Call-back method called at the beginning of a Parallel call"""
|
| 170 |
+
|
| 171 |
+
def stop_call(self):
|
| 172 |
+
"""Call-back method called at the end of a Parallel call"""
|
| 173 |
+
|
| 174 |
+
def terminate(self):
|
| 175 |
+
"""Shutdown the workers and free the shared memory."""
|
| 176 |
+
|
| 177 |
+
def compute_batch_size(self):
|
| 178 |
+
"""Determine the optimal batch size"""
|
| 179 |
+
return 1
|
| 180 |
+
|
| 181 |
+
def batch_completed(self, batch_size, duration):
|
| 182 |
+
"""Callback indicate how long it took to run a batch"""
|
| 183 |
+
|
| 184 |
+
def abort_everything(self, ensure_ready=True):
|
| 185 |
+
"""Abort any running tasks
|
| 186 |
+
|
| 187 |
+
This is called when an exception has been raised when executing a task
|
| 188 |
+
and all the remaining tasks will be ignored and can therefore be
|
| 189 |
+
aborted to spare computation resources.
|
| 190 |
+
|
| 191 |
+
If ensure_ready is True, the backend should be left in an operating
|
| 192 |
+
state as future tasks might be re-submitted via that same backend
|
| 193 |
+
instance.
|
| 194 |
+
|
| 195 |
+
If ensure_ready is False, the implementer of this method can decide
|
| 196 |
+
to leave the backend in a closed / terminated state as no new task
|
| 197 |
+
are expected to be submitted to this backend.
|
| 198 |
+
|
| 199 |
+
Setting ensure_ready to False is an optimization that can be leveraged
|
| 200 |
+
when aborting tasks via killing processes from a local process pool
|
| 201 |
+
managed by the backend it-self: if we expect no new tasks, there is no
|
| 202 |
+
point in re-creating new workers.
|
| 203 |
+
"""
|
| 204 |
+
# Does nothing by default: to be overridden in subclasses when
|
| 205 |
+
# canceling tasks is possible.
|
| 206 |
+
pass
|
| 207 |
+
|
| 208 |
+
def get_nested_backend(self):
|
| 209 |
+
"""Backend instance to be used by nested Parallel calls.
|
| 210 |
+
|
| 211 |
+
By default a thread-based backend is used for the first level of
|
| 212 |
+
nesting. Beyond, switch to sequential backend to avoid spawning too
|
| 213 |
+
many threads on the host.
|
| 214 |
+
"""
|
| 215 |
+
nesting_level = getattr(self, "nesting_level", 0) + 1
|
| 216 |
+
if nesting_level > 1:
|
| 217 |
+
return SequentialBackend(nesting_level=nesting_level), None
|
| 218 |
+
else:
|
| 219 |
+
return ThreadingBackend(nesting_level=nesting_level), None
|
| 220 |
+
|
| 221 |
+
def _prepare_worker_env(self, n_jobs):
|
| 222 |
+
"""Return environment variables limiting threadpools in external libs.
|
| 223 |
+
|
| 224 |
+
This function return a dict containing environment variables to pass
|
| 225 |
+
when creating a pool of process. These environment variables limit the
|
| 226 |
+
number of threads to `n_threads` for OpenMP, MKL, Accelerated and
|
| 227 |
+
OpenBLAS libraries in the child processes.
|
| 228 |
+
"""
|
| 229 |
+
explicit_n_threads = self.inner_max_num_threads
|
| 230 |
+
default_n_threads = max(cpu_count() // n_jobs, 1)
|
| 231 |
+
|
| 232 |
+
# Set the inner environment variables to self.inner_max_num_threads if
|
| 233 |
+
# it is given. Else, default to cpu_count // n_jobs unless the variable
|
| 234 |
+
# is already present in the parent process environment.
|
| 235 |
+
env = {}
|
| 236 |
+
for var in self.MAX_NUM_THREADS_VARS:
|
| 237 |
+
if explicit_n_threads is None:
|
| 238 |
+
var_value = os.environ.get(var, default_n_threads)
|
| 239 |
+
else:
|
| 240 |
+
var_value = explicit_n_threads
|
| 241 |
+
|
| 242 |
+
env[var] = str(var_value)
|
| 243 |
+
|
| 244 |
+
if self.TBB_ENABLE_IPC_VAR not in os.environ:
|
| 245 |
+
# To avoid over-subscription when using TBB, let the TBB schedulers
|
| 246 |
+
# use Inter Process Communication to coordinate:
|
| 247 |
+
env[self.TBB_ENABLE_IPC_VAR] = "1"
|
| 248 |
+
return env
|
| 249 |
+
|
| 250 |
+
@contextlib.contextmanager
|
| 251 |
+
def retrieval_context(self):
|
| 252 |
+
"""Context manager to manage an execution context.
|
| 253 |
+
|
| 254 |
+
Calls to Parallel.retrieve will be made inside this context.
|
| 255 |
+
|
| 256 |
+
By default, this does nothing. It may be useful for subclasses to
|
| 257 |
+
handle nested parallelism. In particular, it may be required to avoid
|
| 258 |
+
deadlocks if a backend manages a fixed number of workers, when those
|
| 259 |
+
workers may be asked to do nested Parallel calls. Without
|
| 260 |
+
'retrieval_context' this could lead to deadlock, as all the workers
|
| 261 |
+
managed by the backend may be "busy" waiting for the nested parallel
|
| 262 |
+
calls to finish, but the backend has no free workers to execute those
|
| 263 |
+
tasks.
|
| 264 |
+
"""
|
| 265 |
+
yield
|
| 266 |
+
|
| 267 |
+
@staticmethod
|
| 268 |
+
def in_main_thread():
|
| 269 |
+
return isinstance(threading.current_thread(), threading._MainThread)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class SequentialBackend(ParallelBackendBase):
|
| 273 |
+
"""A ParallelBackend which will execute all batches sequentially.
|
| 274 |
+
|
| 275 |
+
Does not use/create any threading objects, and hence has minimal
|
| 276 |
+
overhead. Used when n_jobs == 1.
|
| 277 |
+
"""
|
| 278 |
+
|
| 279 |
+
uses_threads = True
|
| 280 |
+
supports_timeout = False
|
| 281 |
+
supports_retrieve_callback = False
|
| 282 |
+
supports_sharedmem = True
|
| 283 |
+
|
| 284 |
+
def effective_n_jobs(self, n_jobs):
|
| 285 |
+
"""Determine the number of jobs which are going to run in parallel"""
|
| 286 |
+
if n_jobs == 0:
|
| 287 |
+
raise ValueError("n_jobs == 0 in Parallel has no meaning")
|
| 288 |
+
return 1
|
| 289 |
+
|
| 290 |
+
def submit(self, func, callback=None):
|
| 291 |
+
"""Schedule a func to be run"""
|
| 292 |
+
raise RuntimeError("Should never be called for SequentialBackend.")
|
| 293 |
+
|
| 294 |
+
def retrieve_result_callback(self, out):
|
| 295 |
+
raise RuntimeError("Should never be called for SequentialBackend.")
|
| 296 |
+
|
| 297 |
+
def get_nested_backend(self):
|
| 298 |
+
# import is not top level to avoid cyclic import errors.
|
| 299 |
+
from .parallel import get_active_backend
|
| 300 |
+
|
| 301 |
+
# SequentialBackend should neither change the nesting level, the
|
| 302 |
+
# default backend or the number of jobs. Just return the current one.
|
| 303 |
+
return get_active_backend()
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
class PoolManagerMixin(object):
|
| 307 |
+
"""A helper class for managing pool of workers."""
|
| 308 |
+
|
| 309 |
+
_pool = None
|
| 310 |
+
|
| 311 |
+
def effective_n_jobs(self, n_jobs):
|
| 312 |
+
"""Determine the number of jobs which are going to run in parallel"""
|
| 313 |
+
if n_jobs == 0:
|
| 314 |
+
raise ValueError("n_jobs == 0 in Parallel has no meaning")
|
| 315 |
+
elif mp is None or n_jobs is None:
|
| 316 |
+
# multiprocessing is not available or disabled, fallback
|
| 317 |
+
# to sequential mode
|
| 318 |
+
return 1
|
| 319 |
+
elif n_jobs < 0:
|
| 320 |
+
n_jobs = max(cpu_count() + 1 + n_jobs, 1)
|
| 321 |
+
return n_jobs
|
| 322 |
+
|
| 323 |
+
def terminate(self):
|
| 324 |
+
"""Shutdown the process or thread pool"""
|
| 325 |
+
if self._pool is not None:
|
| 326 |
+
self._pool.close()
|
| 327 |
+
self._pool.terminate() # terminate does a join()
|
| 328 |
+
self._pool = None
|
| 329 |
+
|
| 330 |
+
def _get_pool(self):
|
| 331 |
+
"""Used by `submit` to make it possible to implement lazy init"""
|
| 332 |
+
return self._pool
|
| 333 |
+
|
| 334 |
+
def submit(self, func, callback=None):
|
| 335 |
+
"""Schedule a func to be run"""
|
| 336 |
+
# Here, we need a wrapper to avoid crashes on KeyboardInterruptErrors.
|
| 337 |
+
# We also call the callback on error, to make sure the pool does not
|
| 338 |
+
# wait on crashed jobs.
|
| 339 |
+
return self._get_pool().apply_async(
|
| 340 |
+
_TracebackCapturingWrapper(func),
|
| 341 |
+
(),
|
| 342 |
+
callback=callback,
|
| 343 |
+
error_callback=callback,
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
def retrieve_result_callback(self, result):
|
| 347 |
+
"""Mimic concurrent.futures results, raising an error if needed."""
|
| 348 |
+
# In the multiprocessing Pool API, the callback are called with the
|
| 349 |
+
# result value as an argument so `result`(`out`) is the output of
|
| 350 |
+
# job.get(). It's either the result or the exception raised while
|
| 351 |
+
# collecting the result.
|
| 352 |
+
return _retrieve_traceback_capturing_wrapped_call(result)
|
| 353 |
+
|
| 354 |
+
def abort_everything(self, ensure_ready=True):
|
| 355 |
+
"""Shutdown the pool and restart a new one with the same parameters"""
|
| 356 |
+
self.terminate()
|
| 357 |
+
if ensure_ready:
|
| 358 |
+
self.configure(
|
| 359 |
+
n_jobs=self.parallel.n_jobs,
|
| 360 |
+
parallel=self.parallel,
|
| 361 |
+
**self.parallel._backend_kwargs,
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class AutoBatchingMixin(object):
|
| 366 |
+
"""A helper class for automagically batching jobs."""
|
| 367 |
+
|
| 368 |
+
# In seconds, should be big enough to hide multiprocessing dispatching
|
| 369 |
+
# overhead.
|
| 370 |
+
# This settings was found by running benchmarks/bench_auto_batching.py
|
| 371 |
+
# with various parameters on various platforms.
|
| 372 |
+
MIN_IDEAL_BATCH_DURATION = 0.2
|
| 373 |
+
|
| 374 |
+
# Should not be too high to avoid stragglers: long jobs running alone
|
| 375 |
+
# on a single worker while other workers have no work to process any more.
|
| 376 |
+
MAX_IDEAL_BATCH_DURATION = 2
|
| 377 |
+
|
| 378 |
+
# Batching counters default values
|
| 379 |
+
_DEFAULT_EFFECTIVE_BATCH_SIZE = 1
|
| 380 |
+
_DEFAULT_SMOOTHED_BATCH_DURATION = 0.0
|
| 381 |
+
|
| 382 |
+
def __init__(self, **kwargs):
|
| 383 |
+
super().__init__(**kwargs)
|
| 384 |
+
self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE
|
| 385 |
+
self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION
|
| 386 |
+
|
| 387 |
+
def compute_batch_size(self):
|
| 388 |
+
"""Determine the optimal batch size"""
|
| 389 |
+
old_batch_size = self._effective_batch_size
|
| 390 |
+
batch_duration = self._smoothed_batch_duration
|
| 391 |
+
if batch_duration > 0 and batch_duration < self.MIN_IDEAL_BATCH_DURATION:
|
| 392 |
+
# The current batch size is too small: the duration of the
|
| 393 |
+
# processing of a batch of task is not large enough to hide
|
| 394 |
+
# the scheduling overhead.
|
| 395 |
+
ideal_batch_size = int(
|
| 396 |
+
old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration
|
| 397 |
+
)
|
| 398 |
+
# Multiply by two to limit oscilations between min and max.
|
| 399 |
+
ideal_batch_size *= 2
|
| 400 |
+
|
| 401 |
+
# dont increase the batch size too fast to limit huge batch sizes
|
| 402 |
+
# potentially leading to starving worker
|
| 403 |
+
batch_size = min(2 * old_batch_size, ideal_batch_size)
|
| 404 |
+
|
| 405 |
+
batch_size = max(batch_size, 1)
|
| 406 |
+
|
| 407 |
+
self._effective_batch_size = batch_size
|
| 408 |
+
if self.parallel.verbose >= 10:
|
| 409 |
+
self.parallel._print(
|
| 410 |
+
f"Batch computation too fast ({batch_duration}s.) "
|
| 411 |
+
f"Setting batch_size={batch_size}."
|
| 412 |
+
)
|
| 413 |
+
elif batch_duration > self.MAX_IDEAL_BATCH_DURATION and old_batch_size >= 2:
|
| 414 |
+
# The current batch size is too big. If we schedule overly long
|
| 415 |
+
# running batches some CPUs might wait with nothing left to do
|
| 416 |
+
# while a couple of CPUs a left processing a few long running
|
| 417 |
+
# batches. Better reduce the batch size a bit to limit the
|
| 418 |
+
# likelihood of scheduling such stragglers.
|
| 419 |
+
|
| 420 |
+
# decrease the batch size quickly to limit potential starving
|
| 421 |
+
ideal_batch_size = int(
|
| 422 |
+
old_batch_size * self.MIN_IDEAL_BATCH_DURATION / batch_duration
|
| 423 |
+
)
|
| 424 |
+
# Multiply by two to limit oscilations between min and max.
|
| 425 |
+
batch_size = max(2 * ideal_batch_size, 1)
|
| 426 |
+
self._effective_batch_size = batch_size
|
| 427 |
+
if self.parallel.verbose >= 10:
|
| 428 |
+
self.parallel._print(
|
| 429 |
+
f"Batch computation too slow ({batch_duration}s.) "
|
| 430 |
+
f"Setting batch_size={batch_size}."
|
| 431 |
+
)
|
| 432 |
+
else:
|
| 433 |
+
# No batch size adjustment
|
| 434 |
+
batch_size = old_batch_size
|
| 435 |
+
|
| 436 |
+
if batch_size != old_batch_size:
|
| 437 |
+
# Reset estimation of the smoothed mean batch duration: this
|
| 438 |
+
# estimate is updated in the multiprocessing apply_async
|
| 439 |
+
# CallBack as long as the batch_size is constant. Therefore
|
| 440 |
+
# we need to reset the estimate whenever we re-tune the batch
|
| 441 |
+
# size.
|
| 442 |
+
self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION
|
| 443 |
+
|
| 444 |
+
return batch_size
|
| 445 |
+
|
| 446 |
+
def batch_completed(self, batch_size, duration):
|
| 447 |
+
"""Callback indicate how long it took to run a batch"""
|
| 448 |
+
if batch_size == self._effective_batch_size:
|
| 449 |
+
# Update the smoothed streaming estimate of the duration of a batch
|
| 450 |
+
# from dispatch to completion
|
| 451 |
+
old_duration = self._smoothed_batch_duration
|
| 452 |
+
if old_duration == self._DEFAULT_SMOOTHED_BATCH_DURATION:
|
| 453 |
+
# First record of duration for this batch size after the last
|
| 454 |
+
# reset.
|
| 455 |
+
new_duration = duration
|
| 456 |
+
else:
|
| 457 |
+
# Update the exponentially weighted average of the duration of
|
| 458 |
+
# batch for the current effective size.
|
| 459 |
+
new_duration = 0.8 * old_duration + 0.2 * duration
|
| 460 |
+
self._smoothed_batch_duration = new_duration
|
| 461 |
+
|
| 462 |
+
def reset_batch_stats(self):
|
| 463 |
+
"""Reset batch statistics to default values.
|
| 464 |
+
|
| 465 |
+
This avoids interferences with future jobs.
|
| 466 |
+
"""
|
| 467 |
+
self._effective_batch_size = self._DEFAULT_EFFECTIVE_BATCH_SIZE
|
| 468 |
+
self._smoothed_batch_duration = self._DEFAULT_SMOOTHED_BATCH_DURATION
|
| 469 |
+
|
| 470 |
+
|
| 471 |
+
class ThreadingBackend(PoolManagerMixin, ParallelBackendBase):
|
| 472 |
+
"""A ParallelBackend which will use a thread pool to execute batches in.
|
| 473 |
+
|
| 474 |
+
This is a low-overhead backend but it suffers from the Python Global
|
| 475 |
+
Interpreter Lock if the called function relies a lot on Python objects.
|
| 476 |
+
Mostly useful when the execution bottleneck is a compiled extension that
|
| 477 |
+
explicitly releases the GIL (for instance a Cython loop wrapped in a "with
|
| 478 |
+
nogil" block or an expensive call to a library such as NumPy).
|
| 479 |
+
|
| 480 |
+
The actual thread pool is lazily initialized: the actual thread pool
|
| 481 |
+
construction is delayed to the first call to apply_async.
|
| 482 |
+
|
| 483 |
+
ThreadingBackend is used as the default backend for nested calls.
|
| 484 |
+
"""
|
| 485 |
+
|
| 486 |
+
supports_retrieve_callback = True
|
| 487 |
+
uses_threads = True
|
| 488 |
+
supports_sharedmem = True
|
| 489 |
+
|
| 490 |
+
def configure(self, n_jobs=1, parallel=None, **backend_kwargs):
|
| 491 |
+
"""Build a process or thread pool and return the number of workers"""
|
| 492 |
+
n_jobs = self.effective_n_jobs(n_jobs)
|
| 493 |
+
if n_jobs == 1:
|
| 494 |
+
# Avoid unnecessary overhead and use sequential backend instead.
|
| 495 |
+
raise FallbackToBackend(SequentialBackend(nesting_level=self.nesting_level))
|
| 496 |
+
self.parallel = parallel
|
| 497 |
+
self._n_jobs = n_jobs
|
| 498 |
+
return n_jobs
|
| 499 |
+
|
| 500 |
+
def _get_pool(self):
|
| 501 |
+
"""Lazily initialize the thread pool
|
| 502 |
+
|
| 503 |
+
The actual pool of worker threads is only initialized at the first
|
| 504 |
+
call to apply_async.
|
| 505 |
+
"""
|
| 506 |
+
if self._pool is None:
|
| 507 |
+
self._pool = ThreadPool(self._n_jobs)
|
| 508 |
+
return self._pool
|
| 509 |
+
|
| 510 |
+
|
| 511 |
+
class MultiprocessingBackend(PoolManagerMixin, AutoBatchingMixin, ParallelBackendBase):
|
| 512 |
+
"""A ParallelBackend which will use a multiprocessing.Pool.
|
| 513 |
+
|
| 514 |
+
Will introduce some communication and memory overhead when exchanging
|
| 515 |
+
input and output data with the with the worker Python processes.
|
| 516 |
+
However, does not suffer from the Python Global Interpreter Lock.
|
| 517 |
+
"""
|
| 518 |
+
|
| 519 |
+
supports_retrieve_callback = True
|
| 520 |
+
supports_return_generator = False
|
| 521 |
+
|
| 522 |
+
def effective_n_jobs(self, n_jobs):
|
| 523 |
+
"""Determine the number of jobs which are going to run in parallel.
|
| 524 |
+
|
| 525 |
+
This also checks if we are attempting to create a nested parallel
|
| 526 |
+
loop.
|
| 527 |
+
"""
|
| 528 |
+
if mp is None:
|
| 529 |
+
return 1
|
| 530 |
+
|
| 531 |
+
if mp.current_process().daemon:
|
| 532 |
+
# Daemonic processes cannot have children
|
| 533 |
+
if n_jobs != 1:
|
| 534 |
+
if inside_dask_worker():
|
| 535 |
+
msg = (
|
| 536 |
+
"Inside a Dask worker with daemon=True, "
|
| 537 |
+
"setting n_jobs=1.\nPossible work-arounds:\n"
|
| 538 |
+
"- dask.config.set("
|
| 539 |
+
"{'distributed.worker.daemon': False})"
|
| 540 |
+
"- set the environment variable "
|
| 541 |
+
"DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
|
| 542 |
+
"before creating your Dask cluster."
|
| 543 |
+
)
|
| 544 |
+
else:
|
| 545 |
+
msg = (
|
| 546 |
+
"Multiprocessing-backed parallel loops "
|
| 547 |
+
"cannot be nested, setting n_jobs=1"
|
| 548 |
+
)
|
| 549 |
+
warnings.warn(msg, stacklevel=3)
|
| 550 |
+
return 1
|
| 551 |
+
|
| 552 |
+
if process_executor._CURRENT_DEPTH > 0:
|
| 553 |
+
# Mixing loky and multiprocessing in nested loop is not supported
|
| 554 |
+
if n_jobs != 1:
|
| 555 |
+
warnings.warn(
|
| 556 |
+
"Multiprocessing-backed parallel loops cannot be nested,"
|
| 557 |
+
" below loky, setting n_jobs=1",
|
| 558 |
+
stacklevel=3,
|
| 559 |
+
)
|
| 560 |
+
return 1
|
| 561 |
+
|
| 562 |
+
elif not (self.in_main_thread() or self.nesting_level == 0):
|
| 563 |
+
# Prevent posix fork inside in non-main posix threads
|
| 564 |
+
if n_jobs != 1:
|
| 565 |
+
warnings.warn(
|
| 566 |
+
"Multiprocessing-backed parallel loops cannot be nested"
|
| 567 |
+
" below threads, setting n_jobs=1",
|
| 568 |
+
stacklevel=3,
|
| 569 |
+
)
|
| 570 |
+
return 1
|
| 571 |
+
|
| 572 |
+
return super(MultiprocessingBackend, self).effective_n_jobs(n_jobs)
|
| 573 |
+
|
| 574 |
+
def configure(
|
| 575 |
+
self,
|
| 576 |
+
n_jobs=1,
|
| 577 |
+
parallel=None,
|
| 578 |
+
prefer=None,
|
| 579 |
+
require=None,
|
| 580 |
+
**memmapping_pool_kwargs,
|
| 581 |
+
):
|
| 582 |
+
"""Build a process or thread pool and return the number of workers"""
|
| 583 |
+
n_jobs = self.effective_n_jobs(n_jobs)
|
| 584 |
+
if n_jobs == 1:
|
| 585 |
+
raise FallbackToBackend(SequentialBackend(nesting_level=self.nesting_level))
|
| 586 |
+
|
| 587 |
+
memmapping_pool_kwargs = {
|
| 588 |
+
**self.backend_kwargs,
|
| 589 |
+
**memmapping_pool_kwargs,
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
# Make sure to free as much memory as possible before forking
|
| 593 |
+
gc.collect()
|
| 594 |
+
self._pool = MemmappingPool(n_jobs, **memmapping_pool_kwargs)
|
| 595 |
+
self.parallel = parallel
|
| 596 |
+
return n_jobs
|
| 597 |
+
|
| 598 |
+
def terminate(self):
|
| 599 |
+
"""Shutdown the process or thread pool"""
|
| 600 |
+
super(MultiprocessingBackend, self).terminate()
|
| 601 |
+
self.reset_batch_stats()
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
class LokyBackend(AutoBatchingMixin, ParallelBackendBase):
|
| 605 |
+
"""Managing pool of workers with loky instead of multiprocessing."""
|
| 606 |
+
|
| 607 |
+
supports_retrieve_callback = True
|
| 608 |
+
supports_inner_max_num_threads = True
|
| 609 |
+
|
| 610 |
+
def configure(
|
| 611 |
+
self,
|
| 612 |
+
n_jobs=1,
|
| 613 |
+
parallel=None,
|
| 614 |
+
prefer=None,
|
| 615 |
+
require=None,
|
| 616 |
+
idle_worker_timeout=None,
|
| 617 |
+
**memmapping_executor_kwargs,
|
| 618 |
+
):
|
| 619 |
+
"""Build a process executor and return the number of workers"""
|
| 620 |
+
n_jobs = self.effective_n_jobs(n_jobs)
|
| 621 |
+
if n_jobs == 1:
|
| 622 |
+
raise FallbackToBackend(SequentialBackend(nesting_level=self.nesting_level))
|
| 623 |
+
|
| 624 |
+
memmapping_executor_kwargs = {
|
| 625 |
+
**self.backend_kwargs,
|
| 626 |
+
**memmapping_executor_kwargs,
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
# Prohibit the use of 'timeout' in the LokyBackend, as 'idle_worker_timeout'
|
| 630 |
+
# better describes the backend's behavior.
|
| 631 |
+
if "timeout" in memmapping_executor_kwargs:
|
| 632 |
+
raise ValueError(
|
| 633 |
+
"The 'timeout' parameter is not supported by the LokyBackend. "
|
| 634 |
+
"Please use the `idle_worker_timeout` parameter instead."
|
| 635 |
+
)
|
| 636 |
+
if idle_worker_timeout is None:
|
| 637 |
+
idle_worker_timeout = self.backend_kwargs.get("idle_worker_timeout", 300)
|
| 638 |
+
|
| 639 |
+
self._workers = get_memmapping_executor(
|
| 640 |
+
n_jobs,
|
| 641 |
+
timeout=idle_worker_timeout,
|
| 642 |
+
env=self._prepare_worker_env(n_jobs=n_jobs),
|
| 643 |
+
context_id=parallel._id,
|
| 644 |
+
**memmapping_executor_kwargs,
|
| 645 |
+
)
|
| 646 |
+
self.parallel = parallel
|
| 647 |
+
return n_jobs
|
| 648 |
+
|
| 649 |
+
def effective_n_jobs(self, n_jobs):
|
| 650 |
+
"""Determine the number of jobs which are going to run in parallel"""
|
| 651 |
+
if n_jobs == 0:
|
| 652 |
+
raise ValueError("n_jobs == 0 in Parallel has no meaning")
|
| 653 |
+
elif mp is None or n_jobs is None:
|
| 654 |
+
# multiprocessing is not available or disabled, fallback
|
| 655 |
+
# to sequential mode
|
| 656 |
+
return 1
|
| 657 |
+
elif mp.current_process().daemon:
|
| 658 |
+
# Daemonic processes cannot have children
|
| 659 |
+
if n_jobs != 1:
|
| 660 |
+
if inside_dask_worker():
|
| 661 |
+
msg = (
|
| 662 |
+
"Inside a Dask worker with daemon=True, "
|
| 663 |
+
"setting n_jobs=1.\nPossible work-arounds:\n"
|
| 664 |
+
"- dask.config.set("
|
| 665 |
+
"{'distributed.worker.daemon': False})\n"
|
| 666 |
+
"- set the environment variable "
|
| 667 |
+
"DASK_DISTRIBUTED__WORKER__DAEMON=False\n"
|
| 668 |
+
"before creating your Dask cluster."
|
| 669 |
+
)
|
| 670 |
+
else:
|
| 671 |
+
msg = (
|
| 672 |
+
"Loky-backed parallel loops cannot be called in a"
|
| 673 |
+
" multiprocessing, setting n_jobs=1"
|
| 674 |
+
)
|
| 675 |
+
warnings.warn(msg, stacklevel=3)
|
| 676 |
+
|
| 677 |
+
return 1
|
| 678 |
+
elif not (self.in_main_thread() or self.nesting_level == 0):
|
| 679 |
+
# Prevent posix fork inside in non-main posix threads
|
| 680 |
+
if n_jobs != 1:
|
| 681 |
+
warnings.warn(
|
| 682 |
+
"Loky-backed parallel loops cannot be nested below "
|
| 683 |
+
"threads, setting n_jobs=1",
|
| 684 |
+
stacklevel=3,
|
| 685 |
+
)
|
| 686 |
+
return 1
|
| 687 |
+
elif n_jobs < 0:
|
| 688 |
+
n_jobs = max(cpu_count() + 1 + n_jobs, 1)
|
| 689 |
+
return n_jobs
|
| 690 |
+
|
| 691 |
+
def submit(self, func, callback=None):
|
| 692 |
+
"""Schedule a func to be run"""
|
| 693 |
+
future = self._workers.submit(func)
|
| 694 |
+
if callback is not None:
|
| 695 |
+
future.add_done_callback(callback)
|
| 696 |
+
return future
|
| 697 |
+
|
| 698 |
+
def retrieve_result_callback(self, future):
|
| 699 |
+
"""Retrieve the result, here out is the future given by submit"""
|
| 700 |
+
try:
|
| 701 |
+
return future.result()
|
| 702 |
+
except ShutdownExecutorError:
|
| 703 |
+
raise RuntimeError(
|
| 704 |
+
"The executor underlying Parallel has been shutdown. "
|
| 705 |
+
"This is likely due to the garbage collection of a previous "
|
| 706 |
+
"generator from a call to Parallel with return_as='generator'."
|
| 707 |
+
" Make sure the generator is not garbage collected when "
|
| 708 |
+
"submitting a new job or that it is first properly exhausted."
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
def terminate(self):
|
| 712 |
+
if self._workers is not None:
|
| 713 |
+
# Don't terminate the workers as we want to reuse them in later
|
| 714 |
+
# calls, but cleanup the temporary resources that the Parallel call
|
| 715 |
+
# created. This 'hack' requires a private, low-level operation.
|
| 716 |
+
self._workers._temp_folder_manager._clean_temporary_resources(
|
| 717 |
+
context_id=self.parallel._id, force=False
|
| 718 |
+
)
|
| 719 |
+
self._workers = None
|
| 720 |
+
|
| 721 |
+
self.reset_batch_stats()
|
| 722 |
+
|
| 723 |
+
def abort_everything(self, ensure_ready=True):
|
| 724 |
+
"""Shutdown the workers and restart a new one with the same parameters"""
|
| 725 |
+
self._workers.terminate(kill_workers=True)
|
| 726 |
+
self._workers = None
|
| 727 |
+
|
| 728 |
+
if ensure_ready:
|
| 729 |
+
self.configure(n_jobs=self.parallel.n_jobs, parallel=self.parallel)
|
| 730 |
+
|
| 731 |
+
|
| 732 |
+
class FallbackToBackend(Exception):
|
| 733 |
+
"""Raised when configuration should fallback to another backend"""
|
| 734 |
+
|
| 735 |
+
def __init__(self, backend):
|
| 736 |
+
self.backend = backend
|
| 737 |
+
|
| 738 |
+
|
| 739 |
+
def inside_dask_worker():
|
| 740 |
+
"""Check whether the current function is executed inside a Dask worker."""
|
| 741 |
+
# This function can not be in joblib._dask because there would be a
|
| 742 |
+
# circular import:
|
| 743 |
+
# _dask imports _parallel_backend that imports _dask ...
|
| 744 |
+
try:
|
| 745 |
+
from distributed import get_worker
|
| 746 |
+
except ImportError:
|
| 747 |
+
return False
|
| 748 |
+
|
| 749 |
+
try:
|
| 750 |
+
get_worker()
|
| 751 |
+
return True
|
| 752 |
+
except ValueError:
|
| 753 |
+
return False
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_store_backends.py
ADDED
|
@@ -0,0 +1,488 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Storage providers backends for Memory caching."""
|
| 2 |
+
|
| 3 |
+
import collections
|
| 4 |
+
import datetime
|
| 5 |
+
import json
|
| 6 |
+
import operator
|
| 7 |
+
import os
|
| 8 |
+
import os.path
|
| 9 |
+
import re
|
| 10 |
+
import shutil
|
| 11 |
+
import threading
|
| 12 |
+
import time
|
| 13 |
+
import warnings
|
| 14 |
+
from abc import ABCMeta, abstractmethod
|
| 15 |
+
from pickle import PicklingError
|
| 16 |
+
|
| 17 |
+
from . import numpy_pickle
|
| 18 |
+
from .backports import concurrency_safe_rename
|
| 19 |
+
from .disk import memstr_to_bytes, mkdirp, rm_subdirs
|
| 20 |
+
from .logger import format_time
|
| 21 |
+
|
| 22 |
+
CacheItemInfo = collections.namedtuple("CacheItemInfo", "path size last_access")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class CacheWarning(Warning):
|
| 26 |
+
"""Warning to capture dump failures except for PicklingError."""
|
| 27 |
+
|
| 28 |
+
pass
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def concurrency_safe_write(object_to_write, filename, write_func):
|
| 32 |
+
"""Writes an object into a unique file in a concurrency-safe way."""
|
| 33 |
+
thread_id = id(threading.current_thread())
|
| 34 |
+
temporary_filename = "{}.thread-{}-pid-{}".format(filename, thread_id, os.getpid())
|
| 35 |
+
write_func(object_to_write, temporary_filename)
|
| 36 |
+
|
| 37 |
+
return temporary_filename
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class StoreBackendBase(metaclass=ABCMeta):
|
| 41 |
+
"""Helper Abstract Base Class which defines all methods that
|
| 42 |
+
a StorageBackend must implement."""
|
| 43 |
+
|
| 44 |
+
location = None
|
| 45 |
+
|
| 46 |
+
@abstractmethod
|
| 47 |
+
def _open_item(self, f, mode):
|
| 48 |
+
"""Opens an item on the store and return a file-like object.
|
| 49 |
+
|
| 50 |
+
This method is private and only used by the StoreBackendMixin object.
|
| 51 |
+
|
| 52 |
+
Parameters
|
| 53 |
+
----------
|
| 54 |
+
f: a file-like object
|
| 55 |
+
The file-like object where an item is stored and retrieved
|
| 56 |
+
mode: string, optional
|
| 57 |
+
the mode in which the file-like object is opened allowed valued are
|
| 58 |
+
'rb', 'wb'
|
| 59 |
+
|
| 60 |
+
Returns
|
| 61 |
+
-------
|
| 62 |
+
a file-like object
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
@abstractmethod
|
| 66 |
+
def _item_exists(self, location):
|
| 67 |
+
"""Checks if an item location exists in the store.
|
| 68 |
+
|
| 69 |
+
This method is private and only used by the StoreBackendMixin object.
|
| 70 |
+
|
| 71 |
+
Parameters
|
| 72 |
+
----------
|
| 73 |
+
location: string
|
| 74 |
+
The location of an item. On a filesystem, this corresponds to the
|
| 75 |
+
absolute path, including the filename, of a file.
|
| 76 |
+
|
| 77 |
+
Returns
|
| 78 |
+
-------
|
| 79 |
+
True if the item exists, False otherwise
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
@abstractmethod
|
| 83 |
+
def _move_item(self, src, dst):
|
| 84 |
+
"""Moves an item from src to dst in the store.
|
| 85 |
+
|
| 86 |
+
This method is private and only used by the StoreBackendMixin object.
|
| 87 |
+
|
| 88 |
+
Parameters
|
| 89 |
+
----------
|
| 90 |
+
src: string
|
| 91 |
+
The source location of an item
|
| 92 |
+
dst: string
|
| 93 |
+
The destination location of an item
|
| 94 |
+
"""
|
| 95 |
+
|
| 96 |
+
@abstractmethod
|
| 97 |
+
def create_location(self, location):
|
| 98 |
+
"""Creates a location on the store.
|
| 99 |
+
|
| 100 |
+
Parameters
|
| 101 |
+
----------
|
| 102 |
+
location: string
|
| 103 |
+
The location in the store. On a filesystem, this corresponds to a
|
| 104 |
+
directory.
|
| 105 |
+
"""
|
| 106 |
+
|
| 107 |
+
@abstractmethod
|
| 108 |
+
def clear_location(self, location):
|
| 109 |
+
"""Clears a location on the store.
|
| 110 |
+
|
| 111 |
+
Parameters
|
| 112 |
+
----------
|
| 113 |
+
location: string
|
| 114 |
+
The location in the store. On a filesystem, this corresponds to a
|
| 115 |
+
directory or a filename absolute path
|
| 116 |
+
"""
|
| 117 |
+
|
| 118 |
+
@abstractmethod
|
| 119 |
+
def get_items(self):
|
| 120 |
+
"""Returns the whole list of items available in the store.
|
| 121 |
+
|
| 122 |
+
Returns
|
| 123 |
+
-------
|
| 124 |
+
The list of items identified by their ids (e.g filename in a
|
| 125 |
+
filesystem).
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
@abstractmethod
|
| 129 |
+
def configure(self, location, verbose=0, backend_options=dict()):
|
| 130 |
+
"""Configures the store.
|
| 131 |
+
|
| 132 |
+
Parameters
|
| 133 |
+
----------
|
| 134 |
+
location: string
|
| 135 |
+
The base location used by the store. On a filesystem, this
|
| 136 |
+
corresponds to a directory.
|
| 137 |
+
verbose: int
|
| 138 |
+
The level of verbosity of the store
|
| 139 |
+
backend_options: dict
|
| 140 |
+
Contains a dictionary of named parameters used to configure the
|
| 141 |
+
store backend.
|
| 142 |
+
"""
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class StoreBackendMixin(object):
|
| 146 |
+
"""Class providing all logic for managing the store in a generic way.
|
| 147 |
+
|
| 148 |
+
The StoreBackend subclass has to implement 3 methods: create_location,
|
| 149 |
+
clear_location and configure. The StoreBackend also has to provide
|
| 150 |
+
a private _open_item, _item_exists and _move_item methods. The _open_item
|
| 151 |
+
method has to have the same signature as the builtin open and return a
|
| 152 |
+
file-like object.
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
def load_item(self, call_id, verbose=1, timestamp=None, metadata=None):
|
| 156 |
+
"""Load an item from the store given its id as a list of str."""
|
| 157 |
+
full_path = os.path.join(self.location, *call_id)
|
| 158 |
+
|
| 159 |
+
if verbose > 1:
|
| 160 |
+
ts_string = (
|
| 161 |
+
"{: <16}".format(format_time(time.time() - timestamp))
|
| 162 |
+
if timestamp is not None
|
| 163 |
+
else ""
|
| 164 |
+
)
|
| 165 |
+
signature = os.path.basename(call_id[0])
|
| 166 |
+
if metadata is not None and "input_args" in metadata:
|
| 167 |
+
kwargs = ", ".join(
|
| 168 |
+
"{}={}".format(*item) for item in metadata["input_args"].items()
|
| 169 |
+
)
|
| 170 |
+
signature += "({})".format(kwargs)
|
| 171 |
+
msg = "[Memory]{}: Loading {}".format(ts_string, signature)
|
| 172 |
+
if verbose < 10:
|
| 173 |
+
print("{0}...".format(msg))
|
| 174 |
+
else:
|
| 175 |
+
print("{0} from {1}".format(msg, full_path))
|
| 176 |
+
|
| 177 |
+
mmap_mode = None if not hasattr(self, "mmap_mode") else self.mmap_mode
|
| 178 |
+
|
| 179 |
+
filename = os.path.join(full_path, "output.pkl")
|
| 180 |
+
if not self._item_exists(filename):
|
| 181 |
+
raise KeyError(
|
| 182 |
+
"Non-existing item (may have been "
|
| 183 |
+
"cleared).\nFile %s does not exist" % filename
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
# file-like object cannot be used when mmap_mode is set
|
| 187 |
+
if mmap_mode is None:
|
| 188 |
+
with self._open_item(filename, "rb") as f:
|
| 189 |
+
item = numpy_pickle.load(f)
|
| 190 |
+
else:
|
| 191 |
+
item = numpy_pickle.load(filename, mmap_mode=mmap_mode)
|
| 192 |
+
return item
|
| 193 |
+
|
| 194 |
+
def dump_item(self, call_id, item, verbose=1):
|
| 195 |
+
"""Dump an item in the store at the id given as a list of str."""
|
| 196 |
+
try:
|
| 197 |
+
item_path = os.path.join(self.location, *call_id)
|
| 198 |
+
if not self._item_exists(item_path):
|
| 199 |
+
self.create_location(item_path)
|
| 200 |
+
filename = os.path.join(item_path, "output.pkl")
|
| 201 |
+
if verbose > 10:
|
| 202 |
+
print("Persisting in %s" % item_path)
|
| 203 |
+
|
| 204 |
+
def write_func(to_write, dest_filename):
|
| 205 |
+
with self._open_item(dest_filename, "wb") as f:
|
| 206 |
+
try:
|
| 207 |
+
numpy_pickle.dump(to_write, f, compress=self.compress)
|
| 208 |
+
except PicklingError as e:
|
| 209 |
+
# TODO(1.5) turn into error
|
| 210 |
+
warnings.warn(
|
| 211 |
+
"Unable to cache to disk: failed to pickle "
|
| 212 |
+
"output. In version 1.5 this will raise an "
|
| 213 |
+
f"exception. Exception: {e}.",
|
| 214 |
+
FutureWarning,
|
| 215 |
+
)
|
| 216 |
+
|
| 217 |
+
self._concurrency_safe_write(item, filename, write_func)
|
| 218 |
+
except Exception as e: # noqa: E722
|
| 219 |
+
warnings.warn(
|
| 220 |
+
"Unable to cache to disk. Possibly a race condition in the "
|
| 221 |
+
f"creation of the directory. Exception: {e}.",
|
| 222 |
+
CacheWarning,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
def clear_item(self, call_id):
|
| 226 |
+
"""Clear the item at the id, given as a list of str."""
|
| 227 |
+
item_path = os.path.join(self.location, *call_id)
|
| 228 |
+
if self._item_exists(item_path):
|
| 229 |
+
self.clear_location(item_path)
|
| 230 |
+
|
| 231 |
+
def contains_item(self, call_id):
|
| 232 |
+
"""Check if there is an item at the id, given as a list of str."""
|
| 233 |
+
item_path = os.path.join(self.location, *call_id)
|
| 234 |
+
filename = os.path.join(item_path, "output.pkl")
|
| 235 |
+
|
| 236 |
+
return self._item_exists(filename)
|
| 237 |
+
|
| 238 |
+
def get_item_info(self, call_id):
|
| 239 |
+
"""Return information about item."""
|
| 240 |
+
return {"location": os.path.join(self.location, *call_id)}
|
| 241 |
+
|
| 242 |
+
def get_metadata(self, call_id):
|
| 243 |
+
"""Return actual metadata of an item."""
|
| 244 |
+
try:
|
| 245 |
+
item_path = os.path.join(self.location, *call_id)
|
| 246 |
+
filename = os.path.join(item_path, "metadata.json")
|
| 247 |
+
with self._open_item(filename, "rb") as f:
|
| 248 |
+
return json.loads(f.read().decode("utf-8"))
|
| 249 |
+
except: # noqa: E722
|
| 250 |
+
return {}
|
| 251 |
+
|
| 252 |
+
def store_metadata(self, call_id, metadata):
|
| 253 |
+
"""Store metadata of a computation."""
|
| 254 |
+
try:
|
| 255 |
+
item_path = os.path.join(self.location, *call_id)
|
| 256 |
+
self.create_location(item_path)
|
| 257 |
+
filename = os.path.join(item_path, "metadata.json")
|
| 258 |
+
|
| 259 |
+
def write_func(to_write, dest_filename):
|
| 260 |
+
with self._open_item(dest_filename, "wb") as f:
|
| 261 |
+
f.write(json.dumps(to_write).encode("utf-8"))
|
| 262 |
+
|
| 263 |
+
self._concurrency_safe_write(metadata, filename, write_func)
|
| 264 |
+
except: # noqa: E722
|
| 265 |
+
pass
|
| 266 |
+
|
| 267 |
+
def contains_path(self, call_id):
|
| 268 |
+
"""Check cached function is available in store."""
|
| 269 |
+
func_path = os.path.join(self.location, *call_id)
|
| 270 |
+
return self.object_exists(func_path)
|
| 271 |
+
|
| 272 |
+
def clear_path(self, call_id):
|
| 273 |
+
"""Clear all items with a common path in the store."""
|
| 274 |
+
func_path = os.path.join(self.location, *call_id)
|
| 275 |
+
if self._item_exists(func_path):
|
| 276 |
+
self.clear_location(func_path)
|
| 277 |
+
|
| 278 |
+
def store_cached_func_code(self, call_id, func_code=None):
|
| 279 |
+
"""Store the code of the cached function."""
|
| 280 |
+
func_path = os.path.join(self.location, *call_id)
|
| 281 |
+
if not self._item_exists(func_path):
|
| 282 |
+
self.create_location(func_path)
|
| 283 |
+
|
| 284 |
+
if func_code is not None:
|
| 285 |
+
filename = os.path.join(func_path, "func_code.py")
|
| 286 |
+
with self._open_item(filename, "wb") as f:
|
| 287 |
+
f.write(func_code.encode("utf-8"))
|
| 288 |
+
|
| 289 |
+
def get_cached_func_code(self, call_id):
|
| 290 |
+
"""Store the code of the cached function."""
|
| 291 |
+
filename = os.path.join(self.location, *call_id, "func_code.py")
|
| 292 |
+
try:
|
| 293 |
+
with self._open_item(filename, "rb") as f:
|
| 294 |
+
return f.read().decode("utf-8")
|
| 295 |
+
except: # noqa: E722
|
| 296 |
+
raise
|
| 297 |
+
|
| 298 |
+
def get_cached_func_info(self, call_id):
|
| 299 |
+
"""Return information related to the cached function if it exists."""
|
| 300 |
+
return {"location": os.path.join(self.location, *call_id)}
|
| 301 |
+
|
| 302 |
+
def clear(self):
|
| 303 |
+
"""Clear the whole store content."""
|
| 304 |
+
self.clear_location(self.location)
|
| 305 |
+
|
| 306 |
+
def enforce_store_limits(self, bytes_limit, items_limit=None, age_limit=None):
|
| 307 |
+
"""
|
| 308 |
+
Remove the store's oldest files to enforce item, byte, and age limits.
|
| 309 |
+
"""
|
| 310 |
+
items_to_delete = self._get_items_to_delete(bytes_limit, items_limit, age_limit)
|
| 311 |
+
|
| 312 |
+
for item in items_to_delete:
|
| 313 |
+
if self.verbose > 10:
|
| 314 |
+
print("Deleting item {0}".format(item))
|
| 315 |
+
try:
|
| 316 |
+
self.clear_location(item.path)
|
| 317 |
+
except OSError:
|
| 318 |
+
# Even with ignore_errors=True shutil.rmtree can raise OSError
|
| 319 |
+
# with:
|
| 320 |
+
# [Errno 116] Stale file handle if another process has deleted
|
| 321 |
+
# the folder already.
|
| 322 |
+
pass
|
| 323 |
+
|
| 324 |
+
def _get_items_to_delete(self, bytes_limit, items_limit=None, age_limit=None):
|
| 325 |
+
"""
|
| 326 |
+
Get items to delete to keep the store under size, file, & age limits.
|
| 327 |
+
"""
|
| 328 |
+
if isinstance(bytes_limit, str):
|
| 329 |
+
bytes_limit = memstr_to_bytes(bytes_limit)
|
| 330 |
+
|
| 331 |
+
items = self.get_items()
|
| 332 |
+
if not items:
|
| 333 |
+
return []
|
| 334 |
+
|
| 335 |
+
size = sum(item.size for item in items)
|
| 336 |
+
|
| 337 |
+
if bytes_limit is not None:
|
| 338 |
+
to_delete_size = size - bytes_limit
|
| 339 |
+
else:
|
| 340 |
+
to_delete_size = 0
|
| 341 |
+
|
| 342 |
+
if items_limit is not None:
|
| 343 |
+
to_delete_items = len(items) - items_limit
|
| 344 |
+
else:
|
| 345 |
+
to_delete_items = 0
|
| 346 |
+
|
| 347 |
+
if age_limit is not None:
|
| 348 |
+
older_item = min(item.last_access for item in items)
|
| 349 |
+
if age_limit.total_seconds() < 0:
|
| 350 |
+
raise ValueError("age_limit has to be a positive timedelta")
|
| 351 |
+
deadline = datetime.datetime.now() - age_limit
|
| 352 |
+
else:
|
| 353 |
+
deadline = None
|
| 354 |
+
|
| 355 |
+
if (
|
| 356 |
+
to_delete_size <= 0
|
| 357 |
+
and to_delete_items <= 0
|
| 358 |
+
and (deadline is None or older_item > deadline)
|
| 359 |
+
):
|
| 360 |
+
return []
|
| 361 |
+
|
| 362 |
+
# We want to delete first the cache items that were accessed a
|
| 363 |
+
# long time ago
|
| 364 |
+
items.sort(key=operator.attrgetter("last_access"))
|
| 365 |
+
|
| 366 |
+
items_to_delete = []
|
| 367 |
+
size_so_far = 0
|
| 368 |
+
items_so_far = 0
|
| 369 |
+
|
| 370 |
+
for item in items:
|
| 371 |
+
if (
|
| 372 |
+
(size_so_far >= to_delete_size)
|
| 373 |
+
and items_so_far >= to_delete_items
|
| 374 |
+
and (deadline is None or deadline < item.last_access)
|
| 375 |
+
):
|
| 376 |
+
break
|
| 377 |
+
|
| 378 |
+
items_to_delete.append(item)
|
| 379 |
+
size_so_far += item.size
|
| 380 |
+
items_so_far += 1
|
| 381 |
+
|
| 382 |
+
return items_to_delete
|
| 383 |
+
|
| 384 |
+
def _concurrency_safe_write(self, to_write, filename, write_func):
|
| 385 |
+
"""Writes an object into a file in a concurrency-safe way."""
|
| 386 |
+
temporary_filename = concurrency_safe_write(to_write, filename, write_func)
|
| 387 |
+
self._move_item(temporary_filename, filename)
|
| 388 |
+
|
| 389 |
+
def __repr__(self):
|
| 390 |
+
"""Printable representation of the store location."""
|
| 391 |
+
return '{class_name}(location="{location}")'.format(
|
| 392 |
+
class_name=self.__class__.__name__, location=self.location
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class FileSystemStoreBackend(StoreBackendBase, StoreBackendMixin):
|
| 397 |
+
"""A StoreBackend used with local or network file systems."""
|
| 398 |
+
|
| 399 |
+
_open_item = staticmethod(open)
|
| 400 |
+
_item_exists = staticmethod(os.path.exists)
|
| 401 |
+
_move_item = staticmethod(concurrency_safe_rename)
|
| 402 |
+
|
| 403 |
+
def clear_location(self, location):
|
| 404 |
+
"""Delete location on store."""
|
| 405 |
+
if location == self.location:
|
| 406 |
+
rm_subdirs(location)
|
| 407 |
+
else:
|
| 408 |
+
shutil.rmtree(location, ignore_errors=True)
|
| 409 |
+
|
| 410 |
+
def create_location(self, location):
|
| 411 |
+
"""Create object location on store"""
|
| 412 |
+
mkdirp(location)
|
| 413 |
+
|
| 414 |
+
def get_items(self):
|
| 415 |
+
"""Returns the whole list of items available in the store."""
|
| 416 |
+
items = []
|
| 417 |
+
|
| 418 |
+
for dirpath, _, filenames in os.walk(self.location):
|
| 419 |
+
is_cache_hash_dir = re.match("[a-f0-9]{32}", os.path.basename(dirpath))
|
| 420 |
+
|
| 421 |
+
if is_cache_hash_dir:
|
| 422 |
+
output_filename = os.path.join(dirpath, "output.pkl")
|
| 423 |
+
try:
|
| 424 |
+
last_access = os.path.getatime(output_filename)
|
| 425 |
+
except OSError:
|
| 426 |
+
try:
|
| 427 |
+
last_access = os.path.getatime(dirpath)
|
| 428 |
+
except OSError:
|
| 429 |
+
# The directory has already been deleted
|
| 430 |
+
continue
|
| 431 |
+
|
| 432 |
+
last_access = datetime.datetime.fromtimestamp(last_access)
|
| 433 |
+
try:
|
| 434 |
+
full_filenames = [os.path.join(dirpath, fn) for fn in filenames]
|
| 435 |
+
dirsize = sum(os.path.getsize(fn) for fn in full_filenames)
|
| 436 |
+
except OSError:
|
| 437 |
+
# Either output_filename or one of the files in
|
| 438 |
+
# dirpath does not exist any more. We assume this
|
| 439 |
+
# directory is being cleaned by another process already
|
| 440 |
+
continue
|
| 441 |
+
|
| 442 |
+
items.append(CacheItemInfo(dirpath, dirsize, last_access))
|
| 443 |
+
|
| 444 |
+
return items
|
| 445 |
+
|
| 446 |
+
def configure(self, location, verbose=1, backend_options=None):
|
| 447 |
+
"""Configure the store backend.
|
| 448 |
+
|
| 449 |
+
For this backend, valid store options are 'compress' and 'mmap_mode'
|
| 450 |
+
"""
|
| 451 |
+
if backend_options is None:
|
| 452 |
+
backend_options = {}
|
| 453 |
+
|
| 454 |
+
# setup location directory
|
| 455 |
+
self.location = location
|
| 456 |
+
if not os.path.exists(self.location):
|
| 457 |
+
mkdirp(self.location)
|
| 458 |
+
|
| 459 |
+
# Automatically add `.gitignore` file to the cache folder.
|
| 460 |
+
# XXX: the condition is necessary because in `Memory.__init__`, the user
|
| 461 |
+
# passed `location` param is modified to be either `{location}` or
|
| 462 |
+
# `{location}/joblib` depending on input type (`pathlib.Path` vs `str`).
|
| 463 |
+
# The proper resolution of this inconsistency is tracked in:
|
| 464 |
+
# https://github.com/joblib/joblib/issues/1684
|
| 465 |
+
cache_directory = (
|
| 466 |
+
os.path.dirname(location)
|
| 467 |
+
if os.path.dirname(location) and os.path.basename(location) == "joblib"
|
| 468 |
+
else location
|
| 469 |
+
)
|
| 470 |
+
with open(os.path.join(cache_directory, ".gitignore"), "w") as file:
|
| 471 |
+
file.write("# Created by joblib automatically.\n")
|
| 472 |
+
file.write("*\n")
|
| 473 |
+
|
| 474 |
+
# item can be stored compressed for faster I/O
|
| 475 |
+
self.compress = backend_options.get("compress", False)
|
| 476 |
+
|
| 477 |
+
# FileSystemStoreBackend can be used with mmap_mode options under
|
| 478 |
+
# certain conditions.
|
| 479 |
+
mmap_mode = backend_options.get("mmap_mode")
|
| 480 |
+
if self.compress and mmap_mode is not None:
|
| 481 |
+
warnings.warn(
|
| 482 |
+
"Compressed items cannot be memmapped in a "
|
| 483 |
+
"filesystem store. Option will be ignored.",
|
| 484 |
+
stacklevel=2,
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
self.mmap_mode = mmap_mode
|
| 488 |
+
self.verbose = verbose
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/_utils.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from https://stackoverflow.com/a/9558001/2536294
|
| 2 |
+
|
| 3 |
+
import ast
|
| 4 |
+
import operator as op
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
|
| 7 |
+
from ._multiprocessing_helpers import mp
|
| 8 |
+
|
| 9 |
+
if mp is not None:
|
| 10 |
+
from .externals.loky.process_executor import _ExceptionWithTraceback
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
# supported operators
|
| 14 |
+
operators = {
|
| 15 |
+
ast.Add: op.add,
|
| 16 |
+
ast.Sub: op.sub,
|
| 17 |
+
ast.Mult: op.mul,
|
| 18 |
+
ast.Div: op.truediv,
|
| 19 |
+
ast.FloorDiv: op.floordiv,
|
| 20 |
+
ast.Mod: op.mod,
|
| 21 |
+
ast.Pow: op.pow,
|
| 22 |
+
ast.USub: op.neg,
|
| 23 |
+
}
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def eval_expr(expr):
|
| 27 |
+
"""
|
| 28 |
+
>>> eval_expr('2*6')
|
| 29 |
+
12
|
| 30 |
+
>>> eval_expr('2**6')
|
| 31 |
+
64
|
| 32 |
+
>>> eval_expr('1 + 2*3**(4) / (6 + -7)')
|
| 33 |
+
-161.0
|
| 34 |
+
"""
|
| 35 |
+
try:
|
| 36 |
+
return eval_(ast.parse(expr, mode="eval").body)
|
| 37 |
+
except (TypeError, SyntaxError, KeyError) as e:
|
| 38 |
+
raise ValueError(
|
| 39 |
+
f"{expr!r} is not a valid or supported arithmetic expression."
|
| 40 |
+
) from e
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def eval_(node):
|
| 44 |
+
if isinstance(node, ast.Constant): # <constant>
|
| 45 |
+
return node.value
|
| 46 |
+
elif isinstance(node, ast.BinOp): # <left> <operator> <right>
|
| 47 |
+
return operators[type(node.op)](eval_(node.left), eval_(node.right))
|
| 48 |
+
elif isinstance(node, ast.UnaryOp): # <operator> <operand> e.g., -1
|
| 49 |
+
return operators[type(node.op)](eval_(node.operand))
|
| 50 |
+
else:
|
| 51 |
+
raise TypeError(node)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass(frozen=True)
|
| 55 |
+
class _Sentinel:
|
| 56 |
+
"""A sentinel to mark a parameter as not explicitly set"""
|
| 57 |
+
|
| 58 |
+
default_value: object
|
| 59 |
+
|
| 60 |
+
def __repr__(self):
|
| 61 |
+
return f"default({self.default_value!r})"
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class _TracebackCapturingWrapper:
|
| 65 |
+
"""Protect function call and return error with traceback."""
|
| 66 |
+
|
| 67 |
+
def __init__(self, func):
|
| 68 |
+
self.func = func
|
| 69 |
+
|
| 70 |
+
def __call__(self, **kwargs):
|
| 71 |
+
try:
|
| 72 |
+
return self.func(**kwargs)
|
| 73 |
+
except BaseException as e:
|
| 74 |
+
return _ExceptionWithTraceback(e)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _retrieve_traceback_capturing_wrapped_call(out):
|
| 78 |
+
if isinstance(out, _ExceptionWithTraceback):
|
| 79 |
+
rebuild, args = out.__reduce__()
|
| 80 |
+
out = rebuild(*args)
|
| 81 |
+
if isinstance(out, BaseException):
|
| 82 |
+
raise out
|
| 83 |
+
return out
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/backports.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Backports of fixes for joblib dependencies
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
import re
|
| 7 |
+
import time
|
| 8 |
+
from multiprocessing import util
|
| 9 |
+
from os.path import basename
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
class Version:
|
| 13 |
+
"""Backport from deprecated distutils
|
| 14 |
+
|
| 15 |
+
We maintain this backport to avoid introducing a new dependency on
|
| 16 |
+
`packaging`.
|
| 17 |
+
|
| 18 |
+
We might rexplore this choice in the future if all major Python projects
|
| 19 |
+
introduce a dependency on packaging anyway.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
def __init__(self, vstring=None):
|
| 23 |
+
if vstring:
|
| 24 |
+
self.parse(vstring)
|
| 25 |
+
|
| 26 |
+
def __repr__(self):
|
| 27 |
+
return "%s ('%s')" % (self.__class__.__name__, str(self))
|
| 28 |
+
|
| 29 |
+
def __eq__(self, other):
|
| 30 |
+
c = self._cmp(other)
|
| 31 |
+
if c is NotImplemented:
|
| 32 |
+
return c
|
| 33 |
+
return c == 0
|
| 34 |
+
|
| 35 |
+
def __lt__(self, other):
|
| 36 |
+
c = self._cmp(other)
|
| 37 |
+
if c is NotImplemented:
|
| 38 |
+
return c
|
| 39 |
+
return c < 0
|
| 40 |
+
|
| 41 |
+
def __le__(self, other):
|
| 42 |
+
c = self._cmp(other)
|
| 43 |
+
if c is NotImplemented:
|
| 44 |
+
return c
|
| 45 |
+
return c <= 0
|
| 46 |
+
|
| 47 |
+
def __gt__(self, other):
|
| 48 |
+
c = self._cmp(other)
|
| 49 |
+
if c is NotImplemented:
|
| 50 |
+
return c
|
| 51 |
+
return c > 0
|
| 52 |
+
|
| 53 |
+
def __ge__(self, other):
|
| 54 |
+
c = self._cmp(other)
|
| 55 |
+
if c is NotImplemented:
|
| 56 |
+
return c
|
| 57 |
+
return c >= 0
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class LooseVersion(Version):
|
| 61 |
+
"""Backport from deprecated distutils
|
| 62 |
+
|
| 63 |
+
We maintain this backport to avoid introducing a new dependency on
|
| 64 |
+
`packaging`.
|
| 65 |
+
|
| 66 |
+
We might rexplore this choice in the future if all major Python projects
|
| 67 |
+
introduce a dependency on packaging anyway.
|
| 68 |
+
"""
|
| 69 |
+
|
| 70 |
+
component_re = re.compile(r"(\d+ | [a-z]+ | \.)", re.VERBOSE)
|
| 71 |
+
|
| 72 |
+
def __init__(self, vstring=None):
|
| 73 |
+
if vstring:
|
| 74 |
+
self.parse(vstring)
|
| 75 |
+
|
| 76 |
+
def parse(self, vstring):
|
| 77 |
+
# I've given up on thinking I can reconstruct the version string
|
| 78 |
+
# from the parsed tuple -- so I just store the string here for
|
| 79 |
+
# use by __str__
|
| 80 |
+
self.vstring = vstring
|
| 81 |
+
components = [x for x in self.component_re.split(vstring) if x and x != "."]
|
| 82 |
+
for i, obj in enumerate(components):
|
| 83 |
+
try:
|
| 84 |
+
components[i] = int(obj)
|
| 85 |
+
except ValueError:
|
| 86 |
+
pass
|
| 87 |
+
|
| 88 |
+
self.version = components
|
| 89 |
+
|
| 90 |
+
def __str__(self):
|
| 91 |
+
return self.vstring
|
| 92 |
+
|
| 93 |
+
def __repr__(self):
|
| 94 |
+
return "LooseVersion ('%s')" % str(self)
|
| 95 |
+
|
| 96 |
+
def _cmp(self, other):
|
| 97 |
+
if isinstance(other, str):
|
| 98 |
+
other = LooseVersion(other)
|
| 99 |
+
elif not isinstance(other, LooseVersion):
|
| 100 |
+
return NotImplemented
|
| 101 |
+
|
| 102 |
+
if self.version == other.version:
|
| 103 |
+
return 0
|
| 104 |
+
if self.version < other.version:
|
| 105 |
+
return -1
|
| 106 |
+
if self.version > other.version:
|
| 107 |
+
return 1
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
import numpy as np
|
| 112 |
+
|
| 113 |
+
def make_memmap(
|
| 114 |
+
filename,
|
| 115 |
+
dtype="uint8",
|
| 116 |
+
mode="r+",
|
| 117 |
+
offset=0,
|
| 118 |
+
shape=None,
|
| 119 |
+
order="C",
|
| 120 |
+
unlink_on_gc_collect=False,
|
| 121 |
+
):
|
| 122 |
+
"""Custom memmap constructor compatible with numpy.memmap.
|
| 123 |
+
|
| 124 |
+
This function:
|
| 125 |
+
- is a backport the numpy memmap offset fix (See
|
| 126 |
+
https://github.com/numpy/numpy/pull/8443 for more details.
|
| 127 |
+
The numpy fix is available starting numpy 1.13)
|
| 128 |
+
- adds ``unlink_on_gc_collect``, which specifies explicitly whether
|
| 129 |
+
the process re-constructing the memmap owns a reference to the
|
| 130 |
+
underlying file. If set to True, it adds a finalizer to the
|
| 131 |
+
newly-created memmap that sends a maybe_unlink request for the
|
| 132 |
+
memmaped file to resource_tracker.
|
| 133 |
+
"""
|
| 134 |
+
util.debug(
|
| 135 |
+
"[MEMMAP READ] creating a memmap (shape {}, filename {}, pid {})".format(
|
| 136 |
+
shape, basename(filename), os.getpid()
|
| 137 |
+
)
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
mm = np.memmap(
|
| 141 |
+
filename, dtype=dtype, mode=mode, offset=offset, shape=shape, order=order
|
| 142 |
+
)
|
| 143 |
+
if LooseVersion(np.__version__) < "1.13":
|
| 144 |
+
mm.offset = offset
|
| 145 |
+
if unlink_on_gc_collect:
|
| 146 |
+
from ._memmapping_reducer import add_maybe_unlink_finalizer
|
| 147 |
+
|
| 148 |
+
add_maybe_unlink_finalizer(mm)
|
| 149 |
+
return mm
|
| 150 |
+
except ImportError:
|
| 151 |
+
|
| 152 |
+
def make_memmap(
|
| 153 |
+
filename,
|
| 154 |
+
dtype="uint8",
|
| 155 |
+
mode="r+",
|
| 156 |
+
offset=0,
|
| 157 |
+
shape=None,
|
| 158 |
+
order="C",
|
| 159 |
+
unlink_on_gc_collect=False,
|
| 160 |
+
):
|
| 161 |
+
raise NotImplementedError(
|
| 162 |
+
"'joblib.backports.make_memmap' should not be used "
|
| 163 |
+
"if numpy is not installed."
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
if os.name == "nt":
|
| 168 |
+
# https://github.com/joblib/joblib/issues/540
|
| 169 |
+
access_denied_errors = (5, 13)
|
| 170 |
+
from os import replace
|
| 171 |
+
|
| 172 |
+
def concurrency_safe_rename(src, dst):
|
| 173 |
+
"""Renames ``src`` into ``dst`` overwriting ``dst`` if it exists.
|
| 174 |
+
|
| 175 |
+
On Windows os.replace can yield permission errors if executed by two
|
| 176 |
+
different processes.
|
| 177 |
+
"""
|
| 178 |
+
max_sleep_time = 1
|
| 179 |
+
total_sleep_time = 0
|
| 180 |
+
sleep_time = 0.001
|
| 181 |
+
while total_sleep_time < max_sleep_time:
|
| 182 |
+
try:
|
| 183 |
+
replace(src, dst)
|
| 184 |
+
break
|
| 185 |
+
except Exception as exc:
|
| 186 |
+
if getattr(exc, "winerror", None) in access_denied_errors:
|
| 187 |
+
time.sleep(sleep_time)
|
| 188 |
+
total_sleep_time += sleep_time
|
| 189 |
+
sleep_time *= 2
|
| 190 |
+
else:
|
| 191 |
+
raise
|
| 192 |
+
else:
|
| 193 |
+
raise
|
| 194 |
+
else:
|
| 195 |
+
from os import replace as concurrency_safe_rename # noqa
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/compressor.py
ADDED
|
@@ -0,0 +1,572 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Classes and functions for managing compressors."""
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import zlib
|
| 5 |
+
|
| 6 |
+
from joblib.backports import LooseVersion
|
| 7 |
+
|
| 8 |
+
try:
|
| 9 |
+
from threading import RLock
|
| 10 |
+
except ImportError:
|
| 11 |
+
from dummy_threading import RLock
|
| 12 |
+
|
| 13 |
+
try:
|
| 14 |
+
import bz2
|
| 15 |
+
except ImportError:
|
| 16 |
+
bz2 = None
|
| 17 |
+
|
| 18 |
+
try:
|
| 19 |
+
import lz4
|
| 20 |
+
from lz4.frame import LZ4FrameFile
|
| 21 |
+
except ImportError:
|
| 22 |
+
lz4 = None
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
import lzma
|
| 26 |
+
except ImportError:
|
| 27 |
+
lzma = None
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
LZ4_NOT_INSTALLED_ERROR = (
|
| 31 |
+
"LZ4 is not installed. Install it with pip: https://python-lz4.readthedocs.io/"
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
# Registered compressors
|
| 35 |
+
_COMPRESSORS = {}
|
| 36 |
+
|
| 37 |
+
# Magic numbers of supported compression file formats.
|
| 38 |
+
_ZFILE_PREFIX = b"ZF" # used with pickle files created before 0.9.3.
|
| 39 |
+
_ZLIB_PREFIX = b"\x78"
|
| 40 |
+
_GZIP_PREFIX = b"\x1f\x8b"
|
| 41 |
+
_BZ2_PREFIX = b"BZ"
|
| 42 |
+
_XZ_PREFIX = b"\xfd\x37\x7a\x58\x5a"
|
| 43 |
+
_LZMA_PREFIX = b"\x5d\x00"
|
| 44 |
+
_LZ4_PREFIX = b"\x04\x22\x4d\x18"
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def register_compressor(compressor_name, compressor, force=False):
|
| 48 |
+
"""Register a new compressor.
|
| 49 |
+
|
| 50 |
+
Parameters
|
| 51 |
+
----------
|
| 52 |
+
compressor_name: str.
|
| 53 |
+
The name of the compressor.
|
| 54 |
+
compressor: CompressorWrapper
|
| 55 |
+
An instance of a 'CompressorWrapper'.
|
| 56 |
+
"""
|
| 57 |
+
global _COMPRESSORS
|
| 58 |
+
if not isinstance(compressor_name, str):
|
| 59 |
+
raise ValueError(
|
| 60 |
+
"Compressor name should be a string, '{}' given.".format(compressor_name)
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
if not isinstance(compressor, CompressorWrapper):
|
| 64 |
+
raise ValueError(
|
| 65 |
+
"Compressor should implement the CompressorWrapper "
|
| 66 |
+
"interface, '{}' given.".format(compressor)
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
if compressor.fileobj_factory is not None and (
|
| 70 |
+
not hasattr(compressor.fileobj_factory, "read")
|
| 71 |
+
or not hasattr(compressor.fileobj_factory, "write")
|
| 72 |
+
or not hasattr(compressor.fileobj_factory, "seek")
|
| 73 |
+
or not hasattr(compressor.fileobj_factory, "tell")
|
| 74 |
+
):
|
| 75 |
+
raise ValueError(
|
| 76 |
+
"Compressor 'fileobj_factory' attribute should "
|
| 77 |
+
"implement the file object interface, '{}' given.".format(
|
| 78 |
+
compressor.fileobj_factory
|
| 79 |
+
)
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
if compressor_name in _COMPRESSORS and not force:
|
| 83 |
+
raise ValueError("Compressor '{}' already registered.".format(compressor_name))
|
| 84 |
+
|
| 85 |
+
_COMPRESSORS[compressor_name] = compressor
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
class CompressorWrapper:
|
| 89 |
+
"""A wrapper around a compressor file object.
|
| 90 |
+
|
| 91 |
+
Attributes
|
| 92 |
+
----------
|
| 93 |
+
obj: a file-like object
|
| 94 |
+
The object must implement the buffer interface and will be used
|
| 95 |
+
internally to compress/decompress the data.
|
| 96 |
+
prefix: bytestring
|
| 97 |
+
A bytestring corresponding to the magic number that identifies the
|
| 98 |
+
file format associated to the compressor.
|
| 99 |
+
extension: str
|
| 100 |
+
The file extension used to automatically select this compressor during
|
| 101 |
+
a dump to a file.
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
def __init__(self, obj, prefix=b"", extension=""):
|
| 105 |
+
self.fileobj_factory = obj
|
| 106 |
+
self.prefix = prefix
|
| 107 |
+
self.extension = extension
|
| 108 |
+
|
| 109 |
+
def compressor_file(self, fileobj, compresslevel=None):
|
| 110 |
+
"""Returns an instance of a compressor file object."""
|
| 111 |
+
if compresslevel is None:
|
| 112 |
+
return self.fileobj_factory(fileobj, "wb")
|
| 113 |
+
else:
|
| 114 |
+
return self.fileobj_factory(fileobj, "wb", compresslevel=compresslevel)
|
| 115 |
+
|
| 116 |
+
def decompressor_file(self, fileobj):
|
| 117 |
+
"""Returns an instance of a decompressor file object."""
|
| 118 |
+
return self.fileobj_factory(fileobj, "rb")
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
class BZ2CompressorWrapper(CompressorWrapper):
|
| 122 |
+
prefix = _BZ2_PREFIX
|
| 123 |
+
extension = ".bz2"
|
| 124 |
+
|
| 125 |
+
def __init__(self):
|
| 126 |
+
if bz2 is not None:
|
| 127 |
+
self.fileobj_factory = bz2.BZ2File
|
| 128 |
+
else:
|
| 129 |
+
self.fileobj_factory = None
|
| 130 |
+
|
| 131 |
+
def _check_versions(self):
|
| 132 |
+
if bz2 is None:
|
| 133 |
+
raise ValueError(
|
| 134 |
+
"bz2 module is not compiled on your python standard library."
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
def compressor_file(self, fileobj, compresslevel=None):
|
| 138 |
+
"""Returns an instance of a compressor file object."""
|
| 139 |
+
self._check_versions()
|
| 140 |
+
if compresslevel is None:
|
| 141 |
+
return self.fileobj_factory(fileobj, "wb")
|
| 142 |
+
else:
|
| 143 |
+
return self.fileobj_factory(fileobj, "wb", compresslevel=compresslevel)
|
| 144 |
+
|
| 145 |
+
def decompressor_file(self, fileobj):
|
| 146 |
+
"""Returns an instance of a decompressor file object."""
|
| 147 |
+
self._check_versions()
|
| 148 |
+
fileobj = self.fileobj_factory(fileobj, "rb")
|
| 149 |
+
return fileobj
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class LZMACompressorWrapper(CompressorWrapper):
|
| 153 |
+
prefix = _LZMA_PREFIX
|
| 154 |
+
extension = ".lzma"
|
| 155 |
+
_lzma_format_name = "FORMAT_ALONE"
|
| 156 |
+
|
| 157 |
+
def __init__(self):
|
| 158 |
+
if lzma is not None:
|
| 159 |
+
self.fileobj_factory = lzma.LZMAFile
|
| 160 |
+
self._lzma_format = getattr(lzma, self._lzma_format_name)
|
| 161 |
+
else:
|
| 162 |
+
self.fileobj_factory = None
|
| 163 |
+
|
| 164 |
+
def _check_versions(self):
|
| 165 |
+
if lzma is None:
|
| 166 |
+
raise ValueError(
|
| 167 |
+
"lzma module is not compiled on your python standard library."
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def compressor_file(self, fileobj, compresslevel=None):
|
| 171 |
+
"""Returns an instance of a compressor file object."""
|
| 172 |
+
if compresslevel is None:
|
| 173 |
+
return self.fileobj_factory(fileobj, "wb", format=self._lzma_format)
|
| 174 |
+
else:
|
| 175 |
+
return self.fileobj_factory(
|
| 176 |
+
fileobj, "wb", format=self._lzma_format, preset=compresslevel
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def decompressor_file(self, fileobj):
|
| 180 |
+
"""Returns an instance of a decompressor file object."""
|
| 181 |
+
return lzma.LZMAFile(fileobj, "rb")
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
class XZCompressorWrapper(LZMACompressorWrapper):
|
| 185 |
+
prefix = _XZ_PREFIX
|
| 186 |
+
extension = ".xz"
|
| 187 |
+
_lzma_format_name = "FORMAT_XZ"
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
class LZ4CompressorWrapper(CompressorWrapper):
|
| 191 |
+
prefix = _LZ4_PREFIX
|
| 192 |
+
extension = ".lz4"
|
| 193 |
+
|
| 194 |
+
def __init__(self):
|
| 195 |
+
if lz4 is not None:
|
| 196 |
+
self.fileobj_factory = LZ4FrameFile
|
| 197 |
+
else:
|
| 198 |
+
self.fileobj_factory = None
|
| 199 |
+
|
| 200 |
+
def _check_versions(self):
|
| 201 |
+
if lz4 is None:
|
| 202 |
+
raise ValueError(LZ4_NOT_INSTALLED_ERROR)
|
| 203 |
+
lz4_version = lz4.__version__
|
| 204 |
+
if lz4_version.startswith("v"):
|
| 205 |
+
lz4_version = lz4_version[1:]
|
| 206 |
+
if LooseVersion(lz4_version) < LooseVersion("0.19"):
|
| 207 |
+
raise ValueError(LZ4_NOT_INSTALLED_ERROR)
|
| 208 |
+
|
| 209 |
+
def compressor_file(self, fileobj, compresslevel=None):
|
| 210 |
+
"""Returns an instance of a compressor file object."""
|
| 211 |
+
self._check_versions()
|
| 212 |
+
if compresslevel is None:
|
| 213 |
+
return self.fileobj_factory(fileobj, "wb")
|
| 214 |
+
else:
|
| 215 |
+
return self.fileobj_factory(fileobj, "wb", compression_level=compresslevel)
|
| 216 |
+
|
| 217 |
+
def decompressor_file(self, fileobj):
|
| 218 |
+
"""Returns an instance of a decompressor file object."""
|
| 219 |
+
self._check_versions()
|
| 220 |
+
return self.fileobj_factory(fileobj, "rb")
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
###############################################################################
|
| 224 |
+
# base file compression/decompression object definition
|
| 225 |
+
_MODE_CLOSED = 0
|
| 226 |
+
_MODE_READ = 1
|
| 227 |
+
_MODE_READ_EOF = 2
|
| 228 |
+
_MODE_WRITE = 3
|
| 229 |
+
_BUFFER_SIZE = 8192
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
class BinaryZlibFile(io.BufferedIOBase):
|
| 233 |
+
"""A file object providing transparent zlib (de)compression.
|
| 234 |
+
|
| 235 |
+
TODO python2_drop: is it still needed since we dropped Python 2 support A
|
| 236 |
+
BinaryZlibFile can act as a wrapper for an existing file object, or refer
|
| 237 |
+
directly to a named file on disk.
|
| 238 |
+
|
| 239 |
+
Note that BinaryZlibFile provides only a *binary* file interface: data read
|
| 240 |
+
is returned as bytes, and data to be written should be given as bytes.
|
| 241 |
+
|
| 242 |
+
This object is an adaptation of the BZ2File object and is compatible with
|
| 243 |
+
versions of python >= 2.7.
|
| 244 |
+
|
| 245 |
+
If filename is a str or bytes object, it gives the name
|
| 246 |
+
of the file to be opened. Otherwise, it should be a file object,
|
| 247 |
+
which will be used to read or write the compressed data.
|
| 248 |
+
|
| 249 |
+
mode can be 'rb' for reading (default) or 'wb' for (over)writing
|
| 250 |
+
|
| 251 |
+
If mode is 'wb', compresslevel can be a number between 1
|
| 252 |
+
and 9 specifying the level of compression: 1 produces the least
|
| 253 |
+
compression, and 9 produces the most compression. 3 is the default.
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
wbits = zlib.MAX_WBITS
|
| 257 |
+
|
| 258 |
+
def __init__(self, filename, mode="rb", compresslevel=3):
|
| 259 |
+
# This lock must be recursive, so that BufferedIOBase's
|
| 260 |
+
# readline(), readlines() and writelines() don't deadlock.
|
| 261 |
+
self._lock = RLock()
|
| 262 |
+
self._fp = None
|
| 263 |
+
self._closefp = False
|
| 264 |
+
self._mode = _MODE_CLOSED
|
| 265 |
+
self._pos = 0
|
| 266 |
+
self._size = -1
|
| 267 |
+
self.compresslevel = compresslevel
|
| 268 |
+
|
| 269 |
+
if not isinstance(compresslevel, int) or not (1 <= compresslevel <= 9):
|
| 270 |
+
raise ValueError(
|
| 271 |
+
"'compresslevel' must be an integer "
|
| 272 |
+
"between 1 and 9. You provided 'compresslevel={}'".format(compresslevel)
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
if mode == "rb":
|
| 276 |
+
self._mode = _MODE_READ
|
| 277 |
+
self._decompressor = zlib.decompressobj(self.wbits)
|
| 278 |
+
self._buffer = b""
|
| 279 |
+
self._buffer_offset = 0
|
| 280 |
+
elif mode == "wb":
|
| 281 |
+
self._mode = _MODE_WRITE
|
| 282 |
+
self._compressor = zlib.compressobj(
|
| 283 |
+
self.compresslevel, zlib.DEFLATED, self.wbits, zlib.DEF_MEM_LEVEL, 0
|
| 284 |
+
)
|
| 285 |
+
else:
|
| 286 |
+
raise ValueError("Invalid mode: %r" % (mode,))
|
| 287 |
+
|
| 288 |
+
if isinstance(filename, str):
|
| 289 |
+
self._fp = io.open(filename, mode)
|
| 290 |
+
self._closefp = True
|
| 291 |
+
elif hasattr(filename, "read") or hasattr(filename, "write"):
|
| 292 |
+
self._fp = filename
|
| 293 |
+
else:
|
| 294 |
+
raise TypeError("filename must be a str or bytes object, or a file")
|
| 295 |
+
|
| 296 |
+
def close(self):
|
| 297 |
+
"""Flush and close the file.
|
| 298 |
+
|
| 299 |
+
May be called more than once without error. Once the file is
|
| 300 |
+
closed, any other operation on it will raise a ValueError.
|
| 301 |
+
"""
|
| 302 |
+
with self._lock:
|
| 303 |
+
if self._mode == _MODE_CLOSED:
|
| 304 |
+
return
|
| 305 |
+
try:
|
| 306 |
+
if self._mode in (_MODE_READ, _MODE_READ_EOF):
|
| 307 |
+
self._decompressor = None
|
| 308 |
+
elif self._mode == _MODE_WRITE:
|
| 309 |
+
self._fp.write(self._compressor.flush())
|
| 310 |
+
self._compressor = None
|
| 311 |
+
finally:
|
| 312 |
+
try:
|
| 313 |
+
if self._closefp:
|
| 314 |
+
self._fp.close()
|
| 315 |
+
finally:
|
| 316 |
+
self._fp = None
|
| 317 |
+
self._closefp = False
|
| 318 |
+
self._mode = _MODE_CLOSED
|
| 319 |
+
self._buffer = b""
|
| 320 |
+
self._buffer_offset = 0
|
| 321 |
+
|
| 322 |
+
@property
|
| 323 |
+
def closed(self):
|
| 324 |
+
"""True if this file is closed."""
|
| 325 |
+
return self._mode == _MODE_CLOSED
|
| 326 |
+
|
| 327 |
+
def fileno(self):
|
| 328 |
+
"""Return the file descriptor for the underlying file."""
|
| 329 |
+
self._check_not_closed()
|
| 330 |
+
return self._fp.fileno()
|
| 331 |
+
|
| 332 |
+
def seekable(self):
|
| 333 |
+
"""Return whether the file supports seeking."""
|
| 334 |
+
return self.readable() and self._fp.seekable()
|
| 335 |
+
|
| 336 |
+
def readable(self):
|
| 337 |
+
"""Return whether the file was opened for reading."""
|
| 338 |
+
self._check_not_closed()
|
| 339 |
+
return self._mode in (_MODE_READ, _MODE_READ_EOF)
|
| 340 |
+
|
| 341 |
+
def writable(self):
|
| 342 |
+
"""Return whether the file was opened for writing."""
|
| 343 |
+
self._check_not_closed()
|
| 344 |
+
return self._mode == _MODE_WRITE
|
| 345 |
+
|
| 346 |
+
# Mode-checking helper functions.
|
| 347 |
+
|
| 348 |
+
def _check_not_closed(self):
|
| 349 |
+
if self.closed:
|
| 350 |
+
fname = getattr(self._fp, "name", None)
|
| 351 |
+
msg = "I/O operation on closed file"
|
| 352 |
+
if fname is not None:
|
| 353 |
+
msg += " {}".format(fname)
|
| 354 |
+
msg += "."
|
| 355 |
+
raise ValueError(msg)
|
| 356 |
+
|
| 357 |
+
def _check_can_read(self):
|
| 358 |
+
if self._mode not in (_MODE_READ, _MODE_READ_EOF):
|
| 359 |
+
self._check_not_closed()
|
| 360 |
+
raise io.UnsupportedOperation("File not open for reading")
|
| 361 |
+
|
| 362 |
+
def _check_can_write(self):
|
| 363 |
+
if self._mode != _MODE_WRITE:
|
| 364 |
+
self._check_not_closed()
|
| 365 |
+
raise io.UnsupportedOperation("File not open for writing")
|
| 366 |
+
|
| 367 |
+
def _check_can_seek(self):
|
| 368 |
+
if self._mode not in (_MODE_READ, _MODE_READ_EOF):
|
| 369 |
+
self._check_not_closed()
|
| 370 |
+
raise io.UnsupportedOperation(
|
| 371 |
+
"Seeking is only supported on files open for reading"
|
| 372 |
+
)
|
| 373 |
+
if not self._fp.seekable():
|
| 374 |
+
raise io.UnsupportedOperation(
|
| 375 |
+
"The underlying file object does not support seeking"
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
# Fill the readahead buffer if it is empty. Returns False on EOF.
|
| 379 |
+
def _fill_buffer(self):
|
| 380 |
+
if self._mode == _MODE_READ_EOF:
|
| 381 |
+
return False
|
| 382 |
+
# Depending on the input data, our call to the decompressor may not
|
| 383 |
+
# return any data. In this case, try again after reading another block.
|
| 384 |
+
while self._buffer_offset == len(self._buffer):
|
| 385 |
+
try:
|
| 386 |
+
rawblock = self._decompressor.unused_data or self._fp.read(_BUFFER_SIZE)
|
| 387 |
+
if not rawblock:
|
| 388 |
+
raise EOFError
|
| 389 |
+
except EOFError:
|
| 390 |
+
# End-of-stream marker and end of file. We're good.
|
| 391 |
+
self._mode = _MODE_READ_EOF
|
| 392 |
+
self._size = self._pos
|
| 393 |
+
return False
|
| 394 |
+
else:
|
| 395 |
+
self._buffer = self._decompressor.decompress(rawblock)
|
| 396 |
+
self._buffer_offset = 0
|
| 397 |
+
return True
|
| 398 |
+
|
| 399 |
+
# Read data until EOF.
|
| 400 |
+
# If return_data is false, consume the data without returning it.
|
| 401 |
+
def _read_all(self, return_data=True):
|
| 402 |
+
# The loop assumes that _buffer_offset is 0. Ensure that this is true.
|
| 403 |
+
self._buffer = self._buffer[self._buffer_offset :]
|
| 404 |
+
self._buffer_offset = 0
|
| 405 |
+
|
| 406 |
+
blocks = []
|
| 407 |
+
while self._fill_buffer():
|
| 408 |
+
if return_data:
|
| 409 |
+
blocks.append(self._buffer)
|
| 410 |
+
self._pos += len(self._buffer)
|
| 411 |
+
self._buffer = b""
|
| 412 |
+
if return_data:
|
| 413 |
+
return b"".join(blocks)
|
| 414 |
+
|
| 415 |
+
# Read a block of up to n bytes.
|
| 416 |
+
# If return_data is false, consume the data without returning it.
|
| 417 |
+
def _read_block(self, n_bytes, return_data=True):
|
| 418 |
+
# If we have enough data buffered, return immediately.
|
| 419 |
+
end = self._buffer_offset + n_bytes
|
| 420 |
+
if end <= len(self._buffer):
|
| 421 |
+
data = self._buffer[self._buffer_offset : end]
|
| 422 |
+
self._buffer_offset = end
|
| 423 |
+
self._pos += len(data)
|
| 424 |
+
return data if return_data else None
|
| 425 |
+
|
| 426 |
+
# The loop assumes that _buffer_offset is 0. Ensure that this is true.
|
| 427 |
+
self._buffer = self._buffer[self._buffer_offset :]
|
| 428 |
+
self._buffer_offset = 0
|
| 429 |
+
|
| 430 |
+
blocks = []
|
| 431 |
+
while n_bytes > 0 and self._fill_buffer():
|
| 432 |
+
if n_bytes < len(self._buffer):
|
| 433 |
+
data = self._buffer[:n_bytes]
|
| 434 |
+
self._buffer_offset = n_bytes
|
| 435 |
+
else:
|
| 436 |
+
data = self._buffer
|
| 437 |
+
self._buffer = b""
|
| 438 |
+
if return_data:
|
| 439 |
+
blocks.append(data)
|
| 440 |
+
self._pos += len(data)
|
| 441 |
+
n_bytes -= len(data)
|
| 442 |
+
if return_data:
|
| 443 |
+
return b"".join(blocks)
|
| 444 |
+
|
| 445 |
+
def read(self, size=-1):
|
| 446 |
+
"""Read up to size uncompressed bytes from the file.
|
| 447 |
+
|
| 448 |
+
If size is negative or omitted, read until EOF is reached.
|
| 449 |
+
Returns b'' if the file is already at EOF.
|
| 450 |
+
"""
|
| 451 |
+
with self._lock:
|
| 452 |
+
self._check_can_read()
|
| 453 |
+
if size == 0:
|
| 454 |
+
return b""
|
| 455 |
+
elif size < 0:
|
| 456 |
+
return self._read_all()
|
| 457 |
+
else:
|
| 458 |
+
return self._read_block(size)
|
| 459 |
+
|
| 460 |
+
def readinto(self, b):
|
| 461 |
+
"""Read up to len(b) bytes into b.
|
| 462 |
+
|
| 463 |
+
Returns the number of bytes read (0 for EOF).
|
| 464 |
+
"""
|
| 465 |
+
with self._lock:
|
| 466 |
+
return io.BufferedIOBase.readinto(self, b)
|
| 467 |
+
|
| 468 |
+
def write(self, data):
|
| 469 |
+
"""Write a byte string to the file.
|
| 470 |
+
|
| 471 |
+
Returns the number of uncompressed bytes written, which is
|
| 472 |
+
always len(data). Note that due to buffering, the file on disk
|
| 473 |
+
may not reflect the data written until close() is called.
|
| 474 |
+
"""
|
| 475 |
+
with self._lock:
|
| 476 |
+
self._check_can_write()
|
| 477 |
+
# Convert data type if called by io.BufferedWriter.
|
| 478 |
+
if isinstance(data, memoryview):
|
| 479 |
+
data = data.tobytes()
|
| 480 |
+
|
| 481 |
+
compressed = self._compressor.compress(data)
|
| 482 |
+
self._fp.write(compressed)
|
| 483 |
+
self._pos += len(data)
|
| 484 |
+
return len(data)
|
| 485 |
+
|
| 486 |
+
# Rewind the file to the beginning of the data stream.
|
| 487 |
+
def _rewind(self):
|
| 488 |
+
self._fp.seek(0, 0)
|
| 489 |
+
self._mode = _MODE_READ
|
| 490 |
+
self._pos = 0
|
| 491 |
+
self._decompressor = zlib.decompressobj(self.wbits)
|
| 492 |
+
self._buffer = b""
|
| 493 |
+
self._buffer_offset = 0
|
| 494 |
+
|
| 495 |
+
def seek(self, offset, whence=0):
|
| 496 |
+
"""Change the file position.
|
| 497 |
+
|
| 498 |
+
The new position is specified by offset, relative to the
|
| 499 |
+
position indicated by whence. Values for whence are:
|
| 500 |
+
|
| 501 |
+
0: start of stream (default); offset must not be negative
|
| 502 |
+
1: current stream position
|
| 503 |
+
2: end of stream; offset must not be positive
|
| 504 |
+
|
| 505 |
+
Returns the new file position.
|
| 506 |
+
|
| 507 |
+
Note that seeking is emulated, so depending on the parameters,
|
| 508 |
+
this operation may be extremely slow.
|
| 509 |
+
"""
|
| 510 |
+
with self._lock:
|
| 511 |
+
self._check_can_seek()
|
| 512 |
+
|
| 513 |
+
# Recalculate offset as an absolute file position.
|
| 514 |
+
if whence == 0:
|
| 515 |
+
pass
|
| 516 |
+
elif whence == 1:
|
| 517 |
+
offset = self._pos + offset
|
| 518 |
+
elif whence == 2:
|
| 519 |
+
# Seeking relative to EOF - we need to know the file's size.
|
| 520 |
+
if self._size < 0:
|
| 521 |
+
self._read_all(return_data=False)
|
| 522 |
+
offset = self._size + offset
|
| 523 |
+
else:
|
| 524 |
+
raise ValueError("Invalid value for whence: %s" % (whence,))
|
| 525 |
+
|
| 526 |
+
# Make it so that offset is the number of bytes to skip forward.
|
| 527 |
+
if offset < self._pos:
|
| 528 |
+
self._rewind()
|
| 529 |
+
else:
|
| 530 |
+
offset -= self._pos
|
| 531 |
+
|
| 532 |
+
# Read and discard data until we reach the desired position.
|
| 533 |
+
self._read_block(offset, return_data=False)
|
| 534 |
+
|
| 535 |
+
return self._pos
|
| 536 |
+
|
| 537 |
+
def tell(self):
|
| 538 |
+
"""Return the current file position."""
|
| 539 |
+
with self._lock:
|
| 540 |
+
self._check_not_closed()
|
| 541 |
+
return self._pos
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
class ZlibCompressorWrapper(CompressorWrapper):
|
| 545 |
+
def __init__(self):
|
| 546 |
+
CompressorWrapper.__init__(
|
| 547 |
+
self, obj=BinaryZlibFile, prefix=_ZLIB_PREFIX, extension=".z"
|
| 548 |
+
)
|
| 549 |
+
|
| 550 |
+
|
| 551 |
+
class BinaryGzipFile(BinaryZlibFile):
|
| 552 |
+
"""A file object providing transparent gzip (de)compression.
|
| 553 |
+
|
| 554 |
+
If filename is a str or bytes object, it gives the name
|
| 555 |
+
of the file to be opened. Otherwise, it should be a file object,
|
| 556 |
+
which will be used to read or write the compressed data.
|
| 557 |
+
|
| 558 |
+
mode can be 'rb' for reading (default) or 'wb' for (over)writing
|
| 559 |
+
|
| 560 |
+
If mode is 'wb', compresslevel can be a number between 1
|
| 561 |
+
and 9 specifying the level of compression: 1 produces the least
|
| 562 |
+
compression, and 9 produces the most compression. 3 is the default.
|
| 563 |
+
"""
|
| 564 |
+
|
| 565 |
+
wbits = 31 # zlib compressor/decompressor wbits value for gzip format.
|
| 566 |
+
|
| 567 |
+
|
| 568 |
+
class GzipCompressorWrapper(CompressorWrapper):
|
| 569 |
+
def __init__(self):
|
| 570 |
+
CompressorWrapper.__init__(
|
| 571 |
+
self, obj=BinaryGzipFile, prefix=_GZIP_PREFIX, extension=".gz"
|
| 572 |
+
)
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/disk.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Disk management utilities.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
# Authors: Gael Varoquaux <gael dot varoquaux at normalesup dot org>
|
| 6 |
+
# Lars Buitinck
|
| 7 |
+
# Copyright (c) 2010 Gael Varoquaux
|
| 8 |
+
# License: BSD Style, 3 clauses.
|
| 9 |
+
|
| 10 |
+
import errno
|
| 11 |
+
import os
|
| 12 |
+
import shutil
|
| 13 |
+
import sys
|
| 14 |
+
import time
|
| 15 |
+
from multiprocessing import util
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
WindowsError
|
| 19 |
+
except NameError:
|
| 20 |
+
WindowsError = OSError
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def disk_used(path):
|
| 24 |
+
"""Return the disk usage in a directory."""
|
| 25 |
+
size = 0
|
| 26 |
+
for file in os.listdir(path) + ["."]:
|
| 27 |
+
stat = os.stat(os.path.join(path, file))
|
| 28 |
+
if hasattr(stat, "st_blocks"):
|
| 29 |
+
size += stat.st_blocks * 512
|
| 30 |
+
else:
|
| 31 |
+
# on some platform st_blocks is not available (e.g., Windows)
|
| 32 |
+
# approximate by rounding to next multiple of 512
|
| 33 |
+
size += (stat.st_size // 512 + 1) * 512
|
| 34 |
+
# We need to convert to int to avoid having longs on some systems (we
|
| 35 |
+
# don't want longs to avoid problems we SQLite)
|
| 36 |
+
return int(size / 1024.0)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def memstr_to_bytes(text):
|
| 40 |
+
"""Convert a memory text to its value in bytes."""
|
| 41 |
+
kilo = 1024
|
| 42 |
+
units = dict(K=kilo, M=kilo**2, G=kilo**3)
|
| 43 |
+
try:
|
| 44 |
+
size = int(units[text[-1]] * float(text[:-1]))
|
| 45 |
+
except (KeyError, ValueError) as e:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
"Invalid literal for size give: %s (type %s) should be "
|
| 48 |
+
"alike '10G', '500M', '50K'." % (text, type(text))
|
| 49 |
+
) from e
|
| 50 |
+
return size
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def mkdirp(d):
|
| 54 |
+
"""Ensure directory d exists (like mkdir -p on Unix)
|
| 55 |
+
No guarantee that the directory is writable.
|
| 56 |
+
"""
|
| 57 |
+
try:
|
| 58 |
+
os.makedirs(d)
|
| 59 |
+
except OSError as e:
|
| 60 |
+
if e.errno != errno.EEXIST:
|
| 61 |
+
raise
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# if a rmtree operation fails in rm_subdirs, wait for this much time (in secs),
|
| 65 |
+
# then retry up to RM_SUBDIRS_N_RETRY times. If it still fails, raise the
|
| 66 |
+
# exception. this mechanism ensures that the sub-process gc have the time to
|
| 67 |
+
# collect and close the memmaps before we fail.
|
| 68 |
+
RM_SUBDIRS_RETRY_TIME = 0.1
|
| 69 |
+
RM_SUBDIRS_N_RETRY = 10
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def rm_subdirs(path, onerror=None):
|
| 73 |
+
"""Remove all subdirectories in this path.
|
| 74 |
+
|
| 75 |
+
The directory indicated by `path` is left in place, and its subdirectories
|
| 76 |
+
are erased.
|
| 77 |
+
|
| 78 |
+
If onerror is set, it is called to handle the error with arguments (func,
|
| 79 |
+
path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
|
| 80 |
+
path is the argument to that function that caused it to fail; and
|
| 81 |
+
exc_info is a tuple returned by sys.exc_info(). If onerror is None,
|
| 82 |
+
an exception is raised.
|
| 83 |
+
"""
|
| 84 |
+
|
| 85 |
+
# NOTE this code is adapted from the one in shutil.rmtree, and is
|
| 86 |
+
# just as fast
|
| 87 |
+
|
| 88 |
+
names = []
|
| 89 |
+
try:
|
| 90 |
+
names = os.listdir(path)
|
| 91 |
+
except os.error:
|
| 92 |
+
if onerror is not None:
|
| 93 |
+
onerror(os.listdir, path, sys.exc_info())
|
| 94 |
+
else:
|
| 95 |
+
raise
|
| 96 |
+
|
| 97 |
+
for name in names:
|
| 98 |
+
fullname = os.path.join(path, name)
|
| 99 |
+
delete_folder(fullname, onerror=onerror)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def delete_folder(folder_path, onerror=None, allow_non_empty=True):
|
| 103 |
+
"""Utility function to cleanup a temporary folder if it still exists."""
|
| 104 |
+
if os.path.isdir(folder_path):
|
| 105 |
+
if onerror is not None:
|
| 106 |
+
shutil.rmtree(folder_path, False, onerror)
|
| 107 |
+
else:
|
| 108 |
+
# allow the rmtree to fail once, wait and re-try.
|
| 109 |
+
# if the error is raised again, fail
|
| 110 |
+
err_count = 0
|
| 111 |
+
while True:
|
| 112 |
+
files = os.listdir(folder_path)
|
| 113 |
+
try:
|
| 114 |
+
if len(files) == 0 or allow_non_empty:
|
| 115 |
+
shutil.rmtree(folder_path, ignore_errors=False, onerror=None)
|
| 116 |
+
util.debug("Successfully deleted {}".format(folder_path))
|
| 117 |
+
break
|
| 118 |
+
else:
|
| 119 |
+
raise OSError(
|
| 120 |
+
"Expected empty folder {} but got {} files.".format(
|
| 121 |
+
folder_path, len(files)
|
| 122 |
+
)
|
| 123 |
+
)
|
| 124 |
+
except (OSError, WindowsError):
|
| 125 |
+
err_count += 1
|
| 126 |
+
if err_count > RM_SUBDIRS_N_RETRY:
|
| 127 |
+
# the folder cannot be deleted right now. It maybe
|
| 128 |
+
# because some temporary files have not been deleted
|
| 129 |
+
# yet.
|
| 130 |
+
raise
|
| 131 |
+
time.sleep(RM_SUBDIRS_RETRY_TIME)
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/executor.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Utility function to construct a loky.ReusableExecutor with custom pickler.
|
| 2 |
+
|
| 3 |
+
This module provides efficient ways of working with data stored in
|
| 4 |
+
shared memory with numpy.memmap arrays without inducing any memory
|
| 5 |
+
copy between the parent and child processes.
|
| 6 |
+
"""
|
| 7 |
+
# Author: Thomas Moreau <thomas.moreau.2010@gmail.com>
|
| 8 |
+
# Copyright: 2017, Thomas Moreau
|
| 9 |
+
# License: BSD 3 clause
|
| 10 |
+
|
| 11 |
+
from ._memmapping_reducer import TemporaryResourcesManager, get_memmapping_reducers
|
| 12 |
+
from .externals.loky.reusable_executor import _ReusablePoolExecutor
|
| 13 |
+
|
| 14 |
+
_executor_args = None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def get_memmapping_executor(n_jobs, **kwargs):
|
| 18 |
+
return MemmappingExecutor.get_memmapping_executor(n_jobs, **kwargs)
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class MemmappingExecutor(_ReusablePoolExecutor):
|
| 22 |
+
@classmethod
|
| 23 |
+
def get_memmapping_executor(
|
| 24 |
+
cls,
|
| 25 |
+
n_jobs,
|
| 26 |
+
timeout=300,
|
| 27 |
+
initializer=None,
|
| 28 |
+
initargs=(),
|
| 29 |
+
env=None,
|
| 30 |
+
temp_folder=None,
|
| 31 |
+
context_id=None,
|
| 32 |
+
**backend_args,
|
| 33 |
+
):
|
| 34 |
+
"""Factory for ReusableExecutor with automatic memmapping for large
|
| 35 |
+
numpy arrays.
|
| 36 |
+
"""
|
| 37 |
+
global _executor_args
|
| 38 |
+
# Check if we can reuse the executor here instead of deferring the test
|
| 39 |
+
# to loky as the reducers are objects that changes at each call.
|
| 40 |
+
executor_args = backend_args.copy()
|
| 41 |
+
executor_args.update(env if env else {})
|
| 42 |
+
executor_args.update(
|
| 43 |
+
dict(timeout=timeout, initializer=initializer, initargs=initargs)
|
| 44 |
+
)
|
| 45 |
+
reuse = _executor_args is None or _executor_args == executor_args
|
| 46 |
+
_executor_args = executor_args
|
| 47 |
+
|
| 48 |
+
manager = TemporaryResourcesManager(temp_folder)
|
| 49 |
+
|
| 50 |
+
# reducers access the temporary folder in which to store temporary
|
| 51 |
+
# pickles through a call to manager.resolve_temp_folder_name. resolving
|
| 52 |
+
# the folder name dynamically is useful to use different folders across
|
| 53 |
+
# calls of a same reusable executor
|
| 54 |
+
job_reducers, result_reducers = get_memmapping_reducers(
|
| 55 |
+
unlink_on_gc_collect=True,
|
| 56 |
+
temp_folder_resolver=manager.resolve_temp_folder_name,
|
| 57 |
+
**backend_args,
|
| 58 |
+
)
|
| 59 |
+
_executor, executor_is_reused = super().get_reusable_executor(
|
| 60 |
+
n_jobs,
|
| 61 |
+
job_reducers=job_reducers,
|
| 62 |
+
result_reducers=result_reducers,
|
| 63 |
+
reuse=reuse,
|
| 64 |
+
timeout=timeout,
|
| 65 |
+
initializer=initializer,
|
| 66 |
+
initargs=initargs,
|
| 67 |
+
env=env,
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
if not executor_is_reused:
|
| 71 |
+
# Only set a _temp_folder_manager for new executors. Reused
|
| 72 |
+
# executors already have a _temporary_folder_manager that must not
|
| 73 |
+
# be re-assigned like that because it is referenced in various
|
| 74 |
+
# places in the reducing machinery of the executor.
|
| 75 |
+
_executor._temp_folder_manager = manager
|
| 76 |
+
|
| 77 |
+
if context_id is not None:
|
| 78 |
+
# Only register the specified context once we know which manager
|
| 79 |
+
# the current executor is using, in order to not register an atexit
|
| 80 |
+
# finalizer twice for the same folder.
|
| 81 |
+
_executor._temp_folder_manager.register_new_context(context_id)
|
| 82 |
+
|
| 83 |
+
return _executor
|
| 84 |
+
|
| 85 |
+
def terminate(self, kill_workers=False):
|
| 86 |
+
self.shutdown(kill_workers=kill_workers)
|
| 87 |
+
|
| 88 |
+
# When workers are killed in a brutal manner, they cannot execute the
|
| 89 |
+
# finalizer of their shared memmaps. The refcount of those memmaps may
|
| 90 |
+
# be off by an unknown number, so instead of decref'ing them, we force
|
| 91 |
+
# delete the whole temporary folder, and unregister them. There is no
|
| 92 |
+
# risk of PermissionError at folder deletion because at this
|
| 93 |
+
# point, all child processes are dead, so all references to temporary
|
| 94 |
+
# memmaps are closed. Otherwise, just try to delete as much as possible
|
| 95 |
+
# with allow_non_empty=True but if we can't, it will be clean up later
|
| 96 |
+
# on by the resource_tracker.
|
| 97 |
+
with self._submit_resize_lock:
|
| 98 |
+
self._temp_folder_manager._clean_temporary_resources(
|
| 99 |
+
force=kill_workers, allow_non_empty=True
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
@property
|
| 103 |
+
def _temp_folder(self):
|
| 104 |
+
# Legacy property in tests. could be removed if we refactored the
|
| 105 |
+
# memmapping tests. SHOULD ONLY BE USED IN TESTS!
|
| 106 |
+
# We cache this property because it is called late in the tests - at
|
| 107 |
+
# this point, all context have been unregistered, and
|
| 108 |
+
# resolve_temp_folder_name raises an error.
|
| 109 |
+
if getattr(self, "_cached_temp_folder", None) is not None:
|
| 110 |
+
return self._cached_temp_folder
|
| 111 |
+
else:
|
| 112 |
+
self._cached_temp_folder = (
|
| 113 |
+
self._temp_folder_manager.resolve_temp_folder_name()
|
| 114 |
+
) # noqa
|
| 115 |
+
return self._cached_temp_folder
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
class _TestingMemmappingExecutor(MemmappingExecutor):
|
| 119 |
+
"""Wrapper around ReusableExecutor to ease memmapping testing with Pool
|
| 120 |
+
and Executor. This is only for testing purposes.
|
| 121 |
+
|
| 122 |
+
"""
|
| 123 |
+
|
| 124 |
+
def apply_async(self, func, args):
|
| 125 |
+
"""Schedule a func to be run"""
|
| 126 |
+
future = self.submit(func, *args)
|
| 127 |
+
future.get = future.result
|
| 128 |
+
return future
|
| 129 |
+
|
| 130 |
+
def map(self, f, *args):
|
| 131 |
+
return list(super().map(f, *args))
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/__init__.py
ADDED
|
File without changes
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (227 Bytes). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/__init__.py
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import cloudpickle
|
| 2 |
+
from .cloudpickle import * # noqa
|
| 3 |
+
|
| 4 |
+
__doc__ = cloudpickle.__doc__
|
| 5 |
+
|
| 6 |
+
__version__ = "3.1.1"
|
| 7 |
+
|
| 8 |
+
__all__ = [ # noqa
|
| 9 |
+
"__version__",
|
| 10 |
+
"Pickler",
|
| 11 |
+
"CloudPickler",
|
| 12 |
+
"dumps",
|
| 13 |
+
"loads",
|
| 14 |
+
"dump",
|
| 15 |
+
"load",
|
| 16 |
+
"register_pickle_by_value",
|
| 17 |
+
"unregister_pickle_by_value",
|
| 18 |
+
]
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (462 Bytes). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/__pycache__/cloudpickle.cpython-310.pyc
ADDED
|
Binary file (38.3 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/cloudpickle.py
ADDED
|
@@ -0,0 +1,1545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Pickler class to extend the standard pickle.Pickler functionality
|
| 2 |
+
|
| 3 |
+
The main objective is to make it natural to perform distributed computing on
|
| 4 |
+
clusters (such as PySpark, Dask, Ray...) with interactively defined code
|
| 5 |
+
(functions, classes, ...) written in notebooks or console.
|
| 6 |
+
|
| 7 |
+
In particular this pickler adds the following features:
|
| 8 |
+
- serialize interactively-defined or locally-defined functions, classes,
|
| 9 |
+
enums, typevars, lambdas and nested functions to compiled byte code;
|
| 10 |
+
- deal with some other non-serializable objects in an ad-hoc manner where
|
| 11 |
+
applicable.
|
| 12 |
+
|
| 13 |
+
This pickler is therefore meant to be used for the communication between short
|
| 14 |
+
lived Python processes running the same version of Python and libraries. In
|
| 15 |
+
particular, it is not meant to be used for long term storage of Python objects.
|
| 16 |
+
|
| 17 |
+
It does not include an unpickler, as standard Python unpickling suffices.
|
| 18 |
+
|
| 19 |
+
This module was extracted from the `cloud` package, developed by `PiCloud, Inc.
|
| 20 |
+
<https://web.archive.org/web/20140626004012/http://www.picloud.com/>`_.
|
| 21 |
+
|
| 22 |
+
Copyright (c) 2012-now, CloudPickle developers and contributors.
|
| 23 |
+
Copyright (c) 2012, Regents of the University of California.
|
| 24 |
+
Copyright (c) 2009 `PiCloud, Inc. <https://web.archive.org/web/20140626004012/http://www.picloud.com/>`_.
|
| 25 |
+
All rights reserved.
|
| 26 |
+
|
| 27 |
+
Redistribution and use in source and binary forms, with or without
|
| 28 |
+
modification, are permitted provided that the following conditions
|
| 29 |
+
are met:
|
| 30 |
+
* Redistributions of source code must retain the above copyright
|
| 31 |
+
notice, this list of conditions and the following disclaimer.
|
| 32 |
+
* Redistributions in binary form must reproduce the above copyright
|
| 33 |
+
notice, this list of conditions and the following disclaimer in the
|
| 34 |
+
documentation and/or other materials provided with the distribution.
|
| 35 |
+
* Neither the name of the University of California, Berkeley nor the
|
| 36 |
+
names of its contributors may be used to endorse or promote
|
| 37 |
+
products derived from this software without specific prior written
|
| 38 |
+
permission.
|
| 39 |
+
|
| 40 |
+
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
| 41 |
+
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
| 42 |
+
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
| 43 |
+
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
| 44 |
+
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
| 45 |
+
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
|
| 46 |
+
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
|
| 47 |
+
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
|
| 48 |
+
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
|
| 49 |
+
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
|
| 50 |
+
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
| 51 |
+
"""
|
| 52 |
+
|
| 53 |
+
import _collections_abc
|
| 54 |
+
from collections import ChainMap, OrderedDict
|
| 55 |
+
import abc
|
| 56 |
+
import builtins
|
| 57 |
+
import copyreg
|
| 58 |
+
import dataclasses
|
| 59 |
+
import dis
|
| 60 |
+
from enum import Enum
|
| 61 |
+
import io
|
| 62 |
+
import itertools
|
| 63 |
+
import logging
|
| 64 |
+
import opcode
|
| 65 |
+
import pickle
|
| 66 |
+
from pickle import _getattribute as _pickle_getattribute
|
| 67 |
+
import platform
|
| 68 |
+
import struct
|
| 69 |
+
import sys
|
| 70 |
+
import threading
|
| 71 |
+
import types
|
| 72 |
+
import typing
|
| 73 |
+
import uuid
|
| 74 |
+
import warnings
|
| 75 |
+
import weakref
|
| 76 |
+
|
| 77 |
+
# The following import is required to be imported in the cloudpickle
|
| 78 |
+
# namespace to be able to load pickle files generated with older versions of
|
| 79 |
+
# cloudpickle. See: tests/test_backward_compat.py
|
| 80 |
+
from types import CellType # noqa: F401
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
# cloudpickle is meant for inter process communication: we expect all
|
| 84 |
+
# communicating processes to run the same Python version hence we favor
|
| 85 |
+
# communication speed over compatibility:
|
| 86 |
+
DEFAULT_PROTOCOL = pickle.HIGHEST_PROTOCOL
|
| 87 |
+
|
| 88 |
+
# Names of modules whose resources should be treated as dynamic.
|
| 89 |
+
_PICKLE_BY_VALUE_MODULES = set()
|
| 90 |
+
|
| 91 |
+
# Track the provenance of reconstructed dynamic classes to make it possible to
|
| 92 |
+
# reconstruct instances from the matching singleton class definition when
|
| 93 |
+
# appropriate and preserve the usual "isinstance" semantics of Python objects.
|
| 94 |
+
_DYNAMIC_CLASS_TRACKER_BY_CLASS = weakref.WeakKeyDictionary()
|
| 95 |
+
_DYNAMIC_CLASS_TRACKER_BY_ID = weakref.WeakValueDictionary()
|
| 96 |
+
_DYNAMIC_CLASS_TRACKER_LOCK = threading.Lock()
|
| 97 |
+
|
| 98 |
+
PYPY = platform.python_implementation() == "PyPy"
|
| 99 |
+
|
| 100 |
+
builtin_code_type = None
|
| 101 |
+
if PYPY:
|
| 102 |
+
# builtin-code objects only exist in pypy
|
| 103 |
+
builtin_code_type = type(float.__new__.__code__)
|
| 104 |
+
|
| 105 |
+
_extract_code_globals_cache = weakref.WeakKeyDictionary()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _get_or_create_tracker_id(class_def):
|
| 109 |
+
with _DYNAMIC_CLASS_TRACKER_LOCK:
|
| 110 |
+
class_tracker_id = _DYNAMIC_CLASS_TRACKER_BY_CLASS.get(class_def)
|
| 111 |
+
if class_tracker_id is None:
|
| 112 |
+
class_tracker_id = uuid.uuid4().hex
|
| 113 |
+
_DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
|
| 114 |
+
_DYNAMIC_CLASS_TRACKER_BY_ID[class_tracker_id] = class_def
|
| 115 |
+
return class_tracker_id
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _lookup_class_or_track(class_tracker_id, class_def):
|
| 119 |
+
if class_tracker_id is not None:
|
| 120 |
+
with _DYNAMIC_CLASS_TRACKER_LOCK:
|
| 121 |
+
class_def = _DYNAMIC_CLASS_TRACKER_BY_ID.setdefault(
|
| 122 |
+
class_tracker_id, class_def
|
| 123 |
+
)
|
| 124 |
+
_DYNAMIC_CLASS_TRACKER_BY_CLASS[class_def] = class_tracker_id
|
| 125 |
+
return class_def
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def register_pickle_by_value(module):
|
| 129 |
+
"""Register a module to make its functions and classes picklable by value.
|
| 130 |
+
|
| 131 |
+
By default, functions and classes that are attributes of an importable
|
| 132 |
+
module are to be pickled by reference, that is relying on re-importing
|
| 133 |
+
the attribute from the module at load time.
|
| 134 |
+
|
| 135 |
+
If `register_pickle_by_value(module)` is called, all its functions and
|
| 136 |
+
classes are subsequently to be pickled by value, meaning that they can
|
| 137 |
+
be loaded in Python processes where the module is not importable.
|
| 138 |
+
|
| 139 |
+
This is especially useful when developing a module in a distributed
|
| 140 |
+
execution environment: restarting the client Python process with the new
|
| 141 |
+
source code is enough: there is no need to re-install the new version
|
| 142 |
+
of the module on all the worker nodes nor to restart the workers.
|
| 143 |
+
|
| 144 |
+
Note: this feature is considered experimental. See the cloudpickle
|
| 145 |
+
README.md file for more details and limitations.
|
| 146 |
+
"""
|
| 147 |
+
if not isinstance(module, types.ModuleType):
|
| 148 |
+
raise ValueError(f"Input should be a module object, got {str(module)} instead")
|
| 149 |
+
# In the future, cloudpickle may need a way to access any module registered
|
| 150 |
+
# for pickling by value in order to introspect relative imports inside
|
| 151 |
+
# functions pickled by value. (see
|
| 152 |
+
# https://github.com/cloudpipe/cloudpickle/pull/417#issuecomment-873684633).
|
| 153 |
+
# This access can be ensured by checking that module is present in
|
| 154 |
+
# sys.modules at registering time and assuming that it will still be in
|
| 155 |
+
# there when accessed during pickling. Another alternative would be to
|
| 156 |
+
# store a weakref to the module. Even though cloudpickle does not implement
|
| 157 |
+
# this introspection yet, in order to avoid a possible breaking change
|
| 158 |
+
# later, we still enforce the presence of module inside sys.modules.
|
| 159 |
+
if module.__name__ not in sys.modules:
|
| 160 |
+
raise ValueError(
|
| 161 |
+
f"{module} was not imported correctly, have you used an "
|
| 162 |
+
"`import` statement to access it?"
|
| 163 |
+
)
|
| 164 |
+
_PICKLE_BY_VALUE_MODULES.add(module.__name__)
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def unregister_pickle_by_value(module):
|
| 168 |
+
"""Unregister that the input module should be pickled by value."""
|
| 169 |
+
if not isinstance(module, types.ModuleType):
|
| 170 |
+
raise ValueError(f"Input should be a module object, got {str(module)} instead")
|
| 171 |
+
if module.__name__ not in _PICKLE_BY_VALUE_MODULES:
|
| 172 |
+
raise ValueError(f"{module} is not registered for pickle by value")
|
| 173 |
+
else:
|
| 174 |
+
_PICKLE_BY_VALUE_MODULES.remove(module.__name__)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def list_registry_pickle_by_value():
|
| 178 |
+
return _PICKLE_BY_VALUE_MODULES.copy()
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _is_registered_pickle_by_value(module):
|
| 182 |
+
module_name = module.__name__
|
| 183 |
+
if module_name in _PICKLE_BY_VALUE_MODULES:
|
| 184 |
+
return True
|
| 185 |
+
while True:
|
| 186 |
+
parent_name = module_name.rsplit(".", 1)[0]
|
| 187 |
+
if parent_name == module_name:
|
| 188 |
+
break
|
| 189 |
+
if parent_name in _PICKLE_BY_VALUE_MODULES:
|
| 190 |
+
return True
|
| 191 |
+
module_name = parent_name
|
| 192 |
+
return False
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
if sys.version_info >= (3, 14):
|
| 196 |
+
def _getattribute(obj, name):
|
| 197 |
+
return _pickle_getattribute(obj, name.split('.'))
|
| 198 |
+
else:
|
| 199 |
+
def _getattribute(obj, name):
|
| 200 |
+
return _pickle_getattribute(obj, name)[0]
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def _whichmodule(obj, name):
|
| 204 |
+
"""Find the module an object belongs to.
|
| 205 |
+
|
| 206 |
+
This function differs from ``pickle.whichmodule`` in two ways:
|
| 207 |
+
- it does not mangle the cases where obj's module is __main__ and obj was
|
| 208 |
+
not found in any module.
|
| 209 |
+
- Errors arising during module introspection are ignored, as those errors
|
| 210 |
+
are considered unwanted side effects.
|
| 211 |
+
"""
|
| 212 |
+
module_name = getattr(obj, "__module__", None)
|
| 213 |
+
|
| 214 |
+
if module_name is not None:
|
| 215 |
+
return module_name
|
| 216 |
+
# Protect the iteration by using a copy of sys.modules against dynamic
|
| 217 |
+
# modules that trigger imports of other modules upon calls to getattr or
|
| 218 |
+
# other threads importing at the same time.
|
| 219 |
+
for module_name, module in sys.modules.copy().items():
|
| 220 |
+
# Some modules such as coverage can inject non-module objects inside
|
| 221 |
+
# sys.modules
|
| 222 |
+
if (
|
| 223 |
+
module_name == "__main__"
|
| 224 |
+
or module_name == "__mp_main__"
|
| 225 |
+
or module is None
|
| 226 |
+
or not isinstance(module, types.ModuleType)
|
| 227 |
+
):
|
| 228 |
+
continue
|
| 229 |
+
try:
|
| 230 |
+
if _getattribute(module, name) is obj:
|
| 231 |
+
return module_name
|
| 232 |
+
except Exception:
|
| 233 |
+
pass
|
| 234 |
+
return None
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _should_pickle_by_reference(obj, name=None):
|
| 238 |
+
"""Test whether an function or a class should be pickled by reference
|
| 239 |
+
|
| 240 |
+
Pickling by reference means by that the object (typically a function or a
|
| 241 |
+
class) is an attribute of a module that is assumed to be importable in the
|
| 242 |
+
target Python environment. Loading will therefore rely on importing the
|
| 243 |
+
module and then calling `getattr` on it to access the function or class.
|
| 244 |
+
|
| 245 |
+
Pickling by reference is the only option to pickle functions and classes
|
| 246 |
+
in the standard library. In cloudpickle the alternative option is to
|
| 247 |
+
pickle by value (for instance for interactively or locally defined
|
| 248 |
+
functions and classes or for attributes of modules that have been
|
| 249 |
+
explicitly registered to be pickled by value.
|
| 250 |
+
"""
|
| 251 |
+
if isinstance(obj, types.FunctionType) or issubclass(type(obj), type):
|
| 252 |
+
module_and_name = _lookup_module_and_qualname(obj, name=name)
|
| 253 |
+
if module_and_name is None:
|
| 254 |
+
return False
|
| 255 |
+
module, name = module_and_name
|
| 256 |
+
return not _is_registered_pickle_by_value(module)
|
| 257 |
+
|
| 258 |
+
elif isinstance(obj, types.ModuleType):
|
| 259 |
+
# We assume that sys.modules is primarily used as a cache mechanism for
|
| 260 |
+
# the Python import machinery. Checking if a module has been added in
|
| 261 |
+
# is sys.modules therefore a cheap and simple heuristic to tell us
|
| 262 |
+
# whether we can assume that a given module could be imported by name
|
| 263 |
+
# in another Python process.
|
| 264 |
+
if _is_registered_pickle_by_value(obj):
|
| 265 |
+
return False
|
| 266 |
+
return obj.__name__ in sys.modules
|
| 267 |
+
else:
|
| 268 |
+
raise TypeError(
|
| 269 |
+
"cannot check importability of {} instances".format(type(obj).__name__)
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def _lookup_module_and_qualname(obj, name=None):
|
| 274 |
+
if name is None:
|
| 275 |
+
name = getattr(obj, "__qualname__", None)
|
| 276 |
+
if name is None: # pragma: no cover
|
| 277 |
+
# This used to be needed for Python 2.7 support but is probably not
|
| 278 |
+
# needed anymore. However we keep the __name__ introspection in case
|
| 279 |
+
# users of cloudpickle rely on this old behavior for unknown reasons.
|
| 280 |
+
name = getattr(obj, "__name__", None)
|
| 281 |
+
|
| 282 |
+
module_name = _whichmodule(obj, name)
|
| 283 |
+
|
| 284 |
+
if module_name is None:
|
| 285 |
+
# In this case, obj.__module__ is None AND obj was not found in any
|
| 286 |
+
# imported module. obj is thus treated as dynamic.
|
| 287 |
+
return None
|
| 288 |
+
|
| 289 |
+
if module_name == "__main__":
|
| 290 |
+
return None
|
| 291 |
+
|
| 292 |
+
# Note: if module_name is in sys.modules, the corresponding module is
|
| 293 |
+
# assumed importable at unpickling time. See #357
|
| 294 |
+
module = sys.modules.get(module_name, None)
|
| 295 |
+
if module is None:
|
| 296 |
+
# The main reason why obj's module would not be imported is that this
|
| 297 |
+
# module has been dynamically created, using for example
|
| 298 |
+
# types.ModuleType. The other possibility is that module was removed
|
| 299 |
+
# from sys.modules after obj was created/imported. But this case is not
|
| 300 |
+
# supported, as the standard pickle does not support it either.
|
| 301 |
+
return None
|
| 302 |
+
|
| 303 |
+
try:
|
| 304 |
+
obj2 = _getattribute(module, name)
|
| 305 |
+
except AttributeError:
|
| 306 |
+
# obj was not found inside the module it points to
|
| 307 |
+
return None
|
| 308 |
+
if obj2 is not obj:
|
| 309 |
+
return None
|
| 310 |
+
return module, name
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def _extract_code_globals(co):
|
| 314 |
+
"""Find all globals names read or written to by codeblock co."""
|
| 315 |
+
out_names = _extract_code_globals_cache.get(co)
|
| 316 |
+
if out_names is None:
|
| 317 |
+
# We use a dict with None values instead of a set to get a
|
| 318 |
+
# deterministic order and avoid introducing non-deterministic pickle
|
| 319 |
+
# bytes as a results.
|
| 320 |
+
out_names = {name: None for name in _walk_global_ops(co)}
|
| 321 |
+
|
| 322 |
+
# Declaring a function inside another one using the "def ..." syntax
|
| 323 |
+
# generates a constant code object corresponding to the one of the
|
| 324 |
+
# nested function's As the nested function may itself need global
|
| 325 |
+
# variables, we need to introspect its code, extract its globals, (look
|
| 326 |
+
# for code object in it's co_consts attribute..) and add the result to
|
| 327 |
+
# code_globals
|
| 328 |
+
if co.co_consts:
|
| 329 |
+
for const in co.co_consts:
|
| 330 |
+
if isinstance(const, types.CodeType):
|
| 331 |
+
out_names.update(_extract_code_globals(const))
|
| 332 |
+
|
| 333 |
+
_extract_code_globals_cache[co] = out_names
|
| 334 |
+
|
| 335 |
+
return out_names
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def _find_imported_submodules(code, top_level_dependencies):
|
| 339 |
+
"""Find currently imported submodules used by a function.
|
| 340 |
+
|
| 341 |
+
Submodules used by a function need to be detected and referenced for the
|
| 342 |
+
function to work correctly at depickling time. Because submodules can be
|
| 343 |
+
referenced as attribute of their parent package (``package.submodule``), we
|
| 344 |
+
need a special introspection technique that does not rely on GLOBAL-related
|
| 345 |
+
opcodes to find references of them in a code object.
|
| 346 |
+
|
| 347 |
+
Example:
|
| 348 |
+
```
|
| 349 |
+
import concurrent.futures
|
| 350 |
+
import cloudpickle
|
| 351 |
+
def func():
|
| 352 |
+
x = concurrent.futures.ThreadPoolExecutor
|
| 353 |
+
if __name__ == '__main__':
|
| 354 |
+
cloudpickle.dumps(func)
|
| 355 |
+
```
|
| 356 |
+
The globals extracted by cloudpickle in the function's state include the
|
| 357 |
+
concurrent package, but not its submodule (here, concurrent.futures), which
|
| 358 |
+
is the module used by func. Find_imported_submodules will detect the usage
|
| 359 |
+
of concurrent.futures. Saving this module alongside with func will ensure
|
| 360 |
+
that calling func once depickled does not fail due to concurrent.futures
|
| 361 |
+
not being imported
|
| 362 |
+
"""
|
| 363 |
+
|
| 364 |
+
subimports = []
|
| 365 |
+
# check if any known dependency is an imported package
|
| 366 |
+
for x in top_level_dependencies:
|
| 367 |
+
if (
|
| 368 |
+
isinstance(x, types.ModuleType)
|
| 369 |
+
and hasattr(x, "__package__")
|
| 370 |
+
and x.__package__
|
| 371 |
+
):
|
| 372 |
+
# check if the package has any currently loaded sub-imports
|
| 373 |
+
prefix = x.__name__ + "."
|
| 374 |
+
# A concurrent thread could mutate sys.modules,
|
| 375 |
+
# make sure we iterate over a copy to avoid exceptions
|
| 376 |
+
for name in list(sys.modules):
|
| 377 |
+
# Older versions of pytest will add a "None" module to
|
| 378 |
+
# sys.modules.
|
| 379 |
+
if name is not None and name.startswith(prefix):
|
| 380 |
+
# check whether the function can address the sub-module
|
| 381 |
+
tokens = set(name[len(prefix) :].split("."))
|
| 382 |
+
if not tokens - set(code.co_names):
|
| 383 |
+
subimports.append(sys.modules[name])
|
| 384 |
+
return subimports
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# relevant opcodes
|
| 388 |
+
STORE_GLOBAL = opcode.opmap["STORE_GLOBAL"]
|
| 389 |
+
DELETE_GLOBAL = opcode.opmap["DELETE_GLOBAL"]
|
| 390 |
+
LOAD_GLOBAL = opcode.opmap["LOAD_GLOBAL"]
|
| 391 |
+
GLOBAL_OPS = (STORE_GLOBAL, DELETE_GLOBAL, LOAD_GLOBAL)
|
| 392 |
+
HAVE_ARGUMENT = dis.HAVE_ARGUMENT
|
| 393 |
+
EXTENDED_ARG = dis.EXTENDED_ARG
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
_BUILTIN_TYPE_NAMES = {}
|
| 397 |
+
for k, v in types.__dict__.items():
|
| 398 |
+
if type(v) is type:
|
| 399 |
+
_BUILTIN_TYPE_NAMES[v] = k
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def _builtin_type(name):
|
| 403 |
+
if name == "ClassType": # pragma: no cover
|
| 404 |
+
# Backward compat to load pickle files generated with cloudpickle
|
| 405 |
+
# < 1.3 even if loading pickle files from older versions is not
|
| 406 |
+
# officially supported.
|
| 407 |
+
return type
|
| 408 |
+
return getattr(types, name)
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def _walk_global_ops(code):
|
| 412 |
+
"""Yield referenced name for global-referencing instructions in code."""
|
| 413 |
+
for instr in dis.get_instructions(code):
|
| 414 |
+
op = instr.opcode
|
| 415 |
+
if op in GLOBAL_OPS:
|
| 416 |
+
yield instr.argval
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
def _extract_class_dict(cls):
|
| 420 |
+
"""Retrieve a copy of the dict of a class without the inherited method."""
|
| 421 |
+
# Hack to circumvent non-predictable memoization caused by string interning.
|
| 422 |
+
# See the inline comment in _class_setstate for details.
|
| 423 |
+
clsdict = {"".join(k): cls.__dict__[k] for k in sorted(cls.__dict__)}
|
| 424 |
+
|
| 425 |
+
if len(cls.__bases__) == 1:
|
| 426 |
+
inherited_dict = cls.__bases__[0].__dict__
|
| 427 |
+
else:
|
| 428 |
+
inherited_dict = {}
|
| 429 |
+
for base in reversed(cls.__bases__):
|
| 430 |
+
inherited_dict.update(base.__dict__)
|
| 431 |
+
to_remove = []
|
| 432 |
+
for name, value in clsdict.items():
|
| 433 |
+
try:
|
| 434 |
+
base_value = inherited_dict[name]
|
| 435 |
+
if value is base_value:
|
| 436 |
+
to_remove.append(name)
|
| 437 |
+
except KeyError:
|
| 438 |
+
pass
|
| 439 |
+
for name in to_remove:
|
| 440 |
+
clsdict.pop(name)
|
| 441 |
+
return clsdict
|
| 442 |
+
|
| 443 |
+
|
| 444 |
+
def is_tornado_coroutine(func):
|
| 445 |
+
"""Return whether `func` is a Tornado coroutine function.
|
| 446 |
+
|
| 447 |
+
Running coroutines are not supported.
|
| 448 |
+
"""
|
| 449 |
+
warnings.warn(
|
| 450 |
+
"is_tornado_coroutine is deprecated in cloudpickle 3.0 and will be "
|
| 451 |
+
"removed in cloudpickle 4.0. Use tornado.gen.is_coroutine_function "
|
| 452 |
+
"directly instead.",
|
| 453 |
+
category=DeprecationWarning,
|
| 454 |
+
)
|
| 455 |
+
if "tornado.gen" not in sys.modules:
|
| 456 |
+
return False
|
| 457 |
+
gen = sys.modules["tornado.gen"]
|
| 458 |
+
if not hasattr(gen, "is_coroutine_function"):
|
| 459 |
+
# Tornado version is too old
|
| 460 |
+
return False
|
| 461 |
+
return gen.is_coroutine_function(func)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def subimport(name):
|
| 465 |
+
# We cannot do simply: `return __import__(name)`: Indeed, if ``name`` is
|
| 466 |
+
# the name of a submodule, __import__ will return the top-level root module
|
| 467 |
+
# of this submodule. For instance, __import__('os.path') returns the `os`
|
| 468 |
+
# module.
|
| 469 |
+
__import__(name)
|
| 470 |
+
return sys.modules[name]
|
| 471 |
+
|
| 472 |
+
|
| 473 |
+
def dynamic_subimport(name, vars):
|
| 474 |
+
mod = types.ModuleType(name)
|
| 475 |
+
mod.__dict__.update(vars)
|
| 476 |
+
mod.__dict__["__builtins__"] = builtins.__dict__
|
| 477 |
+
return mod
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def _get_cell_contents(cell):
|
| 481 |
+
try:
|
| 482 |
+
return cell.cell_contents
|
| 483 |
+
except ValueError:
|
| 484 |
+
# Handle empty cells explicitly with a sentinel value.
|
| 485 |
+
return _empty_cell_value
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def instance(cls):
|
| 489 |
+
"""Create a new instance of a class.
|
| 490 |
+
|
| 491 |
+
Parameters
|
| 492 |
+
----------
|
| 493 |
+
cls : type
|
| 494 |
+
The class to create an instance of.
|
| 495 |
+
|
| 496 |
+
Returns
|
| 497 |
+
-------
|
| 498 |
+
instance : cls
|
| 499 |
+
A new instance of ``cls``.
|
| 500 |
+
"""
|
| 501 |
+
return cls()
|
| 502 |
+
|
| 503 |
+
|
| 504 |
+
@instance
|
| 505 |
+
class _empty_cell_value:
|
| 506 |
+
"""Sentinel for empty closures."""
|
| 507 |
+
|
| 508 |
+
@classmethod
|
| 509 |
+
def __reduce__(cls):
|
| 510 |
+
return cls.__name__
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def _make_function(code, globals, name, argdefs, closure):
|
| 514 |
+
# Setting __builtins__ in globals is needed for nogil CPython.
|
| 515 |
+
globals["__builtins__"] = __builtins__
|
| 516 |
+
return types.FunctionType(code, globals, name, argdefs, closure)
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _make_empty_cell():
|
| 520 |
+
if False:
|
| 521 |
+
# trick the compiler into creating an empty cell in our lambda
|
| 522 |
+
cell = None
|
| 523 |
+
raise AssertionError("this route should not be executed")
|
| 524 |
+
|
| 525 |
+
return (lambda: cell).__closure__[0]
|
| 526 |
+
|
| 527 |
+
|
| 528 |
+
def _make_cell(value=_empty_cell_value):
|
| 529 |
+
cell = _make_empty_cell()
|
| 530 |
+
if value is not _empty_cell_value:
|
| 531 |
+
cell.cell_contents = value
|
| 532 |
+
return cell
|
| 533 |
+
|
| 534 |
+
|
| 535 |
+
def _make_skeleton_class(
|
| 536 |
+
type_constructor, name, bases, type_kwargs, class_tracker_id, extra
|
| 537 |
+
):
|
| 538 |
+
"""Build dynamic class with an empty __dict__ to be filled once memoized
|
| 539 |
+
|
| 540 |
+
If class_tracker_id is not None, try to lookup an existing class definition
|
| 541 |
+
matching that id. If none is found, track a newly reconstructed class
|
| 542 |
+
definition under that id so that other instances stemming from the same
|
| 543 |
+
class id will also reuse this class definition.
|
| 544 |
+
|
| 545 |
+
The "extra" variable is meant to be a dict (or None) that can be used for
|
| 546 |
+
forward compatibility shall the need arise.
|
| 547 |
+
"""
|
| 548 |
+
# We need to intern the keys of the type_kwargs dict to avoid having
|
| 549 |
+
# different pickles for the same dynamic class depending on whether it was
|
| 550 |
+
# dynamically created or reconstructed from a pickled stream.
|
| 551 |
+
type_kwargs = {sys.intern(k): v for k, v in type_kwargs.items()}
|
| 552 |
+
|
| 553 |
+
skeleton_class = types.new_class(
|
| 554 |
+
name, bases, {"metaclass": type_constructor}, lambda ns: ns.update(type_kwargs)
|
| 555 |
+
)
|
| 556 |
+
|
| 557 |
+
return _lookup_class_or_track(class_tracker_id, skeleton_class)
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
def _make_skeleton_enum(
|
| 561 |
+
bases, name, qualname, members, module, class_tracker_id, extra
|
| 562 |
+
):
|
| 563 |
+
"""Build dynamic enum with an empty __dict__ to be filled once memoized
|
| 564 |
+
|
| 565 |
+
The creation of the enum class is inspired by the code of
|
| 566 |
+
EnumMeta._create_.
|
| 567 |
+
|
| 568 |
+
If class_tracker_id is not None, try to lookup an existing enum definition
|
| 569 |
+
matching that id. If none is found, track a newly reconstructed enum
|
| 570 |
+
definition under that id so that other instances stemming from the same
|
| 571 |
+
class id will also reuse this enum definition.
|
| 572 |
+
|
| 573 |
+
The "extra" variable is meant to be a dict (or None) that can be used for
|
| 574 |
+
forward compatibility shall the need arise.
|
| 575 |
+
"""
|
| 576 |
+
# enums always inherit from their base Enum class at the last position in
|
| 577 |
+
# the list of base classes:
|
| 578 |
+
enum_base = bases[-1]
|
| 579 |
+
metacls = enum_base.__class__
|
| 580 |
+
classdict = metacls.__prepare__(name, bases)
|
| 581 |
+
|
| 582 |
+
for member_name, member_value in members.items():
|
| 583 |
+
classdict[member_name] = member_value
|
| 584 |
+
enum_class = metacls.__new__(metacls, name, bases, classdict)
|
| 585 |
+
enum_class.__module__ = module
|
| 586 |
+
enum_class.__qualname__ = qualname
|
| 587 |
+
|
| 588 |
+
return _lookup_class_or_track(class_tracker_id, enum_class)
|
| 589 |
+
|
| 590 |
+
|
| 591 |
+
def _make_typevar(name, bound, constraints, covariant, contravariant, class_tracker_id):
|
| 592 |
+
tv = typing.TypeVar(
|
| 593 |
+
name,
|
| 594 |
+
*constraints,
|
| 595 |
+
bound=bound,
|
| 596 |
+
covariant=covariant,
|
| 597 |
+
contravariant=contravariant,
|
| 598 |
+
)
|
| 599 |
+
return _lookup_class_or_track(class_tracker_id, tv)
|
| 600 |
+
|
| 601 |
+
|
| 602 |
+
def _decompose_typevar(obj):
|
| 603 |
+
return (
|
| 604 |
+
obj.__name__,
|
| 605 |
+
obj.__bound__,
|
| 606 |
+
obj.__constraints__,
|
| 607 |
+
obj.__covariant__,
|
| 608 |
+
obj.__contravariant__,
|
| 609 |
+
_get_or_create_tracker_id(obj),
|
| 610 |
+
)
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _typevar_reduce(obj):
|
| 614 |
+
# TypeVar instances require the module information hence why we
|
| 615 |
+
# are not using the _should_pickle_by_reference directly
|
| 616 |
+
module_and_name = _lookup_module_and_qualname(obj, name=obj.__name__)
|
| 617 |
+
|
| 618 |
+
if module_and_name is None:
|
| 619 |
+
return (_make_typevar, _decompose_typevar(obj))
|
| 620 |
+
elif _is_registered_pickle_by_value(module_and_name[0]):
|
| 621 |
+
return (_make_typevar, _decompose_typevar(obj))
|
| 622 |
+
|
| 623 |
+
return (getattr, module_and_name)
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
def _get_bases(typ):
|
| 627 |
+
if "__orig_bases__" in getattr(typ, "__dict__", {}):
|
| 628 |
+
# For generic types (see PEP 560)
|
| 629 |
+
# Note that simply checking `hasattr(typ, '__orig_bases__')` is not
|
| 630 |
+
# correct. Subclasses of a fully-parameterized generic class does not
|
| 631 |
+
# have `__orig_bases__` defined, but `hasattr(typ, '__orig_bases__')`
|
| 632 |
+
# will return True because it's defined in the base class.
|
| 633 |
+
bases_attr = "__orig_bases__"
|
| 634 |
+
else:
|
| 635 |
+
# For regular class objects
|
| 636 |
+
bases_attr = "__bases__"
|
| 637 |
+
return getattr(typ, bases_attr)
|
| 638 |
+
|
| 639 |
+
|
| 640 |
+
def _make_dict_keys(obj, is_ordered=False):
|
| 641 |
+
if is_ordered:
|
| 642 |
+
return OrderedDict.fromkeys(obj).keys()
|
| 643 |
+
else:
|
| 644 |
+
return dict.fromkeys(obj).keys()
|
| 645 |
+
|
| 646 |
+
|
| 647 |
+
def _make_dict_values(obj, is_ordered=False):
|
| 648 |
+
if is_ordered:
|
| 649 |
+
return OrderedDict((i, _) for i, _ in enumerate(obj)).values()
|
| 650 |
+
else:
|
| 651 |
+
return {i: _ for i, _ in enumerate(obj)}.values()
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def _make_dict_items(obj, is_ordered=False):
|
| 655 |
+
if is_ordered:
|
| 656 |
+
return OrderedDict(obj).items()
|
| 657 |
+
else:
|
| 658 |
+
return obj.items()
|
| 659 |
+
|
| 660 |
+
|
| 661 |
+
# COLLECTION OF OBJECTS __getnewargs__-LIKE METHODS
|
| 662 |
+
# -------------------------------------------------
|
| 663 |
+
|
| 664 |
+
|
| 665 |
+
def _class_getnewargs(obj):
|
| 666 |
+
type_kwargs = {}
|
| 667 |
+
if "__module__" in obj.__dict__:
|
| 668 |
+
type_kwargs["__module__"] = obj.__module__
|
| 669 |
+
|
| 670 |
+
__dict__ = obj.__dict__.get("__dict__", None)
|
| 671 |
+
if isinstance(__dict__, property):
|
| 672 |
+
type_kwargs["__dict__"] = __dict__
|
| 673 |
+
|
| 674 |
+
return (
|
| 675 |
+
type(obj),
|
| 676 |
+
obj.__name__,
|
| 677 |
+
_get_bases(obj),
|
| 678 |
+
type_kwargs,
|
| 679 |
+
_get_or_create_tracker_id(obj),
|
| 680 |
+
None,
|
| 681 |
+
)
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
def _enum_getnewargs(obj):
|
| 685 |
+
members = {e.name: e.value for e in obj}
|
| 686 |
+
return (
|
| 687 |
+
obj.__bases__,
|
| 688 |
+
obj.__name__,
|
| 689 |
+
obj.__qualname__,
|
| 690 |
+
members,
|
| 691 |
+
obj.__module__,
|
| 692 |
+
_get_or_create_tracker_id(obj),
|
| 693 |
+
None,
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
# COLLECTION OF OBJECTS RECONSTRUCTORS
|
| 698 |
+
# ------------------------------------
|
| 699 |
+
def _file_reconstructor(retval):
|
| 700 |
+
return retval
|
| 701 |
+
|
| 702 |
+
|
| 703 |
+
# COLLECTION OF OBJECTS STATE GETTERS
|
| 704 |
+
# -----------------------------------
|
| 705 |
+
|
| 706 |
+
|
| 707 |
+
def _function_getstate(func):
|
| 708 |
+
# - Put func's dynamic attributes (stored in func.__dict__) in state. These
|
| 709 |
+
# attributes will be restored at unpickling time using
|
| 710 |
+
# f.__dict__.update(state)
|
| 711 |
+
# - Put func's members into slotstate. Such attributes will be restored at
|
| 712 |
+
# unpickling time by iterating over slotstate and calling setattr(func,
|
| 713 |
+
# slotname, slotvalue)
|
| 714 |
+
slotstate = {
|
| 715 |
+
# Hack to circumvent non-predictable memoization caused by string interning.
|
| 716 |
+
# See the inline comment in _class_setstate for details.
|
| 717 |
+
"__name__": "".join(func.__name__),
|
| 718 |
+
"__qualname__": "".join(func.__qualname__),
|
| 719 |
+
"__annotations__": func.__annotations__,
|
| 720 |
+
"__kwdefaults__": func.__kwdefaults__,
|
| 721 |
+
"__defaults__": func.__defaults__,
|
| 722 |
+
"__module__": func.__module__,
|
| 723 |
+
"__doc__": func.__doc__,
|
| 724 |
+
"__closure__": func.__closure__,
|
| 725 |
+
}
|
| 726 |
+
|
| 727 |
+
f_globals_ref = _extract_code_globals(func.__code__)
|
| 728 |
+
f_globals = {k: func.__globals__[k] for k in f_globals_ref if k in func.__globals__}
|
| 729 |
+
|
| 730 |
+
if func.__closure__ is not None:
|
| 731 |
+
closure_values = list(map(_get_cell_contents, func.__closure__))
|
| 732 |
+
else:
|
| 733 |
+
closure_values = ()
|
| 734 |
+
|
| 735 |
+
# Extract currently-imported submodules used by func. Storing these modules
|
| 736 |
+
# in a smoke _cloudpickle_subimports attribute of the object's state will
|
| 737 |
+
# trigger the side effect of importing these modules at unpickling time
|
| 738 |
+
# (which is necessary for func to work correctly once depickled)
|
| 739 |
+
slotstate["_cloudpickle_submodules"] = _find_imported_submodules(
|
| 740 |
+
func.__code__, itertools.chain(f_globals.values(), closure_values)
|
| 741 |
+
)
|
| 742 |
+
slotstate["__globals__"] = f_globals
|
| 743 |
+
|
| 744 |
+
# Hack to circumvent non-predictable memoization caused by string interning.
|
| 745 |
+
# See the inline comment in _class_setstate for details.
|
| 746 |
+
state = {"".join(k): v for k, v in func.__dict__.items()}
|
| 747 |
+
return state, slotstate
|
| 748 |
+
|
| 749 |
+
|
| 750 |
+
def _class_getstate(obj):
|
| 751 |
+
clsdict = _extract_class_dict(obj)
|
| 752 |
+
clsdict.pop("__weakref__", None)
|
| 753 |
+
|
| 754 |
+
if issubclass(type(obj), abc.ABCMeta):
|
| 755 |
+
# If obj is an instance of an ABCMeta subclass, don't pickle the
|
| 756 |
+
# cache/negative caches populated during isinstance/issubclass
|
| 757 |
+
# checks, but pickle the list of registered subclasses of obj.
|
| 758 |
+
clsdict.pop("_abc_cache", None)
|
| 759 |
+
clsdict.pop("_abc_negative_cache", None)
|
| 760 |
+
clsdict.pop("_abc_negative_cache_version", None)
|
| 761 |
+
registry = clsdict.pop("_abc_registry", None)
|
| 762 |
+
if registry is None:
|
| 763 |
+
# The abc caches and registered subclasses of a
|
| 764 |
+
# class are bundled into the single _abc_impl attribute
|
| 765 |
+
clsdict.pop("_abc_impl", None)
|
| 766 |
+
(registry, _, _, _) = abc._get_dump(obj)
|
| 767 |
+
|
| 768 |
+
clsdict["_abc_impl"] = [subclass_weakref() for subclass_weakref in registry]
|
| 769 |
+
else:
|
| 770 |
+
# In the above if clause, registry is a set of weakrefs -- in
|
| 771 |
+
# this case, registry is a WeakSet
|
| 772 |
+
clsdict["_abc_impl"] = [type_ for type_ in registry]
|
| 773 |
+
|
| 774 |
+
if "__slots__" in clsdict:
|
| 775 |
+
# pickle string length optimization: member descriptors of obj are
|
| 776 |
+
# created automatically from obj's __slots__ attribute, no need to
|
| 777 |
+
# save them in obj's state
|
| 778 |
+
if isinstance(obj.__slots__, str):
|
| 779 |
+
clsdict.pop(obj.__slots__)
|
| 780 |
+
else:
|
| 781 |
+
for k in obj.__slots__:
|
| 782 |
+
clsdict.pop(k, None)
|
| 783 |
+
|
| 784 |
+
clsdict.pop("__dict__", None) # unpicklable property object
|
| 785 |
+
|
| 786 |
+
return (clsdict, {})
|
| 787 |
+
|
| 788 |
+
|
| 789 |
+
def _enum_getstate(obj):
|
| 790 |
+
clsdict, slotstate = _class_getstate(obj)
|
| 791 |
+
|
| 792 |
+
members = {e.name: e.value for e in obj}
|
| 793 |
+
# Cleanup the clsdict that will be passed to _make_skeleton_enum:
|
| 794 |
+
# Those attributes are already handled by the metaclass.
|
| 795 |
+
for attrname in [
|
| 796 |
+
"_generate_next_value_",
|
| 797 |
+
"_member_names_",
|
| 798 |
+
"_member_map_",
|
| 799 |
+
"_member_type_",
|
| 800 |
+
"_value2member_map_",
|
| 801 |
+
]:
|
| 802 |
+
clsdict.pop(attrname, None)
|
| 803 |
+
for member in members:
|
| 804 |
+
clsdict.pop(member)
|
| 805 |
+
# Special handling of Enum subclasses
|
| 806 |
+
return clsdict, slotstate
|
| 807 |
+
|
| 808 |
+
|
| 809 |
+
# COLLECTIONS OF OBJECTS REDUCERS
|
| 810 |
+
# -------------------------------
|
| 811 |
+
# A reducer is a function taking a single argument (obj), and that returns a
|
| 812 |
+
# tuple with all the necessary data to re-construct obj. Apart from a few
|
| 813 |
+
# exceptions (list, dict, bytes, int, etc.), a reducer is necessary to
|
| 814 |
+
# correctly pickle an object.
|
| 815 |
+
# While many built-in objects (Exceptions objects, instances of the "object"
|
| 816 |
+
# class, etc), are shipped with their own built-in reducer (invoked using
|
| 817 |
+
# obj.__reduce__), some do not. The following methods were created to "fill
|
| 818 |
+
# these holes".
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
def _code_reduce(obj):
|
| 822 |
+
"""code object reducer."""
|
| 823 |
+
# If you are not sure about the order of arguments, take a look at help
|
| 824 |
+
# of the specific type from types, for example:
|
| 825 |
+
# >>> from types import CodeType
|
| 826 |
+
# >>> help(CodeType)
|
| 827 |
+
|
| 828 |
+
# Hack to circumvent non-predictable memoization caused by string interning.
|
| 829 |
+
# See the inline comment in _class_setstate for details.
|
| 830 |
+
co_name = "".join(obj.co_name)
|
| 831 |
+
|
| 832 |
+
# Create shallow copies of these tuple to make cloudpickle payload deterministic.
|
| 833 |
+
# When creating a code object during load, copies of these four tuples are
|
| 834 |
+
# created, while in the main process, these tuples can be shared.
|
| 835 |
+
# By always creating copies, we make sure the resulting payload is deterministic.
|
| 836 |
+
co_names = tuple(name for name in obj.co_names)
|
| 837 |
+
co_varnames = tuple(name for name in obj.co_varnames)
|
| 838 |
+
co_freevars = tuple(name for name in obj.co_freevars)
|
| 839 |
+
co_cellvars = tuple(name for name in obj.co_cellvars)
|
| 840 |
+
if hasattr(obj, "co_exceptiontable"):
|
| 841 |
+
# Python 3.11 and later: there are some new attributes
|
| 842 |
+
# related to the enhanced exceptions.
|
| 843 |
+
args = (
|
| 844 |
+
obj.co_argcount,
|
| 845 |
+
obj.co_posonlyargcount,
|
| 846 |
+
obj.co_kwonlyargcount,
|
| 847 |
+
obj.co_nlocals,
|
| 848 |
+
obj.co_stacksize,
|
| 849 |
+
obj.co_flags,
|
| 850 |
+
obj.co_code,
|
| 851 |
+
obj.co_consts,
|
| 852 |
+
co_names,
|
| 853 |
+
co_varnames,
|
| 854 |
+
obj.co_filename,
|
| 855 |
+
co_name,
|
| 856 |
+
obj.co_qualname,
|
| 857 |
+
obj.co_firstlineno,
|
| 858 |
+
obj.co_linetable,
|
| 859 |
+
obj.co_exceptiontable,
|
| 860 |
+
co_freevars,
|
| 861 |
+
co_cellvars,
|
| 862 |
+
)
|
| 863 |
+
elif hasattr(obj, "co_linetable"):
|
| 864 |
+
# Python 3.10 and later: obj.co_lnotab is deprecated and constructor
|
| 865 |
+
# expects obj.co_linetable instead.
|
| 866 |
+
args = (
|
| 867 |
+
obj.co_argcount,
|
| 868 |
+
obj.co_posonlyargcount,
|
| 869 |
+
obj.co_kwonlyargcount,
|
| 870 |
+
obj.co_nlocals,
|
| 871 |
+
obj.co_stacksize,
|
| 872 |
+
obj.co_flags,
|
| 873 |
+
obj.co_code,
|
| 874 |
+
obj.co_consts,
|
| 875 |
+
co_names,
|
| 876 |
+
co_varnames,
|
| 877 |
+
obj.co_filename,
|
| 878 |
+
co_name,
|
| 879 |
+
obj.co_firstlineno,
|
| 880 |
+
obj.co_linetable,
|
| 881 |
+
co_freevars,
|
| 882 |
+
co_cellvars,
|
| 883 |
+
)
|
| 884 |
+
elif hasattr(obj, "co_nmeta"): # pragma: no cover
|
| 885 |
+
# "nogil" Python: modified attributes from 3.9
|
| 886 |
+
args = (
|
| 887 |
+
obj.co_argcount,
|
| 888 |
+
obj.co_posonlyargcount,
|
| 889 |
+
obj.co_kwonlyargcount,
|
| 890 |
+
obj.co_nlocals,
|
| 891 |
+
obj.co_framesize,
|
| 892 |
+
obj.co_ndefaultargs,
|
| 893 |
+
obj.co_nmeta,
|
| 894 |
+
obj.co_flags,
|
| 895 |
+
obj.co_code,
|
| 896 |
+
obj.co_consts,
|
| 897 |
+
co_varnames,
|
| 898 |
+
obj.co_filename,
|
| 899 |
+
co_name,
|
| 900 |
+
obj.co_firstlineno,
|
| 901 |
+
obj.co_lnotab,
|
| 902 |
+
obj.co_exc_handlers,
|
| 903 |
+
obj.co_jump_table,
|
| 904 |
+
co_freevars,
|
| 905 |
+
co_cellvars,
|
| 906 |
+
obj.co_free2reg,
|
| 907 |
+
obj.co_cell2reg,
|
| 908 |
+
)
|
| 909 |
+
else:
|
| 910 |
+
# Backward compat for 3.8 and 3.9
|
| 911 |
+
args = (
|
| 912 |
+
obj.co_argcount,
|
| 913 |
+
obj.co_posonlyargcount,
|
| 914 |
+
obj.co_kwonlyargcount,
|
| 915 |
+
obj.co_nlocals,
|
| 916 |
+
obj.co_stacksize,
|
| 917 |
+
obj.co_flags,
|
| 918 |
+
obj.co_code,
|
| 919 |
+
obj.co_consts,
|
| 920 |
+
co_names,
|
| 921 |
+
co_varnames,
|
| 922 |
+
obj.co_filename,
|
| 923 |
+
co_name,
|
| 924 |
+
obj.co_firstlineno,
|
| 925 |
+
obj.co_lnotab,
|
| 926 |
+
co_freevars,
|
| 927 |
+
co_cellvars,
|
| 928 |
+
)
|
| 929 |
+
return types.CodeType, args
|
| 930 |
+
|
| 931 |
+
|
| 932 |
+
def _cell_reduce(obj):
|
| 933 |
+
"""Cell (containing values of a function's free variables) reducer."""
|
| 934 |
+
try:
|
| 935 |
+
obj.cell_contents
|
| 936 |
+
except ValueError: # cell is empty
|
| 937 |
+
return _make_empty_cell, ()
|
| 938 |
+
else:
|
| 939 |
+
return _make_cell, (obj.cell_contents,)
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
def _classmethod_reduce(obj):
|
| 943 |
+
orig_func = obj.__func__
|
| 944 |
+
return type(obj), (orig_func,)
|
| 945 |
+
|
| 946 |
+
|
| 947 |
+
def _file_reduce(obj):
|
| 948 |
+
"""Save a file."""
|
| 949 |
+
import io
|
| 950 |
+
|
| 951 |
+
if not hasattr(obj, "name") or not hasattr(obj, "mode"):
|
| 952 |
+
raise pickle.PicklingError(
|
| 953 |
+
"Cannot pickle files that do not map to an actual file"
|
| 954 |
+
)
|
| 955 |
+
if obj is sys.stdout:
|
| 956 |
+
return getattr, (sys, "stdout")
|
| 957 |
+
if obj is sys.stderr:
|
| 958 |
+
return getattr, (sys, "stderr")
|
| 959 |
+
if obj is sys.stdin:
|
| 960 |
+
raise pickle.PicklingError("Cannot pickle standard input")
|
| 961 |
+
if obj.closed:
|
| 962 |
+
raise pickle.PicklingError("Cannot pickle closed files")
|
| 963 |
+
if hasattr(obj, "isatty") and obj.isatty():
|
| 964 |
+
raise pickle.PicklingError("Cannot pickle files that map to tty objects")
|
| 965 |
+
if "r" not in obj.mode and "+" not in obj.mode:
|
| 966 |
+
raise pickle.PicklingError(
|
| 967 |
+
"Cannot pickle files that are not opened for reading: %s" % obj.mode
|
| 968 |
+
)
|
| 969 |
+
|
| 970 |
+
name = obj.name
|
| 971 |
+
|
| 972 |
+
retval = io.StringIO()
|
| 973 |
+
|
| 974 |
+
try:
|
| 975 |
+
# Read the whole file
|
| 976 |
+
curloc = obj.tell()
|
| 977 |
+
obj.seek(0)
|
| 978 |
+
contents = obj.read()
|
| 979 |
+
obj.seek(curloc)
|
| 980 |
+
except OSError as e:
|
| 981 |
+
raise pickle.PicklingError(
|
| 982 |
+
"Cannot pickle file %s as it cannot be read" % name
|
| 983 |
+
) from e
|
| 984 |
+
retval.write(contents)
|
| 985 |
+
retval.seek(curloc)
|
| 986 |
+
|
| 987 |
+
retval.name = name
|
| 988 |
+
return _file_reconstructor, (retval,)
|
| 989 |
+
|
| 990 |
+
|
| 991 |
+
def _getset_descriptor_reduce(obj):
|
| 992 |
+
return getattr, (obj.__objclass__, obj.__name__)
|
| 993 |
+
|
| 994 |
+
|
| 995 |
+
def _mappingproxy_reduce(obj):
|
| 996 |
+
return types.MappingProxyType, (dict(obj),)
|
| 997 |
+
|
| 998 |
+
|
| 999 |
+
def _memoryview_reduce(obj):
|
| 1000 |
+
return bytes, (obj.tobytes(),)
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
def _module_reduce(obj):
|
| 1004 |
+
if _should_pickle_by_reference(obj):
|
| 1005 |
+
return subimport, (obj.__name__,)
|
| 1006 |
+
else:
|
| 1007 |
+
# Some external libraries can populate the "__builtins__" entry of a
|
| 1008 |
+
# module's `__dict__` with unpicklable objects (see #316). For that
|
| 1009 |
+
# reason, we do not attempt to pickle the "__builtins__" entry, and
|
| 1010 |
+
# restore a default value for it at unpickling time.
|
| 1011 |
+
state = obj.__dict__.copy()
|
| 1012 |
+
state.pop("__builtins__", None)
|
| 1013 |
+
return dynamic_subimport, (obj.__name__, state)
|
| 1014 |
+
|
| 1015 |
+
|
| 1016 |
+
def _method_reduce(obj):
|
| 1017 |
+
return (types.MethodType, (obj.__func__, obj.__self__))
|
| 1018 |
+
|
| 1019 |
+
|
| 1020 |
+
def _logger_reduce(obj):
|
| 1021 |
+
return logging.getLogger, (obj.name,)
|
| 1022 |
+
|
| 1023 |
+
|
| 1024 |
+
def _root_logger_reduce(obj):
|
| 1025 |
+
return logging.getLogger, ()
|
| 1026 |
+
|
| 1027 |
+
|
| 1028 |
+
def _property_reduce(obj):
|
| 1029 |
+
return property, (obj.fget, obj.fset, obj.fdel, obj.__doc__)
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
def _weakset_reduce(obj):
|
| 1033 |
+
return weakref.WeakSet, (list(obj),)
|
| 1034 |
+
|
| 1035 |
+
|
| 1036 |
+
def _dynamic_class_reduce(obj):
|
| 1037 |
+
"""Save a class that can't be referenced as a module attribute.
|
| 1038 |
+
|
| 1039 |
+
This method is used to serialize classes that are defined inside
|
| 1040 |
+
functions, or that otherwise can't be serialized as attribute lookups
|
| 1041 |
+
from importable modules.
|
| 1042 |
+
"""
|
| 1043 |
+
if Enum is not None and issubclass(obj, Enum):
|
| 1044 |
+
return (
|
| 1045 |
+
_make_skeleton_enum,
|
| 1046 |
+
_enum_getnewargs(obj),
|
| 1047 |
+
_enum_getstate(obj),
|
| 1048 |
+
None,
|
| 1049 |
+
None,
|
| 1050 |
+
_class_setstate,
|
| 1051 |
+
)
|
| 1052 |
+
else:
|
| 1053 |
+
return (
|
| 1054 |
+
_make_skeleton_class,
|
| 1055 |
+
_class_getnewargs(obj),
|
| 1056 |
+
_class_getstate(obj),
|
| 1057 |
+
None,
|
| 1058 |
+
None,
|
| 1059 |
+
_class_setstate,
|
| 1060 |
+
)
|
| 1061 |
+
|
| 1062 |
+
|
| 1063 |
+
def _class_reduce(obj):
|
| 1064 |
+
"""Select the reducer depending on the dynamic nature of the class obj."""
|
| 1065 |
+
if obj is type(None): # noqa
|
| 1066 |
+
return type, (None,)
|
| 1067 |
+
elif obj is type(Ellipsis):
|
| 1068 |
+
return type, (Ellipsis,)
|
| 1069 |
+
elif obj is type(NotImplemented):
|
| 1070 |
+
return type, (NotImplemented,)
|
| 1071 |
+
elif obj in _BUILTIN_TYPE_NAMES:
|
| 1072 |
+
return _builtin_type, (_BUILTIN_TYPE_NAMES[obj],)
|
| 1073 |
+
elif not _should_pickle_by_reference(obj):
|
| 1074 |
+
return _dynamic_class_reduce(obj)
|
| 1075 |
+
return NotImplemented
|
| 1076 |
+
|
| 1077 |
+
|
| 1078 |
+
def _dict_keys_reduce(obj):
|
| 1079 |
+
# Safer not to ship the full dict as sending the rest might
|
| 1080 |
+
# be unintended and could potentially cause leaking of
|
| 1081 |
+
# sensitive information
|
| 1082 |
+
return _make_dict_keys, (list(obj),)
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
def _dict_values_reduce(obj):
|
| 1086 |
+
# Safer not to ship the full dict as sending the rest might
|
| 1087 |
+
# be unintended and could potentially cause leaking of
|
| 1088 |
+
# sensitive information
|
| 1089 |
+
return _make_dict_values, (list(obj),)
|
| 1090 |
+
|
| 1091 |
+
|
| 1092 |
+
def _dict_items_reduce(obj):
|
| 1093 |
+
return _make_dict_items, (dict(obj),)
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
+
def _odict_keys_reduce(obj):
|
| 1097 |
+
# Safer not to ship the full dict as sending the rest might
|
| 1098 |
+
# be unintended and could potentially cause leaking of
|
| 1099 |
+
# sensitive information
|
| 1100 |
+
return _make_dict_keys, (list(obj), True)
|
| 1101 |
+
|
| 1102 |
+
|
| 1103 |
+
def _odict_values_reduce(obj):
|
| 1104 |
+
# Safer not to ship the full dict as sending the rest might
|
| 1105 |
+
# be unintended and could potentially cause leaking of
|
| 1106 |
+
# sensitive information
|
| 1107 |
+
return _make_dict_values, (list(obj), True)
|
| 1108 |
+
|
| 1109 |
+
|
| 1110 |
+
def _odict_items_reduce(obj):
|
| 1111 |
+
return _make_dict_items, (dict(obj), True)
|
| 1112 |
+
|
| 1113 |
+
|
| 1114 |
+
def _dataclass_field_base_reduce(obj):
|
| 1115 |
+
return _get_dataclass_field_type_sentinel, (obj.name,)
|
| 1116 |
+
|
| 1117 |
+
|
| 1118 |
+
# COLLECTIONS OF OBJECTS STATE SETTERS
|
| 1119 |
+
# ------------------------------------
|
| 1120 |
+
# state setters are called at unpickling time, once the object is created and
|
| 1121 |
+
# it has to be updated to how it was at unpickling time.
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
def _function_setstate(obj, state):
|
| 1125 |
+
"""Update the state of a dynamic function.
|
| 1126 |
+
|
| 1127 |
+
As __closure__ and __globals__ are readonly attributes of a function, we
|
| 1128 |
+
cannot rely on the native setstate routine of pickle.load_build, that calls
|
| 1129 |
+
setattr on items of the slotstate. Instead, we have to modify them inplace.
|
| 1130 |
+
"""
|
| 1131 |
+
state, slotstate = state
|
| 1132 |
+
obj.__dict__.update(state)
|
| 1133 |
+
|
| 1134 |
+
obj_globals = slotstate.pop("__globals__")
|
| 1135 |
+
obj_closure = slotstate.pop("__closure__")
|
| 1136 |
+
# _cloudpickle_subimports is a set of submodules that must be loaded for
|
| 1137 |
+
# the pickled function to work correctly at unpickling time. Now that these
|
| 1138 |
+
# submodules are depickled (hence imported), they can be removed from the
|
| 1139 |
+
# object's state (the object state only served as a reference holder to
|
| 1140 |
+
# these submodules)
|
| 1141 |
+
slotstate.pop("_cloudpickle_submodules")
|
| 1142 |
+
|
| 1143 |
+
obj.__globals__.update(obj_globals)
|
| 1144 |
+
obj.__globals__["__builtins__"] = __builtins__
|
| 1145 |
+
|
| 1146 |
+
if obj_closure is not None:
|
| 1147 |
+
for i, cell in enumerate(obj_closure):
|
| 1148 |
+
try:
|
| 1149 |
+
value = cell.cell_contents
|
| 1150 |
+
except ValueError: # cell is empty
|
| 1151 |
+
continue
|
| 1152 |
+
obj.__closure__[i].cell_contents = value
|
| 1153 |
+
|
| 1154 |
+
for k, v in slotstate.items():
|
| 1155 |
+
setattr(obj, k, v)
|
| 1156 |
+
|
| 1157 |
+
|
| 1158 |
+
def _class_setstate(obj, state):
|
| 1159 |
+
state, slotstate = state
|
| 1160 |
+
registry = None
|
| 1161 |
+
for attrname, attr in state.items():
|
| 1162 |
+
if attrname == "_abc_impl":
|
| 1163 |
+
registry = attr
|
| 1164 |
+
else:
|
| 1165 |
+
# Note: setting attribute names on a class automatically triggers their
|
| 1166 |
+
# interning in CPython:
|
| 1167 |
+
# https://github.com/python/cpython/blob/v3.12.0/Objects/object.c#L957
|
| 1168 |
+
#
|
| 1169 |
+
# This means that to get deterministic pickling for a dynamic class that
|
| 1170 |
+
# was initially defined in a different Python process, the pickler
|
| 1171 |
+
# needs to ensure that dynamic class and function attribute names are
|
| 1172 |
+
# systematically copied into a non-interned version to avoid
|
| 1173 |
+
# unpredictable pickle payloads.
|
| 1174 |
+
#
|
| 1175 |
+
# Indeed the Pickler's memoizer relies on physical object identity to break
|
| 1176 |
+
# cycles in the reference graph of the object being serialized.
|
| 1177 |
+
setattr(obj, attrname, attr)
|
| 1178 |
+
|
| 1179 |
+
if sys.version_info >= (3, 13) and "__firstlineno__" in state:
|
| 1180 |
+
# Set the Python 3.13+ only __firstlineno__ attribute one more time, as it
|
| 1181 |
+
# will be automatically deleted by the `setattr(obj, attrname, attr)` call
|
| 1182 |
+
# above when `attrname` is "__firstlineno__". We assume that preserving this
|
| 1183 |
+
# information might be important for some users and that it not stale in the
|
| 1184 |
+
# context of cloudpickle usage, hence legitimate to propagate. Furthermore it
|
| 1185 |
+
# is necessary to do so to keep deterministic chained pickling as tested in
|
| 1186 |
+
# test_deterministic_str_interning_for_chained_dynamic_class_pickling.
|
| 1187 |
+
obj.__firstlineno__ = state["__firstlineno__"]
|
| 1188 |
+
|
| 1189 |
+
if registry is not None:
|
| 1190 |
+
for subclass in registry:
|
| 1191 |
+
obj.register(subclass)
|
| 1192 |
+
|
| 1193 |
+
return obj
|
| 1194 |
+
|
| 1195 |
+
|
| 1196 |
+
# COLLECTION OF DATACLASS UTILITIES
|
| 1197 |
+
# ---------------------------------
|
| 1198 |
+
# There are some internal sentinel values whose identity must be preserved when
|
| 1199 |
+
# unpickling dataclass fields. Each sentinel value has a unique name that we can
|
| 1200 |
+
# use to retrieve its identity at unpickling time.
|
| 1201 |
+
|
| 1202 |
+
|
| 1203 |
+
_DATACLASSE_FIELD_TYPE_SENTINELS = {
|
| 1204 |
+
dataclasses._FIELD.name: dataclasses._FIELD,
|
| 1205 |
+
dataclasses._FIELD_CLASSVAR.name: dataclasses._FIELD_CLASSVAR,
|
| 1206 |
+
dataclasses._FIELD_INITVAR.name: dataclasses._FIELD_INITVAR,
|
| 1207 |
+
}
|
| 1208 |
+
|
| 1209 |
+
|
| 1210 |
+
def _get_dataclass_field_type_sentinel(name):
|
| 1211 |
+
return _DATACLASSE_FIELD_TYPE_SENTINELS[name]
|
| 1212 |
+
|
| 1213 |
+
|
| 1214 |
+
class Pickler(pickle.Pickler):
|
| 1215 |
+
# set of reducers defined and used by cloudpickle (private)
|
| 1216 |
+
_dispatch_table = {}
|
| 1217 |
+
_dispatch_table[classmethod] = _classmethod_reduce
|
| 1218 |
+
_dispatch_table[io.TextIOWrapper] = _file_reduce
|
| 1219 |
+
_dispatch_table[logging.Logger] = _logger_reduce
|
| 1220 |
+
_dispatch_table[logging.RootLogger] = _root_logger_reduce
|
| 1221 |
+
_dispatch_table[memoryview] = _memoryview_reduce
|
| 1222 |
+
_dispatch_table[property] = _property_reduce
|
| 1223 |
+
_dispatch_table[staticmethod] = _classmethod_reduce
|
| 1224 |
+
_dispatch_table[CellType] = _cell_reduce
|
| 1225 |
+
_dispatch_table[types.CodeType] = _code_reduce
|
| 1226 |
+
_dispatch_table[types.GetSetDescriptorType] = _getset_descriptor_reduce
|
| 1227 |
+
_dispatch_table[types.ModuleType] = _module_reduce
|
| 1228 |
+
_dispatch_table[types.MethodType] = _method_reduce
|
| 1229 |
+
_dispatch_table[types.MappingProxyType] = _mappingproxy_reduce
|
| 1230 |
+
_dispatch_table[weakref.WeakSet] = _weakset_reduce
|
| 1231 |
+
_dispatch_table[typing.TypeVar] = _typevar_reduce
|
| 1232 |
+
_dispatch_table[_collections_abc.dict_keys] = _dict_keys_reduce
|
| 1233 |
+
_dispatch_table[_collections_abc.dict_values] = _dict_values_reduce
|
| 1234 |
+
_dispatch_table[_collections_abc.dict_items] = _dict_items_reduce
|
| 1235 |
+
_dispatch_table[type(OrderedDict().keys())] = _odict_keys_reduce
|
| 1236 |
+
_dispatch_table[type(OrderedDict().values())] = _odict_values_reduce
|
| 1237 |
+
_dispatch_table[type(OrderedDict().items())] = _odict_items_reduce
|
| 1238 |
+
_dispatch_table[abc.abstractmethod] = _classmethod_reduce
|
| 1239 |
+
_dispatch_table[abc.abstractclassmethod] = _classmethod_reduce
|
| 1240 |
+
_dispatch_table[abc.abstractstaticmethod] = _classmethod_reduce
|
| 1241 |
+
_dispatch_table[abc.abstractproperty] = _property_reduce
|
| 1242 |
+
_dispatch_table[dataclasses._FIELD_BASE] = _dataclass_field_base_reduce
|
| 1243 |
+
|
| 1244 |
+
dispatch_table = ChainMap(_dispatch_table, copyreg.dispatch_table)
|
| 1245 |
+
|
| 1246 |
+
# function reducers are defined as instance methods of cloudpickle.Pickler
|
| 1247 |
+
# objects, as they rely on a cloudpickle.Pickler attribute (globals_ref)
|
| 1248 |
+
def _dynamic_function_reduce(self, func):
|
| 1249 |
+
"""Reduce a function that is not pickleable via attribute lookup."""
|
| 1250 |
+
newargs = self._function_getnewargs(func)
|
| 1251 |
+
state = _function_getstate(func)
|
| 1252 |
+
return (_make_function, newargs, state, None, None, _function_setstate)
|
| 1253 |
+
|
| 1254 |
+
def _function_reduce(self, obj):
|
| 1255 |
+
"""Reducer for function objects.
|
| 1256 |
+
|
| 1257 |
+
If obj is a top-level attribute of a file-backed module, this reducer
|
| 1258 |
+
returns NotImplemented, making the cloudpickle.Pickler fall back to
|
| 1259 |
+
traditional pickle.Pickler routines to save obj. Otherwise, it reduces
|
| 1260 |
+
obj using a custom cloudpickle reducer designed specifically to handle
|
| 1261 |
+
dynamic functions.
|
| 1262 |
+
"""
|
| 1263 |
+
if _should_pickle_by_reference(obj):
|
| 1264 |
+
return NotImplemented
|
| 1265 |
+
else:
|
| 1266 |
+
return self._dynamic_function_reduce(obj)
|
| 1267 |
+
|
| 1268 |
+
def _function_getnewargs(self, func):
|
| 1269 |
+
code = func.__code__
|
| 1270 |
+
|
| 1271 |
+
# base_globals represents the future global namespace of func at
|
| 1272 |
+
# unpickling time. Looking it up and storing it in
|
| 1273 |
+
# cloudpickle.Pickler.globals_ref allow functions sharing the same
|
| 1274 |
+
# globals at pickling time to also share them once unpickled, at one
|
| 1275 |
+
# condition: since globals_ref is an attribute of a cloudpickle.Pickler
|
| 1276 |
+
# instance, and that a new cloudpickle.Pickler is created each time
|
| 1277 |
+
# cloudpickle.dump or cloudpickle.dumps is called, functions also need
|
| 1278 |
+
# to be saved within the same invocation of
|
| 1279 |
+
# cloudpickle.dump/cloudpickle.dumps (for example:
|
| 1280 |
+
# cloudpickle.dumps([f1, f2])). There is no such limitation when using
|
| 1281 |
+
# cloudpickle.Pickler.dump, as long as the multiple invocations are
|
| 1282 |
+
# bound to the same cloudpickle.Pickler instance.
|
| 1283 |
+
base_globals = self.globals_ref.setdefault(id(func.__globals__), {})
|
| 1284 |
+
|
| 1285 |
+
if base_globals == {}:
|
| 1286 |
+
# Add module attributes used to resolve relative imports
|
| 1287 |
+
# instructions inside func.
|
| 1288 |
+
for k in ["__package__", "__name__", "__path__", "__file__"]:
|
| 1289 |
+
if k in func.__globals__:
|
| 1290 |
+
base_globals[k] = func.__globals__[k]
|
| 1291 |
+
|
| 1292 |
+
# Do not bind the free variables before the function is created to
|
| 1293 |
+
# avoid infinite recursion.
|
| 1294 |
+
if func.__closure__ is None:
|
| 1295 |
+
closure = None
|
| 1296 |
+
else:
|
| 1297 |
+
closure = tuple(_make_empty_cell() for _ in range(len(code.co_freevars)))
|
| 1298 |
+
|
| 1299 |
+
return code, base_globals, None, None, closure
|
| 1300 |
+
|
| 1301 |
+
def dump(self, obj):
|
| 1302 |
+
try:
|
| 1303 |
+
return super().dump(obj)
|
| 1304 |
+
except RuntimeError as e:
|
| 1305 |
+
if len(e.args) > 0 and "recursion" in e.args[0]:
|
| 1306 |
+
msg = "Could not pickle object as excessively deep recursion required."
|
| 1307 |
+
raise pickle.PicklingError(msg) from e
|
| 1308 |
+
else:
|
| 1309 |
+
raise
|
| 1310 |
+
|
| 1311 |
+
def __init__(self, file, protocol=None, buffer_callback=None):
|
| 1312 |
+
if protocol is None:
|
| 1313 |
+
protocol = DEFAULT_PROTOCOL
|
| 1314 |
+
super().__init__(file, protocol=protocol, buffer_callback=buffer_callback)
|
| 1315 |
+
# map functions __globals__ attribute ids, to ensure that functions
|
| 1316 |
+
# sharing the same global namespace at pickling time also share
|
| 1317 |
+
# their global namespace at unpickling time.
|
| 1318 |
+
self.globals_ref = {}
|
| 1319 |
+
self.proto = int(protocol)
|
| 1320 |
+
|
| 1321 |
+
if not PYPY:
|
| 1322 |
+
# pickle.Pickler is the C implementation of the CPython pickler and
|
| 1323 |
+
# therefore we rely on reduce_override method to customize the pickler
|
| 1324 |
+
# behavior.
|
| 1325 |
+
|
| 1326 |
+
# `cloudpickle.Pickler.dispatch` is only left for backward
|
| 1327 |
+
# compatibility - note that when using protocol 5,
|
| 1328 |
+
# `cloudpickle.Pickler.dispatch` is not an extension of
|
| 1329 |
+
# `pickle._Pickler.dispatch` dictionary, because `cloudpickle.Pickler`
|
| 1330 |
+
# subclasses the C-implemented `pickle.Pickler`, which does not expose
|
| 1331 |
+
# a `dispatch` attribute. Earlier versions of `cloudpickle.Pickler`
|
| 1332 |
+
# used `cloudpickle.Pickler.dispatch` as a class-level attribute
|
| 1333 |
+
# storing all reducers implemented by cloudpickle, but the attribute
|
| 1334 |
+
# name was not a great choice given because it would collide with a
|
| 1335 |
+
# similarly named attribute in the pure-Python `pickle._Pickler`
|
| 1336 |
+
# implementation in the standard library.
|
| 1337 |
+
dispatch = dispatch_table
|
| 1338 |
+
|
| 1339 |
+
# Implementation of the reducer_override callback, in order to
|
| 1340 |
+
# efficiently serialize dynamic functions and classes by subclassing
|
| 1341 |
+
# the C-implemented `pickle.Pickler`.
|
| 1342 |
+
# TODO: decorrelate reducer_override (which is tied to CPython's
|
| 1343 |
+
# implementation - would it make sense to backport it to pypy? - and
|
| 1344 |
+
# pickle's protocol 5 which is implementation agnostic. Currently, the
|
| 1345 |
+
# availability of both notions coincide on CPython's pickle, but it may
|
| 1346 |
+
# not be the case anymore when pypy implements protocol 5.
|
| 1347 |
+
|
| 1348 |
+
def reducer_override(self, obj):
|
| 1349 |
+
"""Type-agnostic reducing callback for function and classes.
|
| 1350 |
+
|
| 1351 |
+
For performance reasons, subclasses of the C `pickle.Pickler` class
|
| 1352 |
+
cannot register custom reducers for functions and classes in the
|
| 1353 |
+
dispatch_table attribute. Reducers for such types must instead
|
| 1354 |
+
implemented via the special `reducer_override` method.
|
| 1355 |
+
|
| 1356 |
+
Note that this method will be called for any object except a few
|
| 1357 |
+
builtin-types (int, lists, dicts etc.), which differs from reducers
|
| 1358 |
+
in the Pickler's dispatch_table, each of them being invoked for
|
| 1359 |
+
objects of a specific type only.
|
| 1360 |
+
|
| 1361 |
+
This property comes in handy for classes: although most classes are
|
| 1362 |
+
instances of the ``type`` metaclass, some of them can be instances
|
| 1363 |
+
of other custom metaclasses (such as enum.EnumMeta for example). In
|
| 1364 |
+
particular, the metaclass will likely not be known in advance, and
|
| 1365 |
+
thus cannot be special-cased using an entry in the dispatch_table.
|
| 1366 |
+
reducer_override, among other things, allows us to register a
|
| 1367 |
+
reducer that will be called for any class, independently of its
|
| 1368 |
+
type.
|
| 1369 |
+
|
| 1370 |
+
Notes:
|
| 1371 |
+
|
| 1372 |
+
* reducer_override has the priority over dispatch_table-registered
|
| 1373 |
+
reducers.
|
| 1374 |
+
* reducer_override can be used to fix other limitations of
|
| 1375 |
+
cloudpickle for other types that suffered from type-specific
|
| 1376 |
+
reducers, such as Exceptions. See
|
| 1377 |
+
https://github.com/cloudpipe/cloudpickle/issues/248
|
| 1378 |
+
"""
|
| 1379 |
+
t = type(obj)
|
| 1380 |
+
try:
|
| 1381 |
+
is_anyclass = issubclass(t, type)
|
| 1382 |
+
except TypeError: # t is not a class (old Boost; see SF #502085)
|
| 1383 |
+
is_anyclass = False
|
| 1384 |
+
|
| 1385 |
+
if is_anyclass:
|
| 1386 |
+
return _class_reduce(obj)
|
| 1387 |
+
elif isinstance(obj, types.FunctionType):
|
| 1388 |
+
return self._function_reduce(obj)
|
| 1389 |
+
else:
|
| 1390 |
+
# fallback to save_global, including the Pickler's
|
| 1391 |
+
# dispatch_table
|
| 1392 |
+
return NotImplemented
|
| 1393 |
+
|
| 1394 |
+
else:
|
| 1395 |
+
# When reducer_override is not available, hack the pure-Python
|
| 1396 |
+
# Pickler's types.FunctionType and type savers. Note: the type saver
|
| 1397 |
+
# must override Pickler.save_global, because pickle.py contains a
|
| 1398 |
+
# hard-coded call to save_global when pickling meta-classes.
|
| 1399 |
+
dispatch = pickle.Pickler.dispatch.copy()
|
| 1400 |
+
|
| 1401 |
+
def _save_reduce_pickle5(
|
| 1402 |
+
self,
|
| 1403 |
+
func,
|
| 1404 |
+
args,
|
| 1405 |
+
state=None,
|
| 1406 |
+
listitems=None,
|
| 1407 |
+
dictitems=None,
|
| 1408 |
+
state_setter=None,
|
| 1409 |
+
obj=None,
|
| 1410 |
+
):
|
| 1411 |
+
save = self.save
|
| 1412 |
+
write = self.write
|
| 1413 |
+
self.save_reduce(
|
| 1414 |
+
func,
|
| 1415 |
+
args,
|
| 1416 |
+
state=None,
|
| 1417 |
+
listitems=listitems,
|
| 1418 |
+
dictitems=dictitems,
|
| 1419 |
+
obj=obj,
|
| 1420 |
+
)
|
| 1421 |
+
# backport of the Python 3.8 state_setter pickle operations
|
| 1422 |
+
save(state_setter)
|
| 1423 |
+
save(obj) # simple BINGET opcode as obj is already memoized.
|
| 1424 |
+
save(state)
|
| 1425 |
+
write(pickle.TUPLE2)
|
| 1426 |
+
# Trigger a state_setter(obj, state) function call.
|
| 1427 |
+
write(pickle.REDUCE)
|
| 1428 |
+
# The purpose of state_setter is to carry-out an
|
| 1429 |
+
# inplace modification of obj. We do not care about what the
|
| 1430 |
+
# method might return, so its output is eventually removed from
|
| 1431 |
+
# the stack.
|
| 1432 |
+
write(pickle.POP)
|
| 1433 |
+
|
| 1434 |
+
def save_global(self, obj, name=None, pack=struct.pack):
|
| 1435 |
+
"""Main dispatch method.
|
| 1436 |
+
|
| 1437 |
+
The name of this method is somewhat misleading: all types get
|
| 1438 |
+
dispatched here.
|
| 1439 |
+
"""
|
| 1440 |
+
if obj is type(None): # noqa
|
| 1441 |
+
return self.save_reduce(type, (None,), obj=obj)
|
| 1442 |
+
elif obj is type(Ellipsis):
|
| 1443 |
+
return self.save_reduce(type, (Ellipsis,), obj=obj)
|
| 1444 |
+
elif obj is type(NotImplemented):
|
| 1445 |
+
return self.save_reduce(type, (NotImplemented,), obj=obj)
|
| 1446 |
+
elif obj in _BUILTIN_TYPE_NAMES:
|
| 1447 |
+
return self.save_reduce(
|
| 1448 |
+
_builtin_type, (_BUILTIN_TYPE_NAMES[obj],), obj=obj
|
| 1449 |
+
)
|
| 1450 |
+
|
| 1451 |
+
if name is not None:
|
| 1452 |
+
super().save_global(obj, name=name)
|
| 1453 |
+
elif not _should_pickle_by_reference(obj, name=name):
|
| 1454 |
+
self._save_reduce_pickle5(*_dynamic_class_reduce(obj), obj=obj)
|
| 1455 |
+
else:
|
| 1456 |
+
super().save_global(obj, name=name)
|
| 1457 |
+
|
| 1458 |
+
dispatch[type] = save_global
|
| 1459 |
+
|
| 1460 |
+
def save_function(self, obj, name=None):
|
| 1461 |
+
"""Registered with the dispatch to handle all function types.
|
| 1462 |
+
|
| 1463 |
+
Determines what kind of function obj is (e.g. lambda, defined at
|
| 1464 |
+
interactive prompt, etc) and handles the pickling appropriately.
|
| 1465 |
+
"""
|
| 1466 |
+
if _should_pickle_by_reference(obj, name=name):
|
| 1467 |
+
return super().save_global(obj, name=name)
|
| 1468 |
+
elif PYPY and isinstance(obj.__code__, builtin_code_type):
|
| 1469 |
+
return self.save_pypy_builtin_func(obj)
|
| 1470 |
+
else:
|
| 1471 |
+
return self._save_reduce_pickle5(
|
| 1472 |
+
*self._dynamic_function_reduce(obj), obj=obj
|
| 1473 |
+
)
|
| 1474 |
+
|
| 1475 |
+
def save_pypy_builtin_func(self, obj):
|
| 1476 |
+
"""Save pypy equivalent of builtin functions.
|
| 1477 |
+
|
| 1478 |
+
PyPy does not have the concept of builtin-functions. Instead,
|
| 1479 |
+
builtin-functions are simple function instances, but with a
|
| 1480 |
+
builtin-code attribute.
|
| 1481 |
+
Most of the time, builtin functions should be pickled by attribute.
|
| 1482 |
+
But PyPy has flaky support for __qualname__, so some builtin
|
| 1483 |
+
functions such as float.__new__ will be classified as dynamic. For
|
| 1484 |
+
this reason only, we created this special routine. Because
|
| 1485 |
+
builtin-functions are not expected to have closure or globals,
|
| 1486 |
+
there is no additional hack (compared the one already implemented
|
| 1487 |
+
in pickle) to protect ourselves from reference cycles. A simple
|
| 1488 |
+
(reconstructor, newargs, obj.__dict__) tuple is save_reduced. Note
|
| 1489 |
+
also that PyPy improved their support for __qualname__ in v3.6, so
|
| 1490 |
+
this routing should be removed when cloudpickle supports only PyPy
|
| 1491 |
+
3.6 and later.
|
| 1492 |
+
"""
|
| 1493 |
+
rv = (
|
| 1494 |
+
types.FunctionType,
|
| 1495 |
+
(obj.__code__, {}, obj.__name__, obj.__defaults__, obj.__closure__),
|
| 1496 |
+
obj.__dict__,
|
| 1497 |
+
)
|
| 1498 |
+
self.save_reduce(*rv, obj=obj)
|
| 1499 |
+
|
| 1500 |
+
dispatch[types.FunctionType] = save_function
|
| 1501 |
+
|
| 1502 |
+
|
| 1503 |
+
# Shorthands similar to pickle.dump/pickle.dumps
|
| 1504 |
+
|
| 1505 |
+
|
| 1506 |
+
def dump(obj, file, protocol=None, buffer_callback=None):
|
| 1507 |
+
"""Serialize obj as bytes streamed into file
|
| 1508 |
+
|
| 1509 |
+
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
|
| 1510 |
+
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
|
| 1511 |
+
speed between processes running the same Python version.
|
| 1512 |
+
|
| 1513 |
+
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
|
| 1514 |
+
compatibility with older versions of Python (although this is not always
|
| 1515 |
+
guaranteed to work because cloudpickle relies on some internal
|
| 1516 |
+
implementation details that can change from one Python version to the
|
| 1517 |
+
next).
|
| 1518 |
+
"""
|
| 1519 |
+
Pickler(file, protocol=protocol, buffer_callback=buffer_callback).dump(obj)
|
| 1520 |
+
|
| 1521 |
+
|
| 1522 |
+
def dumps(obj, protocol=None, buffer_callback=None):
|
| 1523 |
+
"""Serialize obj as a string of bytes allocated in memory
|
| 1524 |
+
|
| 1525 |
+
protocol defaults to cloudpickle.DEFAULT_PROTOCOL which is an alias to
|
| 1526 |
+
pickle.HIGHEST_PROTOCOL. This setting favors maximum communication
|
| 1527 |
+
speed between processes running the same Python version.
|
| 1528 |
+
|
| 1529 |
+
Set protocol=pickle.DEFAULT_PROTOCOL instead if you need to ensure
|
| 1530 |
+
compatibility with older versions of Python (although this is not always
|
| 1531 |
+
guaranteed to work because cloudpickle relies on some internal
|
| 1532 |
+
implementation details that can change from one Python version to the
|
| 1533 |
+
next).
|
| 1534 |
+
"""
|
| 1535 |
+
with io.BytesIO() as file:
|
| 1536 |
+
cp = Pickler(file, protocol=protocol, buffer_callback=buffer_callback)
|
| 1537 |
+
cp.dump(obj)
|
| 1538 |
+
return file.getvalue()
|
| 1539 |
+
|
| 1540 |
+
|
| 1541 |
+
# Include pickles unloading functions in this namespace for convenience.
|
| 1542 |
+
load, loads = pickle.load, pickle.loads
|
| 1543 |
+
|
| 1544 |
+
# Backward compat alias.
|
| 1545 |
+
CloudPickler = Pickler
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/cloudpickle/cloudpickle_fast.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compatibility module.
|
| 2 |
+
|
| 3 |
+
It can be necessary to load files generated by previous versions of cloudpickle
|
| 4 |
+
that rely on symbols being defined under the `cloudpickle.cloudpickle_fast`
|
| 5 |
+
namespace.
|
| 6 |
+
|
| 7 |
+
See: tests/test_backward_compat.py
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from . import cloudpickle
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def __getattr__(name):
|
| 14 |
+
return getattr(cloudpickle, name)
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__init__.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
r"""The :mod:`loky` module manages a pool of worker that can be re-used across time.
|
| 2 |
+
It provides a robust and dynamic implementation os the
|
| 3 |
+
:class:`ProcessPoolExecutor` and a function :func:`get_reusable_executor` which
|
| 4 |
+
hide the pool management under the hood.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from concurrent.futures import (
|
| 8 |
+
ALL_COMPLETED,
|
| 9 |
+
FIRST_COMPLETED,
|
| 10 |
+
FIRST_EXCEPTION,
|
| 11 |
+
CancelledError,
|
| 12 |
+
Executor,
|
| 13 |
+
TimeoutError,
|
| 14 |
+
as_completed,
|
| 15 |
+
wait,
|
| 16 |
+
)
|
| 17 |
+
|
| 18 |
+
from ._base import Future
|
| 19 |
+
from .backend.context import cpu_count
|
| 20 |
+
from .backend.reduction import set_loky_pickler
|
| 21 |
+
from .reusable_executor import get_reusable_executor
|
| 22 |
+
from .cloudpickle_wrapper import wrap_non_picklable_objects
|
| 23 |
+
from .process_executor import BrokenProcessPool, ProcessPoolExecutor
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
__all__ = [
|
| 27 |
+
"get_reusable_executor",
|
| 28 |
+
"cpu_count",
|
| 29 |
+
"wait",
|
| 30 |
+
"as_completed",
|
| 31 |
+
"Future",
|
| 32 |
+
"Executor",
|
| 33 |
+
"ProcessPoolExecutor",
|
| 34 |
+
"BrokenProcessPool",
|
| 35 |
+
"CancelledError",
|
| 36 |
+
"TimeoutError",
|
| 37 |
+
"FIRST_COMPLETED",
|
| 38 |
+
"FIRST_EXCEPTION",
|
| 39 |
+
"ALL_COMPLETED",
|
| 40 |
+
"wrap_non_picklable_objects",
|
| 41 |
+
"set_loky_pickler",
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
__version__ = "3.5.5"
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (1.21 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/_base.cpython-310.pyc
ADDED
|
Binary file (787 Bytes). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/cloudpickle_wrapper.cpython-310.pyc
ADDED
|
Binary file (3.74 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/initializers.cpython-310.pyc
ADDED
|
Binary file (2.42 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/process_executor.cpython-310.pyc
ADDED
|
Binary file (33.8 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/__pycache__/reusable_executor.cpython-310.pyc
ADDED
|
Binary file (7.66 kB). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/_base.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###############################################################################
|
| 2 |
+
# Modification of concurrent.futures.Future
|
| 3 |
+
#
|
| 4 |
+
# author: Thomas Moreau and Olivier Grisel
|
| 5 |
+
#
|
| 6 |
+
# adapted from concurrent/futures/_base.py (17/02/2017)
|
| 7 |
+
# * Do not use yield from
|
| 8 |
+
# * Use old super syntax
|
| 9 |
+
#
|
| 10 |
+
# Copyright 2009 Brian Quinlan. All Rights Reserved.
|
| 11 |
+
# Licensed to PSF under a Contributor Agreement.
|
| 12 |
+
|
| 13 |
+
from concurrent.futures import Future as _BaseFuture
|
| 14 |
+
from concurrent.futures._base import LOGGER
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
# To make loky._base.Future instances awaitable by concurrent.futures.wait,
|
| 18 |
+
# derive our custom Future class from _BaseFuture. _invoke_callback is the only
|
| 19 |
+
# modification made to this class in loky.
|
| 20 |
+
# TODO investigate why using `concurrent.futures.Future` directly does not
|
| 21 |
+
# always work in our test suite.
|
| 22 |
+
class Future(_BaseFuture):
|
| 23 |
+
def _invoke_callbacks(self):
|
| 24 |
+
for callback in self._done_callbacks:
|
| 25 |
+
try:
|
| 26 |
+
callback(self)
|
| 27 |
+
except BaseException:
|
| 28 |
+
LOGGER.exception(f"exception calling callback for {self!r}")
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/backend/__init__.py
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from multiprocessing import synchronize
|
| 3 |
+
|
| 4 |
+
from .context import get_context
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def _make_name():
|
| 8 |
+
return f"/loky-{os.getpid()}-{next(synchronize.SemLock._rand)}"
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
# monkey patch the name creation for multiprocessing
|
| 12 |
+
synchronize.SemLock._make_name = staticmethod(_make_name)
|
| 13 |
+
|
| 14 |
+
__all__ = ["get_context"]
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/backend/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (585 Bytes). View file
|
|
|
Scripts_RSCM_sim_growth_n_climate_to_Yield/.venv/lib/python3.10/site-packages/joblib/externals/loky/backend/__pycache__/_posix_reduction.cpython-310.pyc
ADDED
|
Binary file (1.86 kB). View file
|
|
|