QPromaQ commited on
Commit
189f0df
·
verified ·
1 Parent(s): 5c48d7a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .venv_haddock/lib/python3.12/site-packages/Bio/File.py +626 -0
  2. .venv_haddock/lib/python3.12/site-packages/Bio/Seq.py +0 -0
  3. .venv_haddock/lib/python3.12/site-packages/Bio/SeqFeature.py +2332 -0
  4. .venv_haddock/lib/python3.12/site-packages/Bio/SeqRecord.py +1541 -0
  5. .venv_haddock/lib/python3.12/site-packages/Bio/__init__.py +147 -0
  6. .venv_haddock/lib/python3.12/site-packages/Bio/_utils.py +92 -0
  7. .venv_haddock/lib/python3.12/site-packages/Bio/bgzf.py +960 -0
  8. .venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2.cpython-312-darwin.so +0 -0
  9. .venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2module.c +479 -0
  10. .venv_haddock/lib/python3.12/site-packages/Bio/pairwise2.py +1441 -0
  11. .venv_haddock/lib/python3.12/site-packages/Bio/py.typed +0 -0
  12. .venv_haddock/lib/python3.12/site-packages/__pycache__/six.cpython-312.pyc +0 -0
  13. .venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/INSTALLER +1 -0
  14. .venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/METADATA +205 -0
  15. .venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/RECORD +571 -0
  16. .venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/REQUESTED +0 -0
  17. .venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/WHEEL +5 -0
  18. .venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/entry_points.txt +15 -0
  19. .venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/top_level.txt +1 -0
  20. .venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/INSTALLER +1 -0
  21. .venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/METADATA +232 -0
  22. .venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/RECORD +38 -0
  23. .venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/WHEEL +5 -0
  24. .venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/top_level.txt +1 -0
  25. .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/INSTALLER +1 -0
  26. .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/METADATA +349 -0
  27. .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/RECORD +330 -0
  28. .venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/WHEEL +4 -0
  29. .venv_haddock/lib/python3.12/site-packages/numpy/__init__.cython-30.pxd +1242 -0
  30. .venv_haddock/lib/python3.12/site-packages/numpy/__init__.pxd +1155 -0
  31. .venv_haddock/lib/python3.12/site-packages/numpy/__init__.py +942 -0
  32. .venv_haddock/lib/python3.12/site-packages/numpy/__init__.pyi +0 -0
  33. .venv_haddock/lib/python3.12/site-packages/numpy/_array_api_info.py +346 -0
  34. .venv_haddock/lib/python3.12/site-packages/numpy/_array_api_info.pyi +206 -0
  35. .venv_haddock/lib/python3.12/site-packages/numpy/_configtool.py +39 -0
  36. .venv_haddock/lib/python3.12/site-packages/numpy/_distributor_init.pyi +1 -0
  37. .venv_haddock/lib/python3.12/site-packages/numpy/_globals.py +121 -0
  38. .venv_haddock/lib/python3.12/site-packages/numpy/_globals.pyi +17 -0
  39. .venv_haddock/lib/python3.12/site-packages/numpy/_pytesttester.pyi +18 -0
  40. .venv_haddock/lib/python3.12/site-packages/numpy/conftest.py +248 -0
  41. .venv_haddock/lib/python3.12/site-packages/numpy/dtypes.py +41 -0
  42. .venv_haddock/lib/python3.12/site-packages/numpy/dtypes.pyi +630 -0
  43. .venv_haddock/lib/python3.12/site-packages/numpy/exceptions.pyi +27 -0
  44. .venv_haddock/lib/python3.12/site-packages/numpy/matlib.pyi +582 -0
  45. .venv_haddock/lib/python3.12/site-packages/numpy/version.py +11 -0
  46. .venv_haddock/lib/python3.12/site-packages/numpy/version.pyi +9 -0
  47. .venv_haddock/lib/python3.12/site-packages/packaging/__init__.py +15 -0
  48. .venv_haddock/lib/python3.12/site-packages/packaging/_elffile.py +108 -0
  49. .venv_haddock/lib/python3.12/site-packages/packaging/_manylinux.py +262 -0
  50. .venv_haddock/lib/python3.12/site-packages/packaging/_parser.py +365 -0
.venv_haddock/lib/python3.12/site-packages/Bio/File.py ADDED
@@ -0,0 +1,626 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 1999 by Jeffrey Chang. All rights reserved.
2
+ # Copyright 2009-2018 by Peter Cock. All rights reserved.
3
+ #
4
+ # This file is part of the Biopython distribution and governed by your
5
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
6
+ # Please see the LICENSE file that should have been included as part of this
7
+ # package.
8
+ """Code for more fancy file handles.
9
+
10
+ Bio.File defines private classes used in Bio.SeqIO and Bio.SearchIO for
11
+ indexing files. These are not intended for direct use.
12
+ """
13
+
14
+ import collections.abc
15
+ import contextlib
16
+ import itertools
17
+ import os
18
+ from abc import ABC
19
+ from abc import abstractmethod
20
+
21
+ try:
22
+ import sqlite3
23
+ except ImportError:
24
+ # May be missing if Python was compiled from source without its dependencies
25
+ sqlite3 = None # type: ignore
26
+
27
+
28
+ @contextlib.contextmanager
29
+ def as_handle(handleish, mode="r", **kwargs):
30
+ r"""Context manager to ensure we are using a handle.
31
+
32
+ Context manager for arguments that can be passed to SeqIO and AlignIO read, write,
33
+ and parse methods: either file objects or path-like objects (strings, pathlib.Path
34
+ instances, or more generally, anything that can be handled by the builtin 'open'
35
+ function).
36
+
37
+ When given a path-like object, returns an open file handle to that path, with provided
38
+ mode, which will be closed when the manager exits.
39
+
40
+ All other inputs are returned, and are *not* closed.
41
+
42
+ Arguments:
43
+ - handleish - Either a file handle or path-like object (anything which can be
44
+ passed to the builtin 'open' function, such as str, bytes,
45
+ pathlib.Path, and os.DirEntry objects)
46
+ - mode - Mode to open handleish (used only if handleish is a string)
47
+ - kwargs - Further arguments to pass to open(...)
48
+
49
+ Examples
50
+ --------
51
+ >>> from Bio import File
52
+ >>> import os
53
+ >>> with File.as_handle('seqs.fasta', 'w') as fp:
54
+ ... fp.write('>test\nACGT')
55
+ ...
56
+ 10
57
+ >>> fp.closed
58
+ True
59
+
60
+ >>> handle = open('seqs.fasta', 'w')
61
+ >>> with File.as_handle(handle) as fp:
62
+ ... fp.write('>test\nACGT')
63
+ ...
64
+ 10
65
+ >>> fp.closed
66
+ False
67
+ >>> fp.close()
68
+ >>> os.remove("seqs.fasta") # tidy up
69
+
70
+ """
71
+ try:
72
+ with open(handleish, mode, **kwargs) as fp:
73
+ yield fp
74
+ except TypeError:
75
+ yield handleish
76
+
77
+
78
+ def _open_for_random_access(filename):
79
+ """Open a file in binary mode, spot if it is BGZF format etc (PRIVATE).
80
+
81
+ This functionality is used by the Bio.SeqIO and Bio.SearchIO index
82
+ and index_db functions.
83
+
84
+ If the file is gzipped but not BGZF, a specific ValueError is raised.
85
+ """
86
+ handle = open(filename, "rb")
87
+ magic = handle.read(2)
88
+ handle.seek(0)
89
+
90
+ if magic == b"\x1f\x8b":
91
+ # This is a gzipped file, but is it BGZF?
92
+ from . import bgzf
93
+
94
+ try:
95
+ # If it is BGZF, we support that
96
+ return bgzf.BgzfReader(mode="rb", fileobj=handle)
97
+ except ValueError as e:
98
+ assert "BGZF" in str(e)
99
+ # Not a BGZF file after all,
100
+ handle.close()
101
+ raise ValueError(
102
+ "Gzipped files are not suitable for indexing, "
103
+ "please use BGZF (blocked gzip format) instead."
104
+ ) from None
105
+
106
+ return handle
107
+
108
+
109
+ # The rest of this file defines code used in Bio.SeqIO and Bio.SearchIO
110
+ # for indexing
111
+
112
+
113
+ class _IndexedSeqFileProxy(ABC):
114
+ """Abstract base class for file format specific random access (PRIVATE).
115
+
116
+ This is subclasses in both Bio.SeqIO for indexing as SeqRecord
117
+ objects, and in Bio.SearchIO for indexing QueryResult objects.
118
+
119
+ Subclasses for each file format should define '__iter__', 'get'
120
+ and optionally 'get_raw' methods.
121
+ """
122
+
123
+ @abstractmethod
124
+ def __iter__(self):
125
+ """Return (identifier, offset, length in bytes) tuples.
126
+
127
+ The length can be zero where it is not implemented or not
128
+ possible for a particular file format.
129
+ """
130
+ raise NotImplementedError
131
+
132
+ @abstractmethod
133
+ def get(self, offset):
134
+ """Return parsed object for this entry."""
135
+ # Most file formats with self contained records can be handled by
136
+ # parsing StringIO(self.get_raw(offset).decode())
137
+ raise NotImplementedError
138
+
139
+ def get_raw(self, offset):
140
+ """Return the raw record from the file as a bytes string (if implemented).
141
+
142
+ If the key is not found, a KeyError exception is raised.
143
+
144
+ This may not have been implemented for all file formats.
145
+ """
146
+ # Should be done by each sub-class (if possible)
147
+ raise NotImplementedError("Not available for this file format.")
148
+
149
+
150
+ class _IndexedSeqFileDict(collections.abc.Mapping):
151
+ """Read only dictionary interface to a sequential record file.
152
+
153
+ This code is used in both Bio.SeqIO for indexing as SeqRecord
154
+ objects, and in Bio.SearchIO for indexing QueryResult objects.
155
+
156
+ Keeps the keys and associated file offsets in memory, reads the file
157
+ to access entries as objects parsing them on demand. This approach
158
+ is memory limited, but will work even with millions of records.
159
+
160
+ Note duplicate keys are not allowed. If this happens, a ValueError
161
+ exception is raised.
162
+
163
+ As used in Bio.SeqIO, by default the SeqRecord's id string is used
164
+ as the dictionary key. In Bio.SearchIO, the query's id string is
165
+ used. This can be changed by supplying an optional key_function,
166
+ a callback function which will be given the record id and must
167
+ return the desired key. For example, this allows you to parse
168
+ NCBI style FASTA identifiers, and extract the GI number to use
169
+ as the dictionary key.
170
+
171
+ Note that this dictionary is essentially read only. You cannot
172
+ add or change values, pop values, nor clear the dictionary.
173
+ """
174
+
175
+ def __init__(self, random_access_proxy, key_function, repr, obj_repr):
176
+ """Initialize the class."""
177
+ # Use key_function=None for default value
178
+ self._proxy = random_access_proxy
179
+ self._key_function = key_function
180
+ self._repr = repr
181
+ self._obj_repr = obj_repr
182
+ self._cached_prev_record = (None, None) # (key, record)
183
+ if key_function:
184
+ offset_iter = (
185
+ (key_function(key), offset, length)
186
+ for (key, offset, length) in random_access_proxy
187
+ )
188
+ else:
189
+ offset_iter = random_access_proxy
190
+ offsets = {}
191
+ for key, offset, length in offset_iter:
192
+ # Note - we don't store the length because I want to minimise the
193
+ # memory requirements. With the SQLite backend the length is kept
194
+ # and is used to speed up the get_raw method (by about 3 times).
195
+ # The length should be provided by all the current backends except
196
+ # SFF where there is an existing Roche index we can reuse (very fast
197
+ # but lacks the record lengths)
198
+ # assert length or format in ["sff", "sff-trim"], \
199
+ # "%s at offset %i given length %r (%s format %s)" \
200
+ # % (key, offset, length, filename, format)
201
+ if key in offsets:
202
+ self._proxy._handle.close()
203
+ raise ValueError(f"Duplicate key '{key}'")
204
+ else:
205
+ offsets[key] = offset
206
+ self._offsets = offsets
207
+
208
+ def __repr__(self):
209
+ """Return a string representation of the File object."""
210
+ return self._repr
211
+
212
+ def __str__(self):
213
+ """Create a string representation of the File object."""
214
+ # TODO - How best to handle the __str__ for SeqIO and SearchIO?
215
+ if self:
216
+ return f"{{{list(self.keys())[0]!r} : {self._obj_repr}(...), ...}}"
217
+ else:
218
+ return "{}"
219
+
220
+ def __len__(self):
221
+ """Return the number of records."""
222
+ return len(self._offsets)
223
+
224
+ def __iter__(self):
225
+ """Iterate over the keys."""
226
+ return iter(self._offsets)
227
+
228
+ def __getitem__(self, key):
229
+ """Return record for the specified key.
230
+
231
+ As an optimization when repeatedly asked to look up the same record,
232
+ the key and record are cached so that if the *same* record is
233
+ requested next time, it can be returned without going to disk.
234
+ """
235
+ if key == self._cached_prev_record[0]:
236
+ return self._cached_prev_record[1]
237
+ # Pass the offset to the proxy
238
+ record = self._proxy.get(self._offsets[key])
239
+ if self._key_function:
240
+ key2 = self._key_function(record.id)
241
+ else:
242
+ key2 = record.id
243
+ if key != key2:
244
+ raise ValueError(f"Key did not match ({key} vs {key2})")
245
+ self._cached_prev_record = (key, record)
246
+ return record
247
+
248
+ def get_raw(self, key):
249
+ """Return the raw record from the file as a bytes string.
250
+
251
+ If the key is not found, a KeyError exception is raised.
252
+ """
253
+ # Pass the offset to the proxy
254
+ return self._proxy.get_raw(self._offsets[key])
255
+
256
+ def close(self):
257
+ """Close the file handle being used to read the data.
258
+
259
+ Once called, further use of the index won't work. The sole purpose
260
+ of this method is to allow explicit handle closure - for example
261
+ if you wish to delete the file, on Windows you must first close
262
+ all open handles to that file.
263
+ """
264
+ self._proxy._handle.close()
265
+
266
+
267
+ class _SQLiteManySeqFilesDict(_IndexedSeqFileDict):
268
+ """Read only dictionary interface to many sequential record files.
269
+
270
+ This code is used in both Bio.SeqIO for indexing as SeqRecord
271
+ objects, and in Bio.SearchIO for indexing QueryResult objects.
272
+
273
+ Keeps the keys, file-numbers and offsets in an SQLite database. To access
274
+ a record by key, reads from the offset in the appropriate file and then
275
+ parses the record into an object.
276
+
277
+ There are OS limits on the number of files that can be open at once,
278
+ so a pool are kept. If a record is required from a closed file, then
279
+ one of the open handles is closed first.
280
+ """
281
+
282
+ def __init__(
283
+ self,
284
+ index_filename,
285
+ filenames,
286
+ proxy_factory,
287
+ fmt,
288
+ key_function,
289
+ repr,
290
+ max_open=10,
291
+ ):
292
+ """Initialize the class."""
293
+ # TODO? - Don't keep filename list in memory (just in DB)?
294
+ # Should save a chunk of memory if dealing with 1000s of files.
295
+ # Furthermore could compare a generator to the DB on reloading
296
+ # (no need to turn it into a list)
297
+
298
+ if sqlite3 is None:
299
+ # Python was compiled without sqlite3 support
300
+ from Bio import MissingPythonDependencyError
301
+
302
+ raise MissingPythonDependencyError(
303
+ "Python was compiled without the sqlite3 module"
304
+ )
305
+ if filenames is not None:
306
+ filenames = list(filenames) # In case it was a generator
307
+
308
+ # Cache the arguments as private variables
309
+ self._index_filename = index_filename
310
+ self._filenames = filenames
311
+ self._format = fmt
312
+ self._key_function = key_function
313
+ self._proxy_factory = proxy_factory
314
+ self._repr = repr
315
+ self._max_open = max_open
316
+ self._proxies = {}
317
+
318
+ # Note if using SQLite :memory: trick index filename, this will
319
+ # give $PWD as the relative path (which is fine).
320
+ self._relative_path = os.path.abspath(os.path.dirname(index_filename))
321
+
322
+ if os.path.isfile(index_filename):
323
+ self._load_index()
324
+ else:
325
+ self._build_index()
326
+
327
+ def _load_index(self):
328
+ """Call from __init__ to reuse an existing index (PRIVATE)."""
329
+ index_filename = self._index_filename
330
+ relative_path = self._relative_path
331
+ filenames = self._filenames
332
+ fmt = self._format
333
+ proxy_factory = self._proxy_factory
334
+
335
+ con = sqlite3.dbapi2.connect(index_filename, check_same_thread=False)
336
+ self._con = con
337
+ # Check the count...
338
+ try:
339
+ (count,) = con.execute(
340
+ "SELECT value FROM meta_data WHERE key=?;", ("count",)
341
+ ).fetchone()
342
+ self._length = int(count)
343
+ if self._length == -1:
344
+ con.close()
345
+ raise ValueError("Unfinished/partial database") from None
346
+
347
+ # use MAX(_ROWID_) to obtain the number of sequences in the database
348
+ # using COUNT(key) is quite slow in SQLITE
349
+ # (https://stackoverflow.com/questions/8988915/sqlite-count-slow-on-big-tables)
350
+ (count,) = con.execute("SELECT MAX(_ROWID_) FROM offset_data;").fetchone()
351
+ if self._length != int(count):
352
+ con.close()
353
+ raise ValueError(
354
+ "Corrupt database? %i entries not %i" % (int(count), self._length)
355
+ ) from None
356
+ (self._format,) = con.execute(
357
+ "SELECT value FROM meta_data WHERE key=?;", ("format",)
358
+ ).fetchone()
359
+ if fmt and fmt != self._format:
360
+ con.close()
361
+ raise ValueError(
362
+ f"Index file says format {self._format}, not {fmt}"
363
+ ) from None
364
+ try:
365
+ (filenames_relative_to_index,) = con.execute(
366
+ "SELECT value FROM meta_data WHERE key=?;",
367
+ ("filenames_relative_to_index",),
368
+ ).fetchone()
369
+ filenames_relative_to_index = (
370
+ filenames_relative_to_index.upper() == "TRUE"
371
+ )
372
+ except TypeError:
373
+ # Original behaviour, assume if meta_data missing
374
+ filenames_relative_to_index = False
375
+ self._filenames = [
376
+ row[0]
377
+ for row in con.execute(
378
+ "SELECT name FROM file_data ORDER BY file_number;"
379
+ ).fetchall()
380
+ ]
381
+ if filenames_relative_to_index:
382
+ # Not implicitly relative to $PWD, explicitly relative to index file
383
+ relative_path = os.path.abspath(os.path.dirname(index_filename))
384
+ tmp = []
385
+ for f in self._filenames:
386
+ if os.path.isabs(f):
387
+ tmp.append(f)
388
+ else:
389
+ # Would be stored with Unix / path separator, so convert
390
+ # it to the local OS path separator here:
391
+ tmp.append(
392
+ os.path.join(relative_path, f.replace("/", os.path.sep))
393
+ )
394
+ self._filenames = tmp
395
+ del tmp
396
+ if filenames and len(filenames) != len(self._filenames):
397
+ con.close()
398
+ raise ValueError(
399
+ "Index file says %i files, not %i"
400
+ % (len(self._filenames), len(filenames))
401
+ ) from None
402
+ if filenames and filenames != self._filenames:
403
+ for old, new in zip(self._filenames, filenames):
404
+ # Want exact match (after making relative to the index above)
405
+ if os.path.abspath(old) != os.path.abspath(new):
406
+ con.close()
407
+ if filenames_relative_to_index:
408
+ raise ValueError(
409
+ "Index file has different filenames, e.g. %r != %r"
410
+ % (os.path.abspath(old), os.path.abspath(new))
411
+ ) from None
412
+ else:
413
+ raise ValueError(
414
+ "Index file has different filenames "
415
+ "[This is an old index where any relative paths "
416
+ "were relative to the original working directory]. "
417
+ "e.g. %r != %r"
418
+ % (os.path.abspath(old), os.path.abspath(new))
419
+ ) from None
420
+ # Filenames are equal (after imposing abspath)
421
+ except sqlite3.OperationalError as err:
422
+ con.close()
423
+ raise ValueError(f"Not a Biopython index database? {err}") from None
424
+ # Now we have the format (from the DB if not given to us),
425
+ if not proxy_factory(self._format):
426
+ con.close()
427
+ raise ValueError(f"Unsupported format '{self._format}'")
428
+
429
+ def _build_index(self):
430
+ """Call from __init__ to create a new index (PRIVATE)."""
431
+ index_filename = self._index_filename
432
+ relative_path = self._relative_path
433
+ filenames = self._filenames
434
+ fmt = self._format
435
+ key_function = self._key_function
436
+ proxy_factory = self._proxy_factory
437
+ max_open = self._max_open
438
+ random_access_proxies = self._proxies
439
+
440
+ if not fmt or not filenames:
441
+ raise ValueError(
442
+ f"Filenames to index and format required to build {index_filename!r}"
443
+ )
444
+ if not proxy_factory(fmt):
445
+ raise ValueError(f"Unsupported format '{fmt}'")
446
+ # Create the index
447
+ con = sqlite3.dbapi2.connect(index_filename)
448
+ self._con = con
449
+ # print("Creating index")
450
+ # Sqlite PRAGMA settings for speed
451
+ con.execute("PRAGMA synchronous=OFF")
452
+ con.execute("PRAGMA locking_mode=EXCLUSIVE")
453
+ # Don't index the key column until the end (faster)
454
+ # con.execute("CREATE TABLE offset_data (key TEXT PRIMARY KEY, "
455
+ # "offset INTEGER);")
456
+ con.execute("CREATE TABLE meta_data (key TEXT, value TEXT);")
457
+ con.execute("INSERT INTO meta_data (key, value) VALUES (?,?);", ("count", -1))
458
+ con.execute("INSERT INTO meta_data (key, value) VALUES (?,?);", ("format", fmt))
459
+ con.execute(
460
+ "INSERT INTO meta_data (key, value) VALUES (?,?);",
461
+ ("filenames_relative_to_index", "True"),
462
+ )
463
+ # TODO - Record the file size and modified date?
464
+ con.execute("CREATE TABLE file_data (file_number INTEGER, name TEXT);")
465
+ con.execute(
466
+ "CREATE TABLE offset_data (key TEXT, "
467
+ "file_number INTEGER, offset INTEGER, length INTEGER);"
468
+ )
469
+ count = 0
470
+ for file_index, filename in enumerate(filenames):
471
+ # Default to storing as an absolute path,
472
+ f = os.path.abspath(filename)
473
+ if not os.path.isabs(filename) and not os.path.isabs(index_filename):
474
+ # Since user gave BOTH filename & index as relative paths,
475
+ # we will store this relative to the index file even though
476
+ # if it may now start ../ (meaning up a level)
477
+ # Note for cross platform use (e.g. shared drive over SAMBA),
478
+ # convert any Windows slash into Unix style for rel paths.
479
+ f = os.path.relpath(filename, relative_path).replace(os.path.sep, "/")
480
+ elif (os.path.dirname(os.path.abspath(filename)) + os.path.sep).startswith(
481
+ relative_path + os.path.sep
482
+ ):
483
+ # Since sequence file is in same directory or sub directory,
484
+ # might as well make this into a relative path:
485
+ f = os.path.relpath(filename, relative_path).replace(os.path.sep, "/")
486
+ assert not f.startswith("../"), f
487
+ # print("DEBUG - storing %r as [%r] %r" % (filename, relative_path, f))
488
+ con.execute(
489
+ "INSERT INTO file_data (file_number, name) VALUES (?,?);",
490
+ (file_index, f),
491
+ )
492
+ random_access_proxy = proxy_factory(fmt, filename)
493
+ if key_function:
494
+ offset_iter = (
495
+ (key_function(key), file_index, offset, length)
496
+ for (key, offset, length) in random_access_proxy
497
+ )
498
+ else:
499
+ offset_iter = (
500
+ (key, file_index, offset, length)
501
+ for (key, offset, length) in random_access_proxy
502
+ )
503
+ while True:
504
+ batch = list(itertools.islice(offset_iter, 100))
505
+ if not batch:
506
+ break
507
+ # print("Inserting batch of %i offsets, %s ... %s"
508
+ # % (len(batch), batch[0][0], batch[-1][0]))
509
+ con.executemany(
510
+ "INSERT INTO offset_data (key,file_number,offset,length) VALUES (?,?,?,?);",
511
+ batch,
512
+ )
513
+ con.commit()
514
+ count += len(batch)
515
+ if len(random_access_proxies) < max_open:
516
+ random_access_proxies[file_index] = random_access_proxy
517
+ else:
518
+ random_access_proxy._handle.close()
519
+ self._length = count
520
+ # print("About to index %i entries" % count)
521
+ try:
522
+ con.execute(
523
+ "CREATE UNIQUE INDEX IF NOT EXISTS key_index ON offset_data(key);"
524
+ )
525
+ except sqlite3.IntegrityError as err:
526
+ self._proxies = random_access_proxies
527
+ self.close()
528
+ con.close()
529
+ raise ValueError(f"Duplicate key? {err}") from None
530
+ con.execute("PRAGMA locking_mode=NORMAL")
531
+ con.execute("UPDATE meta_data SET value = ? WHERE key = ?;", (count, "count"))
532
+ con.commit()
533
+ # print("Index created")
534
+
535
+ def __repr__(self):
536
+ return self._repr
537
+
538
+ def __contains__(self, key):
539
+ return bool(
540
+ self._con.execute(
541
+ "SELECT key FROM offset_data WHERE key=?;", (key,)
542
+ ).fetchone()
543
+ )
544
+
545
+ def __len__(self):
546
+ """Return the number of records indexed."""
547
+ return self._length
548
+ # return self._con.execute("SELECT COUNT(key) FROM offset_data;").fetchone()[0]
549
+
550
+ def __iter__(self):
551
+ """Iterate over the keys."""
552
+ for row in self._con.execute(
553
+ "SELECT key FROM offset_data ORDER BY file_number, offset;"
554
+ ):
555
+ yield str(row[0])
556
+
557
+ def __getitem__(self, key):
558
+ """Return record for the specified key."""
559
+ # Pass the offset to the proxy
560
+ row = self._con.execute(
561
+ "SELECT file_number, offset FROM offset_data WHERE key=?;", (key,)
562
+ ).fetchone()
563
+ if not row:
564
+ raise KeyError
565
+ file_number, offset = row
566
+ proxies = self._proxies
567
+ if file_number in proxies:
568
+ record = proxies[file_number].get(offset)
569
+ else:
570
+ if len(proxies) >= self._max_open:
571
+ # Close an old handle...
572
+ proxies.popitem()[1]._handle.close()
573
+ # Open a new handle...
574
+ proxy = self._proxy_factory(self._format, self._filenames[file_number])
575
+ record = proxy.get(offset)
576
+ proxies[file_number] = proxy
577
+ if self._key_function:
578
+ key2 = self._key_function(record.id)
579
+ else:
580
+ key2 = record.id
581
+ if key != key2:
582
+ raise ValueError(f"Key did not match ({key} vs {key2})")
583
+ return record
584
+
585
+ def get_raw(self, key):
586
+ """Return the raw record from the file as a bytes string.
587
+
588
+ If the key is not found, a KeyError exception is raised.
589
+ """
590
+ # Pass the offset to the proxy
591
+ row = self._con.execute(
592
+ "SELECT file_number, offset, length FROM offset_data WHERE key=?;", (key,)
593
+ ).fetchone()
594
+ if not row:
595
+ raise KeyError
596
+ file_number, offset, length = row
597
+ proxies = self._proxies
598
+ if file_number in proxies:
599
+ if length:
600
+ # Shortcut if we have the length
601
+ h = proxies[file_number]._handle
602
+ h.seek(offset)
603
+ return h.read(length)
604
+ else:
605
+ return proxies[file_number].get_raw(offset)
606
+ else:
607
+ # This code is duplicated from __getitem__ to avoid a function call
608
+ if len(proxies) >= self._max_open:
609
+ # Close an old handle...
610
+ proxies.popitem()[1]._handle.close()
611
+ # Open a new handle...
612
+ proxy = self._proxy_factory(self._format, self._filenames[file_number])
613
+ proxies[file_number] = proxy
614
+ if length:
615
+ # Shortcut if we have the length
616
+ h = proxy._handle
617
+ h.seek(offset)
618
+ return h.read(length)
619
+ else:
620
+ return proxy.get_raw(offset)
621
+
622
+ def close(self):
623
+ """Close any open file handles."""
624
+ proxies = self._proxies
625
+ while proxies:
626
+ proxies.popitem()[1]._handle.close()
.venv_haddock/lib/python3.12/site-packages/Bio/Seq.py ADDED
The diff for this file is too large to render. See raw diff
 
.venv_haddock/lib/python3.12/site-packages/Bio/SeqFeature.py ADDED
@@ -0,0 +1,2332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2000-2003 Jeff Chang.
2
+ # Copyright 2001-2008 Brad Chapman.
3
+ # Copyright 2005-2024 by Peter Cock.
4
+ # Copyright 2006-2009 Michiel de Hoon.
5
+ # All rights reserved.
6
+ #
7
+ # This file is part of the Biopython distribution and governed by your
8
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
9
+ # Please see the LICENSE file that should have been included as part of this
10
+ # package.
11
+ """Represent a Sequence Feature holding info about a part of a sequence.
12
+
13
+ This is heavily modeled after the Biocorba SeqFeature objects, and
14
+ may be pretty biased towards GenBank stuff since I'm writing it
15
+ for the GenBank parser output...
16
+
17
+ What's here:
18
+
19
+ Base class to hold a Feature
20
+ ----------------------------
21
+
22
+ Classes:
23
+ - SeqFeature
24
+
25
+ Hold information about a Reference
26
+ ----------------------------------
27
+
28
+ This is an attempt to create a General class to hold Reference type
29
+ information.
30
+
31
+ Classes:
32
+ - Reference
33
+
34
+ Specify locations of a feature on a Sequence
35
+ --------------------------------------------
36
+
37
+ This aims to handle, in Ewan Birney's words, 'the dreaded fuzziness issue'.
38
+ This has the advantages of allowing us to handle fuzzy stuff in case anyone
39
+ needs it, and also be compatible with BioPerl etc and BioSQL.
40
+
41
+ Classes:
42
+ - Location - abstract base class of SimpleLocation and CompoundLocation.
43
+ - SimpleLocation - Specify the start and end location of a feature.
44
+ - CompoundLocation - Collection of SimpleLocation objects (for joins etc).
45
+ - Position - abstract base class of ExactPosition, WithinPosition,
46
+ BetweenPosition, AfterPosition, OneOfPosition, UncertainPosition, and
47
+ UnknownPosition.
48
+ - ExactPosition - Specify the position as being exact.
49
+ - WithinPosition - Specify a position occurring within some range.
50
+ - BetweenPosition - Specify a position occurring between a range (OBSOLETE?).
51
+ - BeforePosition - Specify the position as being found before some base.
52
+ - AfterPosition - Specify the position as being found after some base.
53
+ - OneOfPosition - Specify a position consisting of multiple alternative positions.
54
+ - UncertainPosition - Specify a specific position which is uncertain.
55
+ - UnknownPosition - Represents missing information like '?' in UniProt.
56
+
57
+
58
+ Exceptions:
59
+ - LocationParserError - Exception indicating a failure to parse a location
60
+ string.
61
+
62
+ """
63
+
64
+ import functools
65
+ import re
66
+ import warnings
67
+ from abc import ABC
68
+ from abc import abstractmethod
69
+
70
+ from Bio import BiopythonParserWarning
71
+ from Bio.Seq import MutableSeq
72
+ from Bio.Seq import reverse_complement
73
+ from Bio.Seq import Seq
74
+
75
+ # Regular expressions for location parsing
76
+
77
+ _reference = r"(?:[a-zA-Z][a-zA-Z0-9_\.\|]*[a-zA-Z0-9]?\:)"
78
+ _oneof_position = r"one\-of\(\d+[,\d+]+\)"
79
+
80
+ _oneof_location = rf"[<>]?(?:\d+|{_oneof_position})\.\.[<>]?(?:\d+|{_oneof_position})"
81
+
82
+ _any_location = rf"({_reference}?{_oneof_location}|complement\({_oneof_location}\)|[^,]+|complement\([^,]+\))"
83
+
84
+ _split = re.compile(_any_location).split
85
+
86
+ assert _split("123..145")[1::2] == ["123..145"]
87
+ assert _split("123..145,200..209")[1::2] == ["123..145", "200..209"]
88
+ assert _split("one-of(200,203)..300")[1::2] == ["one-of(200,203)..300"]
89
+ assert _split("complement(123..145),200..209")[1::2] == [
90
+ "complement(123..145)",
91
+ "200..209",
92
+ ]
93
+ assert _split("123..145,one-of(200,203)..209")[1::2] == [
94
+ "123..145",
95
+ "one-of(200,203)..209",
96
+ ]
97
+ assert _split("123..145,one-of(200,203)..one-of(209,211),300")[1::2] == [
98
+ "123..145",
99
+ "one-of(200,203)..one-of(209,211)",
100
+ "300",
101
+ ]
102
+ assert _split("123..145,complement(one-of(200,203)..one-of(209,211)),300")[1::2] == [
103
+ "123..145",
104
+ "complement(one-of(200,203)..one-of(209,211))",
105
+ "300",
106
+ ]
107
+ assert _split("123..145,200..one-of(209,211),300")[1::2] == [
108
+ "123..145",
109
+ "200..one-of(209,211)",
110
+ "300",
111
+ ]
112
+ assert _split("123..145,200..one-of(209,211)")[1::2] == [
113
+ "123..145",
114
+ "200..one-of(209,211)",
115
+ ]
116
+ assert _split(
117
+ "complement(149815..150200),complement(293787..295573),NC_016402.1:6618..6676,181647..181905"
118
+ )[1::2] == [
119
+ "complement(149815..150200)",
120
+ "complement(293787..295573)",
121
+ "NC_016402.1:6618..6676",
122
+ "181647..181905",
123
+ ]
124
+
125
+ _pair_location = r"[<>]?-?\d+\.\.[<>]?-?\d+"
126
+
127
+ _between_location = r"\d+\^\d+"
128
+
129
+ _within_position = r"\(\d+\.\d+\)"
130
+ _within_location = r"([<>]?\d+|%s)\.\.([<>]?\d+|%s)" % (
131
+ _within_position,
132
+ _within_position,
133
+ )
134
+ _within_position = r"\((\d+)\.(\d+)\)"
135
+ _re_within_position = re.compile(_within_position)
136
+ assert _re_within_position.match("(3.9)")
137
+
138
+ _oneof_location = r"([<>]?\d+|%s)\.\.([<>]?\d+|%s)" % (_oneof_position, _oneof_position)
139
+ _oneof_position = r"one\-of\((\d+[,\d+]+)\)"
140
+ _re_oneof_position = re.compile(_oneof_position)
141
+ assert _re_oneof_position.match("one-of(6,9)")
142
+ assert not _re_oneof_position.match("one-of(3)")
143
+ assert _re_oneof_position.match("one-of(3,6)")
144
+ assert _re_oneof_position.match("one-of(3,6,9)")
145
+
146
+ _solo_location = r"[<>]?\d+"
147
+ _solo_bond = r"bond\(%s\)" % _solo_location
148
+
149
+ _re_location_category = re.compile(
150
+ r"^(?P<pair>%s)|(?P<between>%s)|(?P<within>%s)|(?P<oneof>%s)|(?P<bond>%s)|(?P<solo>%s)$"
151
+ % (
152
+ _pair_location,
153
+ _between_location,
154
+ _within_location,
155
+ _oneof_location,
156
+ _solo_bond,
157
+ _solo_location,
158
+ )
159
+ )
160
+
161
+
162
+ class LocationParserError(ValueError):
163
+ """Could not parse a feature location string."""
164
+
165
+
166
+ class SeqFeature:
167
+ """Represent a Sequence Feature on an object.
168
+
169
+ Attributes:
170
+ - location - the location of the feature on the sequence (SimpleLocation)
171
+ - type - the specified type of the feature (ie. CDS, exon, repeat...)
172
+ - id - A string identifier for the feature.
173
+ - qualifiers - A dictionary of qualifiers on the feature. These are
174
+ analogous to the qualifiers from a GenBank feature table. The keys of
175
+ the dictionary are qualifier names, the values are the qualifier
176
+ values.
177
+
178
+ """
179
+
180
+ def __init__(
181
+ self,
182
+ location=None,
183
+ type="",
184
+ id="<unknown id>",
185
+ qualifiers=None,
186
+ sub_features=None,
187
+ ):
188
+ """Initialize a SeqFeature on a sequence.
189
+
190
+ location can either be a SimpleLocation (with strand argument also
191
+ given if required), or None.
192
+
193
+ e.g. With no strand, on the forward strand, and on the reverse strand:
194
+
195
+ >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
196
+ >>> f1 = SeqFeature(SimpleLocation(5, 10), type="domain")
197
+ >>> f1.location.strand == None
198
+ True
199
+ >>> f2 = SeqFeature(SimpleLocation(7, 110, strand=1), type="CDS")
200
+ >>> f2.location.strand == +1
201
+ True
202
+ >>> f3 = SeqFeature(SimpleLocation(9, 108, strand=-1), type="CDS")
203
+ >>> f3.location.strand == -1
204
+ True
205
+
206
+ For exact start/end positions, an integer can be used (as shown above)
207
+ as shorthand for the ExactPosition object. For non-exact locations, the
208
+ SimpleLocation must be specified via the appropriate position objects.
209
+ """
210
+ if (
211
+ location is not None
212
+ and not isinstance(location, SimpleLocation)
213
+ and not isinstance(location, CompoundLocation)
214
+ ):
215
+ raise TypeError(
216
+ "SimpleLocation, CompoundLocation (or None) required for the location"
217
+ )
218
+ self.location = location
219
+ self.type = type
220
+ self.id = id
221
+ self.qualifiers = {}
222
+ if qualifiers is not None:
223
+ self.qualifiers.update(qualifiers)
224
+ if sub_features is not None:
225
+ raise TypeError("Rather than sub_features, use a CompoundLocation")
226
+
227
+ def __eq__(self, other):
228
+ """Check if two SeqFeature objects should be considered equal."""
229
+ return (
230
+ isinstance(other, SeqFeature)
231
+ and self.id == other.id
232
+ and self.type == other.type
233
+ and self.location == other.location
234
+ and self.qualifiers == other.qualifiers
235
+ )
236
+
237
+ def __repr__(self):
238
+ """Represent the feature as a string for debugging."""
239
+ answer = f"{self.__class__.__name__}({self.location!r}"
240
+ if self.type:
241
+ answer += f", type={self.type!r}"
242
+ if self.id and self.id != "<unknown id>":
243
+ answer += f", id={self.id!r}"
244
+ if self.qualifiers:
245
+ answer += ", qualifiers=..."
246
+ answer += ")"
247
+ return answer
248
+
249
+ def __str__(self):
250
+ """Return the full feature as a python string."""
251
+ out = f"type: {self.type}\n"
252
+ out += f"location: {self.location}\n"
253
+ if self.id and self.id != "<unknown id>":
254
+ out += f"id: {self.id}\n"
255
+ out += "qualifiers:\n"
256
+ for qual_key in sorted(self.qualifiers):
257
+ out += f" Key: {qual_key}, Value: {self.qualifiers[qual_key]}\n"
258
+ return out
259
+
260
+ def _shift(self, offset):
261
+ """Return a copy of the feature with its location shifted (PRIVATE).
262
+
263
+ The annotation qualifiers are copied.
264
+ """
265
+ return SeqFeature(
266
+ location=self.location._shift(offset),
267
+ type=self.type,
268
+ id=self.id,
269
+ qualifiers=self.qualifiers.copy(),
270
+ )
271
+
272
+ def _flip(self, length):
273
+ """Return a copy of the feature with its location flipped (PRIVATE).
274
+
275
+ The argument length gives the length of the parent sequence. For
276
+ example a location 0..20 (+1 strand) with parent length 30 becomes
277
+ after flipping 10..30 (-1 strand). Strandless (None) or unknown
278
+ strand (0) remain like that - just their end points are changed.
279
+
280
+ The annotation qualifiers are copied.
281
+ """
282
+ return SeqFeature(
283
+ location=self.location._flip(length),
284
+ type=self.type,
285
+ id=self.id,
286
+ qualifiers=self.qualifiers.copy(),
287
+ )
288
+
289
+ def extract(self, parent_sequence, references=None):
290
+ """Extract the feature's sequence from supplied parent sequence.
291
+
292
+ The parent_sequence can be a Seq like object or a string, and will
293
+ generally return an object of the same type. The exception to this is
294
+ a MutableSeq as the parent sequence will return a Seq object.
295
+
296
+ This should cope with complex locations including complements, joins
297
+ and fuzzy positions. Even mixed strand features should work! This
298
+ also covers features on protein sequences (e.g. domains), although
299
+ here reverse strand features are not permitted. If the
300
+ location refers to other records, they must be supplied in the
301
+ optional dictionary references.
302
+
303
+ >>> from Bio.Seq import Seq
304
+ >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
305
+ >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
306
+ >>> f = SeqFeature(SimpleLocation(8, 15), type="domain")
307
+ >>> f.extract(seq)
308
+ Seq('VALIVIC')
309
+
310
+ If the SimpleLocation is None, e.g. when parsing invalid locus
311
+ locations in the GenBank parser, extract() will raise a ValueError.
312
+
313
+ >>> from Bio.Seq import Seq
314
+ >>> from Bio.SeqFeature import SeqFeature
315
+ >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
316
+ >>> f = SeqFeature(None, type="domain")
317
+ >>> f.extract(seq)
318
+ Traceback (most recent call last):
319
+ ...
320
+ ValueError: The feature's .location is None. Check the sequence file for a valid location.
321
+
322
+ Note - currently only compound features of type "join" are supported.
323
+ """
324
+ if self.location is None:
325
+ raise ValueError(
326
+ "The feature's .location is None. Check the "
327
+ "sequence file for a valid location."
328
+ )
329
+ return self.location.extract(parent_sequence, references=references)
330
+
331
+ def translate(
332
+ self,
333
+ parent_sequence,
334
+ table="Standard",
335
+ start_offset=None,
336
+ stop_symbol="*",
337
+ to_stop=False,
338
+ cds=None,
339
+ gap=None,
340
+ ):
341
+ """Get a translation of the feature's sequence.
342
+
343
+ This method is intended for CDS or other features that code proteins
344
+ and is a shortcut that will both extract the feature and
345
+ translate it, taking into account the codon_start and transl_table
346
+ qualifiers, if they are present. If they are not present the
347
+ value of the arguments "table" and "start_offset" are used.
348
+
349
+ The "cds" parameter is set to "True" if the feature is of type
350
+ "CDS" but can be overridden by giving an explicit argument.
351
+
352
+ The arguments stop_symbol, to_stop and gap have the same meaning
353
+ as Seq.translate, refer to that documentation for further information.
354
+
355
+ Arguments:
356
+ - parent_sequence - A DNA or RNA sequence.
357
+ - table - Which codon table to use if there is no transl_table
358
+ qualifier for this feature. This can be either a name
359
+ (string), an NCBI identifier (integer), or a CodonTable
360
+ object (useful for non-standard genetic codes). This
361
+ defaults to the "Standard" table.
362
+ - start_offset - offset at which the first complete codon of a
363
+ coding feature can be found, relative to the first base of
364
+ that feature. Has a valid value of 0, 1 or 2. NOTE: this
365
+ uses python's 0-based numbering whereas the codon_start
366
+ qualifier in files from NCBI use 1-based numbering.
367
+ Will override a codon_start qualifier
368
+
369
+ >>> from Bio.Seq import Seq
370
+ >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
371
+ >>> seq = Seq("GGTTACACTTACCGATAATGTCTCTGATGA")
372
+ >>> f = SeqFeature(SimpleLocation(0, 30), type="CDS")
373
+ >>> f.qualifiers['transl_table'] = [11]
374
+
375
+ Note that features of type CDS are subject to the usual
376
+ checks at translation. But you can override this behavior
377
+ by giving explicit arguments:
378
+
379
+ >>> f.translate(seq, cds=False)
380
+ Seq('GYTYR*CL**')
381
+
382
+ Now use the start_offset argument to change the frame. Note
383
+ this uses python 0-based numbering.
384
+
385
+ >>> f.translate(seq, start_offset=1, cds=False)
386
+ Seq('VTLTDNVSD')
387
+
388
+ Alternatively use the codon_start qualifier to do the same
389
+ thing. Note: this uses 1-based numbering, which is found
390
+ in files from NCBI.
391
+
392
+ >>> f.qualifiers['codon_start'] = [2]
393
+ >>> f.translate(seq, cds=False)
394
+ Seq('VTLTDNVSD')
395
+ """
396
+ # see if this feature should be translated in a different
397
+ # frame using the "codon_start" qualifier
398
+ if start_offset is None:
399
+ try:
400
+ start_offset = int(self.qualifiers["codon_start"][0]) - 1
401
+ except KeyError:
402
+ start_offset = 0
403
+
404
+ if start_offset not in [0, 1, 2]:
405
+ raise ValueError(
406
+ "The start_offset must be 0, 1, or 2. "
407
+ f"The supplied value is {start_offset}. "
408
+ "Check the value of either the codon_start qualifier "
409
+ "or the start_offset argument"
410
+ )
411
+
412
+ feat_seq = self.extract(parent_sequence)[start_offset:]
413
+ codon_table = self.qualifiers.get("transl_table", [table])[0]
414
+
415
+ if cds is None:
416
+ cds = self.type == "CDS"
417
+
418
+ return feat_seq.translate(
419
+ table=codon_table,
420
+ stop_symbol=stop_symbol,
421
+ to_stop=to_stop,
422
+ cds=cds,
423
+ gap=gap,
424
+ )
425
+
426
+ def __bool__(self):
427
+ """Boolean value of an instance of this class (True).
428
+
429
+ This behavior is for backwards compatibility, since until the
430
+ __len__ method was added, a SeqFeature always evaluated as True.
431
+
432
+ Note that in comparison, Seq objects, strings, lists, etc, will all
433
+ evaluate to False if they have length zero.
434
+
435
+ WARNING: The SeqFeature may in future evaluate to False when its
436
+ length is zero (in order to better match normal python behavior)!
437
+ """
438
+ return True
439
+
440
+ def __len__(self):
441
+ """Return the length of the region where the feature is located.
442
+
443
+ >>> from Bio.Seq import Seq
444
+ >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
445
+ >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
446
+ >>> f = SeqFeature(SimpleLocation(8, 15), type="domain")
447
+ >>> len(f)
448
+ 7
449
+ >>> f.extract(seq)
450
+ Seq('VALIVIC')
451
+ >>> len(f.extract(seq))
452
+ 7
453
+
454
+ This is a proxy for taking the length of the feature's location:
455
+
456
+ >>> len(f.location)
457
+ 7
458
+
459
+ For simple features this is the same as the region spanned (end
460
+ position minus start position using Pythonic counting). However, for
461
+ a compound location (e.g. a CDS as the join of several exons) the
462
+ gaps are not counted (e.g. introns). This ensures that len(f) matches
463
+ len(f.extract(parent_seq)), and also makes sure things work properly
464
+ with features wrapping the origin etc.
465
+ """
466
+ return len(self.location)
467
+
468
+ def __iter__(self):
469
+ """Iterate over the parent positions within the feature.
470
+
471
+ The iteration order is strand aware, and can be thought of as moving
472
+ along the feature using the parent sequence coordinates:
473
+
474
+ >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
475
+ >>> f = SeqFeature(SimpleLocation(5, 10, strand=-1), type="domain")
476
+ >>> len(f)
477
+ 5
478
+ >>> for i in f: print(i)
479
+ 9
480
+ 8
481
+ 7
482
+ 6
483
+ 5
484
+ >>> list(f)
485
+ [9, 8, 7, 6, 5]
486
+
487
+ This is a proxy for iterating over the location,
488
+
489
+ >>> list(f.location)
490
+ [9, 8, 7, 6, 5]
491
+ """
492
+ return iter(self.location)
493
+
494
+ def __contains__(self, value):
495
+ """Check if an integer position is within the feature.
496
+
497
+ >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
498
+ >>> f = SeqFeature(SimpleLocation(5, 10, strand=-1), type="domain")
499
+ >>> len(f)
500
+ 5
501
+ >>> [i for i in range(15) if i in f]
502
+ [5, 6, 7, 8, 9]
503
+
504
+ For example, to see which features include a SNP position, you could
505
+ use this:
506
+
507
+ >>> from Bio import SeqIO
508
+ >>> record = SeqIO.read("GenBank/NC_000932.gb", "gb")
509
+ >>> for f in record.features:
510
+ ... if 1750 in f:
511
+ ... print("%s %s" % (f.type, f.location))
512
+ source [0:154478](+)
513
+ gene [1716:4347](-)
514
+ tRNA join{[4310:4347](-), [1716:1751](-)}
515
+
516
+ Note that for a feature defined as a join of several subfeatures (e.g.
517
+ the union of several exons) the gaps are not checked (e.g. introns).
518
+ In this example, the tRNA location is defined in the GenBank file as
519
+ complement(join(1717..1751,4311..4347)), so that position 1760 falls
520
+ in the gap:
521
+
522
+ >>> for f in record.features:
523
+ ... if 1760 in f:
524
+ ... print("%s %s" % (f.type, f.location))
525
+ source [0:154478](+)
526
+ gene [1716:4347](-)
527
+
528
+ Note that additional care may be required with fuzzy locations, for
529
+ example just before a BeforePosition:
530
+
531
+ >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
532
+ >>> from Bio.SeqFeature import BeforePosition
533
+ >>> f = SeqFeature(SimpleLocation(BeforePosition(3), 8), type="domain")
534
+ >>> len(f)
535
+ 5
536
+ >>> [i for i in range(10) if i in f]
537
+ [3, 4, 5, 6, 7]
538
+
539
+ Note that is is a proxy for testing membership on the location.
540
+
541
+ >>> [i for i in range(10) if i in f.location]
542
+ [3, 4, 5, 6, 7]
543
+ """
544
+ return value in self.location
545
+
546
+
547
+ # --- References
548
+
549
+
550
+ # TODO -- Will this hold PubMed and Medline information decently?
551
+ class Reference:
552
+ """Represent a Generic Reference object.
553
+
554
+ Attributes:
555
+ - location - A list of Location objects specifying regions of
556
+ the sequence that the references correspond to. If no locations are
557
+ specified, the entire sequence is assumed.
558
+ - authors - A big old string, or a list split by author, of authors
559
+ for the reference.
560
+ - title - The title of the reference.
561
+ - journal - Journal the reference was published in.
562
+ - medline_id - A medline reference for the article.
563
+ - pubmed_id - A pubmed reference for the article.
564
+ - comment - A place to stick any comments about the reference.
565
+
566
+ """
567
+
568
+ def __init__(self):
569
+ """Initialize the class."""
570
+ self.location = []
571
+ self.authors = ""
572
+ self.consrtm = ""
573
+ self.title = ""
574
+ self.journal = ""
575
+ self.medline_id = ""
576
+ self.pubmed_id = ""
577
+ self.comment = ""
578
+
579
+ def __str__(self):
580
+ """Return the full Reference object as a python string."""
581
+ out = ""
582
+ for single_location in self.location:
583
+ out += f"location: {single_location}\n"
584
+ out += f"authors: {self.authors}\n"
585
+ if self.consrtm:
586
+ out += f"consrtm: {self.consrtm}\n"
587
+ out += f"title: {self.title}\n"
588
+ out += f"journal: {self.journal}\n"
589
+ out += f"medline id: {self.medline_id}\n"
590
+ out += f"pubmed id: {self.pubmed_id}\n"
591
+ out += f"comment: {self.comment}\n"
592
+ return out
593
+
594
+ def __repr__(self):
595
+ """Represent the Reference object as a string for debugging."""
596
+ # TODO - Update this is __init__ later accepts values
597
+ return f"{self.__class__.__name__}(title={self.title!r}, ...)"
598
+
599
+ def __eq__(self, other):
600
+ """Check if two Reference objects should be considered equal.
601
+
602
+ Note prior to Biopython 1.70 the location was not compared, as
603
+ until then __eq__ for the SimpleLocation class was not defined.
604
+ """
605
+ return (
606
+ self.authors == other.authors
607
+ and self.consrtm == other.consrtm
608
+ and self.title == other.title
609
+ and self.journal == other.journal
610
+ and self.medline_id == other.medline_id
611
+ and self.pubmed_id == other.pubmed_id
612
+ and self.comment == other.comment
613
+ and self.location == other.location
614
+ )
615
+
616
+
617
+ # --- Handling feature locations
618
+
619
+
620
+ class Location(ABC):
621
+ """Abstract base class representing a location."""
622
+
623
+ @abstractmethod
624
+ def __repr__(self):
625
+ """Represent the Location object as a string for debugging."""
626
+ return f"{self.__class__.__name__}(...)"
627
+
628
+ @staticmethod
629
+ def fromstring(text, length=None, circular=False, stranded=True):
630
+ """Create a Location object from a string.
631
+
632
+ This should accept any valid location string in the INSDC Feature Table
633
+ format (https://www.insdc.org/submitting-standards/feature-table/) as
634
+ used in GenBank, DDBJ and EMBL files.
635
+
636
+ Simple examples:
637
+
638
+ >>> Location.fromstring("123..456", 1000)
639
+ SimpleLocation(ExactPosition(122), ExactPosition(456), strand=1)
640
+ >>> Location.fromstring("complement(<123..>456)", 1000)
641
+ SimpleLocation(BeforePosition(122), AfterPosition(456), strand=-1)
642
+
643
+ A more complex location using within positions,
644
+
645
+ >>> Location.fromstring("(9.10)..(20.25)", 1000)
646
+ SimpleLocation(WithinPosition(8, left=8, right=9), WithinPosition(25, left=20, right=25), strand=1)
647
+
648
+ Notice how that will act as though it has overall start 8 and end 25.
649
+
650
+ Zero length between feature,
651
+
652
+ >>> Location.fromstring("123^124", 1000)
653
+ SimpleLocation(ExactPosition(123), ExactPosition(123), strand=1)
654
+
655
+ The expected sequence length is needed for a special case, a between
656
+ position at the start/end of a circular genome:
657
+
658
+ >>> Location.fromstring("1000^1", 1000)
659
+ SimpleLocation(ExactPosition(1000), ExactPosition(1000), strand=1)
660
+
661
+ Apart from this special case, between positions P^Q must have P+1==Q,
662
+
663
+ >>> Location.fromstring("123^456", 1000)
664
+ Traceback (most recent call last):
665
+ ...
666
+ Bio.SeqFeature.LocationParserError: invalid feature location '123^456'
667
+
668
+ You can optionally provide a reference name:
669
+
670
+ >>> Location.fromstring("AL391218.9:105173..108462", 2000000)
671
+ SimpleLocation(ExactPosition(105172), ExactPosition(108462), strand=1, ref='AL391218.9')
672
+
673
+ >>> Location.fromstring("<2644..159", 2868, "circular")
674
+ CompoundLocation([SimpleLocation(BeforePosition(2643), ExactPosition(2868), strand=1), SimpleLocation(ExactPosition(0), ExactPosition(159), strand=1)], 'join')
675
+ """
676
+ if text.startswith("complement("):
677
+ if text[-1] != ")":
678
+ raise ValueError(f"closing bracket missing in '{text}'")
679
+ text = text[11:-1]
680
+ strand = -1
681
+ elif stranded:
682
+ strand = 1
683
+ else:
684
+ strand = None
685
+
686
+ # Determine if we have a simple location or a compound location
687
+ if text.startswith("join("):
688
+ operator = "join"
689
+ parts = _split(text[5:-1])[1::2]
690
+ # assert parts[0] == "" and parts[-1] == ""
691
+ elif text.startswith("order("):
692
+ operator = "order"
693
+ parts = _split(text[6:-1])[1::2]
694
+ # assert parts[0] == "" and parts[-1] == ""
695
+ elif text.startswith("bond("):
696
+ operator = "bond"
697
+ parts = _split(text[5:-1])[1::2]
698
+ # assert parts[0] == "" and parts[-1] == ""
699
+ else:
700
+ loc = SimpleLocation.fromstring(text, length, circular)
701
+ loc.strand = strand
702
+ if strand == -1:
703
+ loc.parts.reverse()
704
+ return loc
705
+ locs = []
706
+ for part in parts:
707
+ loc = SimpleLocation.fromstring(part, length, circular)
708
+ if loc is None:
709
+ break
710
+ if loc.strand == -1:
711
+ if strand == -1:
712
+ raise LocationParserError("double complement in '{text}'?")
713
+ else:
714
+ loc.strand = strand
715
+ locs.extend(loc.parts)
716
+ else:
717
+ if len(locs) == 1:
718
+ return loc
719
+ # Historically a join on the reverse strand has been represented
720
+ # in Biopython with both the parent SeqFeature and its children
721
+ # (the exons for a CDS) all given a strand of -1. Likewise, for
722
+ # a join feature on the forward strand they all have strand +1.
723
+ # However, we must also consider evil mixed strand examples like
724
+ # this, join(complement(69611..69724),139856..140087,140625..140650)
725
+ if strand == -1:
726
+ # Whole thing was wrapped in complement(...)
727
+ for loc in locs:
728
+ assert loc.strand == -1
729
+ # Reverse the backwards order used in GenBank files
730
+ # with complement(join(...))
731
+ locs = locs[::-1]
732
+ return CompoundLocation(locs, operator=operator)
733
+ # Not recognized
734
+ if "order" in text and "join" in text:
735
+ # See Bug 3197
736
+ raise LocationParserError(
737
+ f"failed to parse feature location '{text}' containing a combination of 'join' and 'order' (nested operators) are illegal"
738
+ )
739
+
740
+ # See issue #937. Note that NCBI has already fixed this record.
741
+ if ",)" in text:
742
+ warnings.warn(
743
+ "Dropping trailing comma in malformed feature location",
744
+ BiopythonParserWarning,
745
+ )
746
+ text = text.replace(",)", ")")
747
+ return Location.fromstring(text)
748
+
749
+ raise LocationParserError(f"failed to parse feature location '{text}'")
750
+
751
+
752
+ class SimpleLocation(Location):
753
+ """Specify the location of a feature along a sequence.
754
+
755
+ The SimpleLocation is used for simple continuous features, which can
756
+ be described as running from a start position to and end position
757
+ (optionally with a strand and reference information). More complex
758
+ locations made up from several non-continuous parts (e.g. a coding
759
+ sequence made up of several exons) are described using a SeqFeature
760
+ with a CompoundLocation.
761
+
762
+ Note that the start and end location numbering follow Python's scheme,
763
+ thus a GenBank entry of 123..150 (one based counting) becomes a location
764
+ of [122:150] (zero based counting).
765
+
766
+ >>> from Bio.SeqFeature import SimpleLocation
767
+ >>> f = SimpleLocation(122, 150)
768
+ >>> print(f)
769
+ [122:150]
770
+ >>> print(f.start)
771
+ 122
772
+ >>> print(f.end)
773
+ 150
774
+ >>> print(f.strand)
775
+ None
776
+
777
+ Note the strand defaults to None. If you are working with nucleotide
778
+ sequences you'd want to be explicit if it is the forward strand:
779
+
780
+ >>> from Bio.SeqFeature import SimpleLocation
781
+ >>> f = SimpleLocation(122, 150, strand=+1)
782
+ >>> print(f)
783
+ [122:150](+)
784
+ >>> print(f.strand)
785
+ 1
786
+
787
+ Note that for a parent sequence of length n, the SimpleLocation
788
+ start and end must satisfy the inequality 0 <= start <= end <= n.
789
+ This means even for features on the reverse strand of a nucleotide
790
+ sequence, we expect the 'start' coordinate to be less than the
791
+ 'end'.
792
+
793
+ >>> from Bio.SeqFeature import SimpleLocation
794
+ >>> r = SimpleLocation(122, 150, strand=-1)
795
+ >>> print(r)
796
+ [122:150](-)
797
+ >>> print(r.start)
798
+ 122
799
+ >>> print(r.end)
800
+ 150
801
+ >>> print(r.strand)
802
+ -1
803
+
804
+ i.e. Rather than thinking of the 'start' and 'end' biologically in a
805
+ strand aware manner, think of them as the 'left most' or 'minimum'
806
+ boundary, and the 'right most' or 'maximum' boundary of the region
807
+ being described. This is particularly important with compound
808
+ locations describing non-continuous regions.
809
+
810
+ In the example above we have used standard exact positions, but there
811
+ are also specialised position objects used to represent fuzzy positions
812
+ as well, for example a GenBank location like complement(<123..150)
813
+ would use a BeforePosition object for the start.
814
+ """
815
+
816
+ def __init__(self, start, end, strand=None, ref=None, ref_db=None):
817
+ """Initialize the class.
818
+
819
+ start and end arguments specify the values where the feature begins
820
+ and ends. These can either by any of the ``*Position`` objects that
821
+ inherit from Position, or can just be integers specifying the position.
822
+ In the case of integers, the values are assumed to be exact and are
823
+ converted in ExactPosition arguments. This is meant to make it easy
824
+ to deal with non-fuzzy ends.
825
+
826
+ i.e. Short form:
827
+
828
+ >>> from Bio.SeqFeature import SimpleLocation
829
+ >>> loc = SimpleLocation(5, 10, strand=-1)
830
+ >>> print(loc)
831
+ [5:10](-)
832
+
833
+ Explicit form:
834
+
835
+ >>> from Bio.SeqFeature import SimpleLocation, ExactPosition
836
+ >>> loc = SimpleLocation(ExactPosition(5), ExactPosition(10), strand=-1)
837
+ >>> print(loc)
838
+ [5:10](-)
839
+
840
+ Other fuzzy positions are used similarly,
841
+
842
+ >>> from Bio.SeqFeature import SimpleLocation
843
+ >>> from Bio.SeqFeature import BeforePosition, AfterPosition
844
+ >>> loc2 = SimpleLocation(BeforePosition(5), AfterPosition(10), strand=-1)
845
+ >>> print(loc2)
846
+ [<5:>10](-)
847
+
848
+ For nucleotide features you will also want to specify the strand,
849
+ use 1 for the forward (plus) strand, -1 for the reverse (negative)
850
+ strand, 0 for stranded but strand unknown (? in GFF3), or None for
851
+ when the strand does not apply (dot in GFF3), e.g. features on
852
+ proteins.
853
+
854
+ >>> loc = SimpleLocation(5, 10, strand=+1)
855
+ >>> print(loc)
856
+ [5:10](+)
857
+ >>> print(loc.strand)
858
+ 1
859
+
860
+ Normally feature locations are given relative to the parent
861
+ sequence you are working with, but an explicit accession can
862
+ be given with the optional ref and db_ref strings:
863
+
864
+ >>> loc = SimpleLocation(105172, 108462, ref="AL391218.9", strand=1)
865
+ >>> print(loc)
866
+ AL391218.9[105172:108462](+)
867
+ >>> print(loc.ref)
868
+ AL391218.9
869
+
870
+ """
871
+ # TODO - Check 0 <= start <= end (<= length of reference)
872
+ if isinstance(start, Position):
873
+ self._start = start
874
+ elif isinstance(start, int):
875
+ self._start = ExactPosition(start)
876
+ else:
877
+ raise TypeError(f"start={start!r} {type(start)}")
878
+ if isinstance(end, Position):
879
+ self._end = end
880
+ elif isinstance(end, int):
881
+ self._end = ExactPosition(end)
882
+ else:
883
+ raise TypeError(f"end={end!r} {type(end)}")
884
+ if (
885
+ isinstance(self.start, int)
886
+ and isinstance(self.end, int)
887
+ and self.start > self.end
888
+ ):
889
+ raise ValueError(
890
+ f"End location ({self.end}) must be greater than "
891
+ f"or equal to start location ({self.start})"
892
+ )
893
+ self.strand = strand
894
+ self.ref = ref
895
+ self.ref_db = ref_db
896
+
897
+ @staticmethod
898
+ def fromstring(text, length=None, circular=False):
899
+ """Create a SimpleLocation object from a string."""
900
+ if text.startswith("complement("):
901
+ text = text[11:-1]
902
+ strand = -1
903
+ else:
904
+ strand = None
905
+ # Try simple cases first for speed
906
+ try:
907
+ s, e = text.split("..")
908
+ s = int(s) - 1
909
+ e = int(e)
910
+ except ValueError:
911
+ pass
912
+ else:
913
+ if 0 <= s < e:
914
+ return SimpleLocation(s, e, strand)
915
+ # Try general case
916
+ try:
917
+ ref, text = text.split(":")
918
+ except ValueError:
919
+ ref = None
920
+ m = _re_location_category.match(text)
921
+ if m is None:
922
+ raise LocationParserError(f"Could not parse feature location '{text}'")
923
+ for key, value in m.groupdict().items():
924
+ if value is not None:
925
+ break
926
+ assert value == text
927
+ if key == "bond":
928
+ # e.g. bond(196)
929
+ warnings.warn(
930
+ "Dropping bond qualifier in feature location",
931
+ BiopythonParserWarning,
932
+ )
933
+ text = text[5:-1]
934
+ s_pos = Position.fromstring(text, -1)
935
+ e_pos = Position.fromstring(text)
936
+ elif key == "solo":
937
+ # e.g. "123"
938
+ s_pos = Position.fromstring(text, -1)
939
+ e_pos = Position.fromstring(text)
940
+ elif key in ("pair", "within", "oneof"):
941
+ s, e = text.split("..")
942
+ # Attempt to fix features that span the origin
943
+ s_pos = Position.fromstring(s, -1)
944
+ e_pos = Position.fromstring(e)
945
+ # We have seen Ensembl data in "GenBank Format" with length zero in the LOCUS
946
+ # and variation features with s_pos >= e_pos - they are not origin wrapping!
947
+ if e_pos <= s_pos and length and s_pos < length:
948
+ # Assuming this is meant to be origin wrapping.
949
+ # Create a CompoundLocation of the wrapped feature,
950
+ # consisting of two SimpleLocation objects to extend to
951
+ # the list of feature locations.
952
+ if not circular:
953
+ raise LocationParserError(
954
+ f"it appears that '{text}' is a feature that spans the"
955
+ " origin, but the sequence topology is undefined"
956
+ )
957
+ warnings.warn(
958
+ f"Attempting to fix invalid location {text!r} as it looks"
959
+ " like incorrect origin wrapping. Please fix input file,"
960
+ " this could have unintended behavior.",
961
+ BiopythonParserWarning,
962
+ )
963
+
964
+ f1 = SimpleLocation(s_pos, length, strand)
965
+ f2 = SimpleLocation(0, e_pos, strand)
966
+
967
+ if strand == -1:
968
+ # For complementary features spanning the origin
969
+ return f2 + f1
970
+ else:
971
+ return f1 + f2
972
+ elif key == "between":
973
+ # A between location like "67^68" (one based counting) is a
974
+ # special case (note it has zero length). In python slice
975
+ # notation this is 67:67, a zero length slice. See Bug 2622
976
+ # Further more, on a circular genome of length N you can have
977
+ # a location N^1 meaning the junction at the origin. See Bug 3098.
978
+ # NOTE - We can imagine between locations like "2^4", but this
979
+ # is just "3". Similarly, "2^5" is just "3..4"
980
+ s, e = text.split("^")
981
+ s = int(s)
982
+ e = int(e)
983
+ if s + 1 == e or (s == length and e == 1):
984
+ s_pos = ExactPosition(s)
985
+ e_pos = s_pos
986
+ else:
987
+ raise LocationParserError(f"invalid feature location '{text}'")
988
+ if s_pos < 0:
989
+ raise LocationParserError(
990
+ f"negative starting position in feature location '{text}'"
991
+ )
992
+ return SimpleLocation(s_pos, e_pos, strand, ref=ref)
993
+
994
+ def _get_strand(self):
995
+ """Get function for the strand property (PRIVATE)."""
996
+ return self._strand
997
+
998
+ def _set_strand(self, value):
999
+ """Set function for the strand property (PRIVATE)."""
1000
+ if value not in [+1, -1, 0, None]:
1001
+ raise ValueError(f"Strand should be +1, -1, 0 or None, not {value!r}")
1002
+ self._strand = value
1003
+
1004
+ strand = property(
1005
+ fget=_get_strand,
1006
+ fset=_set_strand,
1007
+ doc="Strand of the location (+1, -1, 0 or None).",
1008
+ )
1009
+
1010
+ def __str__(self):
1011
+ """Return a representation of the SimpleLocation object (with python counting).
1012
+
1013
+ For the simple case this uses the python splicing syntax, [122:150]
1014
+ (zero based counting) which GenBank would call 123..150 (one based
1015
+ counting).
1016
+ """
1017
+ answer = f"[{self._start}:{self._end}]"
1018
+ if self.ref and self.ref_db:
1019
+ answer = f"{self.ref_db}:{self.ref}{answer}"
1020
+ elif self.ref:
1021
+ answer = self.ref + answer
1022
+ # Is ref_db without ref meaningful?
1023
+ if self.strand is None:
1024
+ return answer
1025
+ elif self.strand == +1:
1026
+ return answer + "(+)"
1027
+ elif self.strand == -1:
1028
+ return answer + "(-)"
1029
+ else:
1030
+ # strand = 0, stranded but strand unknown, ? in GFF3
1031
+ return answer + "(?)"
1032
+
1033
+ def __repr__(self):
1034
+ """Represent the SimpleLocation object as a string for debugging."""
1035
+ optional = ""
1036
+ if self.strand is not None:
1037
+ optional += f", strand={self.strand!r}"
1038
+ if self.ref is not None:
1039
+ optional += f", ref={self.ref!r}"
1040
+ if self.ref_db is not None:
1041
+ optional += f", ref_db={self.ref_db!r}"
1042
+ return f"{self.__class__.__name__}({self.start!r}, {self.end!r}{optional})"
1043
+
1044
+ def __add__(self, other):
1045
+ """Combine location with another SimpleLocation object, or shift it.
1046
+
1047
+ You can add two feature locations to make a join CompoundLocation:
1048
+
1049
+ >>> from Bio.SeqFeature import SimpleLocation
1050
+ >>> f1 = SimpleLocation(5, 10)
1051
+ >>> f2 = SimpleLocation(20, 30)
1052
+ >>> combined = f1 + f2
1053
+ >>> print(combined)
1054
+ join{[5:10], [20:30]}
1055
+
1056
+ This is thus equivalent to:
1057
+
1058
+ >>> from Bio.SeqFeature import CompoundLocation
1059
+ >>> join = CompoundLocation([f1, f2])
1060
+ >>> print(join)
1061
+ join{[5:10], [20:30]}
1062
+
1063
+ You can also use sum(...) in this way:
1064
+
1065
+ >>> join = sum([f1, f2])
1066
+ >>> print(join)
1067
+ join{[5:10], [20:30]}
1068
+
1069
+ Furthermore, you can combine a SimpleLocation with a CompoundLocation
1070
+ in this way.
1071
+
1072
+ Separately, adding an integer will give a new SimpleLocation with
1073
+ its start and end offset by that amount. For example:
1074
+
1075
+ >>> print(f1)
1076
+ [5:10]
1077
+ >>> print(f1 + 100)
1078
+ [105:110]
1079
+ >>> print(200 + f1)
1080
+ [205:210]
1081
+
1082
+ This can be useful when editing annotation.
1083
+ """
1084
+ if isinstance(other, SimpleLocation):
1085
+ return CompoundLocation([self, other])
1086
+ elif isinstance(other, int):
1087
+ return self._shift(other)
1088
+ else:
1089
+ # This will allow CompoundLocation's __radd__ to be called:
1090
+ return NotImplemented
1091
+
1092
+ def __radd__(self, other):
1093
+ """Return a SimpleLocation object by shifting the location by an integer amount."""
1094
+ if isinstance(other, int):
1095
+ return self._shift(other)
1096
+ else:
1097
+ return NotImplemented
1098
+
1099
+ def __sub__(self, other):
1100
+ """Subtracting an integer will shift the start and end by that amount.
1101
+
1102
+ >>> from Bio.SeqFeature import SimpleLocation
1103
+ >>> f1 = SimpleLocation(105, 150)
1104
+ >>> print(f1)
1105
+ [105:150]
1106
+ >>> print(f1 - 100)
1107
+ [5:50]
1108
+
1109
+ This can be useful when editing annotation. You can also add an integer
1110
+ to a feature location (which shifts in the opposite direction).
1111
+ """
1112
+ if isinstance(other, int):
1113
+ return self._shift(-other)
1114
+ else:
1115
+ return NotImplemented
1116
+
1117
+ def __nonzero__(self):
1118
+ """Return True regardless of the length of the feature.
1119
+
1120
+ This behavior is for backwards compatibility, since until the
1121
+ __len__ method was added, a SimpleLocation always evaluated as True.
1122
+
1123
+ Note that in comparison, Seq objects, strings, lists, etc, will all
1124
+ evaluate to False if they have length zero.
1125
+
1126
+ WARNING: The SimpleLocation may in future evaluate to False when its
1127
+ length is zero (in order to better match normal python behavior)!
1128
+ """
1129
+ return True
1130
+
1131
+ def __len__(self):
1132
+ """Return the length of the region described by the SimpleLocation object.
1133
+
1134
+ Note that extra care may be needed for fuzzy locations, e.g.
1135
+
1136
+ >>> from Bio.SeqFeature import SimpleLocation
1137
+ >>> from Bio.SeqFeature import BeforePosition, AfterPosition
1138
+ >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
1139
+ >>> len(loc)
1140
+ 5
1141
+ """
1142
+ return int(self._end) - int(self._start)
1143
+
1144
+ def __contains__(self, value):
1145
+ """Check if an integer position is within the SimpleLocation object.
1146
+
1147
+ Note that extra care may be needed for fuzzy locations, e.g.
1148
+
1149
+ >>> from Bio.SeqFeature import SimpleLocation
1150
+ >>> from Bio.SeqFeature import BeforePosition, AfterPosition
1151
+ >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
1152
+ >>> len(loc)
1153
+ 5
1154
+ >>> [i for i in range(15) if i in loc]
1155
+ [5, 6, 7, 8, 9]
1156
+ """
1157
+ if not isinstance(value, int):
1158
+ raise ValueError(
1159
+ "Currently we only support checking for integer "
1160
+ "positions being within a SimpleLocation."
1161
+ )
1162
+ if value < self._start or value >= self._end:
1163
+ return False
1164
+ else:
1165
+ return True
1166
+
1167
+ def __iter__(self):
1168
+ """Iterate over the parent positions within the SimpleLocation object.
1169
+
1170
+ >>> from Bio.SeqFeature import SimpleLocation
1171
+ >>> from Bio.SeqFeature import BeforePosition, AfterPosition
1172
+ >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10))
1173
+ >>> len(loc)
1174
+ 5
1175
+ >>> for i in loc: print(i)
1176
+ 5
1177
+ 6
1178
+ 7
1179
+ 8
1180
+ 9
1181
+ >>> list(loc)
1182
+ [5, 6, 7, 8, 9]
1183
+ >>> [i for i in range(15) if i in loc]
1184
+ [5, 6, 7, 8, 9]
1185
+
1186
+ Note this is strand aware:
1187
+
1188
+ >>> loc = SimpleLocation(BeforePosition(5), AfterPosition(10), strand = -1)
1189
+ >>> list(loc)
1190
+ [9, 8, 7, 6, 5]
1191
+ """
1192
+ if self.strand == -1:
1193
+ yield from range(self._end - 1, self._start - 1, -1)
1194
+ else:
1195
+ yield from range(self._start, self._end)
1196
+
1197
+ def __eq__(self, other):
1198
+ """Implement equality by comparing all the location attributes."""
1199
+ if not isinstance(other, SimpleLocation):
1200
+ return False
1201
+ return (
1202
+ self._start == other.start
1203
+ and self._end == other.end
1204
+ and self._strand == other.strand
1205
+ and self.ref == other.ref
1206
+ and self.ref_db == other.ref_db
1207
+ )
1208
+
1209
+ def _shift(self, offset):
1210
+ """Return a copy of the SimpleLocation shifted by an offset (PRIVATE).
1211
+
1212
+ Returns self when location is relative to an external reference.
1213
+ """
1214
+ # TODO - What if offset is a fuzzy position?
1215
+ if self.ref or self.ref_db:
1216
+ return self
1217
+ return SimpleLocation(
1218
+ start=self._start + offset,
1219
+ end=self._end + offset,
1220
+ strand=self.strand,
1221
+ )
1222
+
1223
+ def _flip(self, length):
1224
+ """Return a copy of the location after the parent is reversed (PRIVATE).
1225
+
1226
+ Returns self when location is relative to an external reference.
1227
+ """
1228
+ if self.ref or self.ref_db:
1229
+ return self
1230
+ # Note this will flip the start and end too!
1231
+ if self.strand == +1:
1232
+ flip_strand = -1
1233
+ elif self.strand == -1:
1234
+ flip_strand = +1
1235
+ else:
1236
+ # 0 or None
1237
+ flip_strand = self.strand
1238
+ return SimpleLocation(
1239
+ start=self._end._flip(length),
1240
+ end=self._start._flip(length),
1241
+ strand=flip_strand,
1242
+ )
1243
+
1244
+ @property
1245
+ def parts(self):
1246
+ """Read only list of sections (always one, the SimpleLocation object).
1247
+
1248
+ This is a convenience property allowing you to write code handling
1249
+ both SimpleLocation objects (with one part) and more complex
1250
+ CompoundLocation objects (with multiple parts) interchangeably.
1251
+ """
1252
+ return [self]
1253
+
1254
+ @property
1255
+ def start(self):
1256
+ """Start location - left most (minimum) value, regardless of strand.
1257
+
1258
+ Read only, returns an integer like position object, possibly a fuzzy
1259
+ position.
1260
+ """
1261
+ return self._start
1262
+
1263
+ @property
1264
+ def end(self):
1265
+ """End location - right most (maximum) value, regardless of strand.
1266
+
1267
+ Read only, returns an integer like position object, possibly a fuzzy
1268
+ position.
1269
+ """
1270
+ return self._end
1271
+
1272
+ def extract(self, parent_sequence, references=None):
1273
+ """Extract the sequence from supplied parent sequence using the SimpleLocation object.
1274
+
1275
+ The parent_sequence can be a Seq like object or a string, and will
1276
+ generally return an object of the same type. The exception to this is
1277
+ a MutableSeq as the parent sequence will return a Seq object.
1278
+ If the location refers to other records, they must be supplied
1279
+ in the optional dictionary references.
1280
+
1281
+ >>> from Bio.Seq import Seq
1282
+ >>> from Bio.SeqFeature import SimpleLocation
1283
+ >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
1284
+ >>> feature_loc = SimpleLocation(8, 15)
1285
+ >>> feature_loc.extract(seq)
1286
+ Seq('VALIVIC')
1287
+
1288
+ """
1289
+ if self.ref or self.ref_db:
1290
+ if not references:
1291
+ raise ValueError(
1292
+ f"Feature references another sequence ({self.ref}),"
1293
+ " references mandatory"
1294
+ )
1295
+ elif self.ref not in references:
1296
+ # KeyError?
1297
+ raise ValueError(
1298
+ f"Feature references another sequence ({self.ref}),"
1299
+ " not found in references"
1300
+ )
1301
+ parent_sequence = references[self.ref]
1302
+ f_seq = parent_sequence[int(self.start) : int(self.end)]
1303
+ if isinstance(f_seq, MutableSeq):
1304
+ f_seq = Seq(f_seq)
1305
+ if self.strand == -1:
1306
+ f_seq = reverse_complement(f_seq)
1307
+ return f_seq
1308
+
1309
+
1310
+ FeatureLocation = SimpleLocation # OBSOLETE; for backward compatibility only.
1311
+
1312
+
1313
+ class CompoundLocation(Location):
1314
+ """For handling joins etc where a feature location has several parts."""
1315
+
1316
+ def __init__(self, parts, operator="join"):
1317
+ """Initialize the class.
1318
+
1319
+ >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
1320
+ >>> f1 = SimpleLocation(10, 40, strand=+1)
1321
+ >>> f2 = SimpleLocation(50, 59, strand=+1)
1322
+ >>> f = CompoundLocation([f1, f2])
1323
+ >>> len(f) == len(f1) + len(f2) == 39 == len(list(f))
1324
+ True
1325
+ >>> print(f.operator)
1326
+ join
1327
+ >>> 5 in f
1328
+ False
1329
+ >>> 15 in f
1330
+ True
1331
+ >>> f.strand
1332
+ 1
1333
+
1334
+ Notice that the strand of the compound location is computed
1335
+ automatically - in the case of mixed strands on the sub-locations
1336
+ the overall strand is set to None.
1337
+
1338
+ >>> f = CompoundLocation([SimpleLocation(3, 6, strand=+1),
1339
+ ... SimpleLocation(10, 13, strand=-1)])
1340
+ >>> print(f.strand)
1341
+ None
1342
+ >>> len(f)
1343
+ 6
1344
+ >>> list(f)
1345
+ [3, 4, 5, 12, 11, 10]
1346
+
1347
+ The example above doing list(f) iterates over the coordinates within the
1348
+ feature. This allows you to use max and min on the location, to find the
1349
+ range covered:
1350
+
1351
+ >>> min(f)
1352
+ 3
1353
+ >>> max(f)
1354
+ 12
1355
+
1356
+ More generally, you can use the compound location's start and end which
1357
+ give the full span covered, 0 <= start <= end <= full sequence length.
1358
+
1359
+ >>> f.start == min(f)
1360
+ True
1361
+ >>> f.end == max(f) + 1
1362
+ True
1363
+
1364
+ This is consistent with the behavior of the SimpleLocation for a single
1365
+ region, where again the 'start' and 'end' do not necessarily give the
1366
+ biological start and end, but rather the 'minimal' and 'maximal'
1367
+ coordinate boundaries.
1368
+
1369
+ Note that adding locations provides a more intuitive method of
1370
+ construction:
1371
+
1372
+ >>> f = SimpleLocation(3, 6, strand=+1) + SimpleLocation(10, 13, strand=-1)
1373
+ >>> len(f)
1374
+ 6
1375
+ >>> list(f)
1376
+ [3, 4, 5, 12, 11, 10]
1377
+ """
1378
+ self.operator = operator
1379
+ self.parts = list(parts)
1380
+ for loc in self.parts:
1381
+ if not isinstance(loc, SimpleLocation):
1382
+ raise ValueError(
1383
+ "CompoundLocation should be given a list of "
1384
+ "SimpleLocation objects, not %s" % loc.__class__
1385
+ )
1386
+ if len(parts) < 2:
1387
+ raise ValueError(
1388
+ f"CompoundLocation should have at least 2 parts, not {parts!r}"
1389
+ )
1390
+
1391
+ def __str__(self):
1392
+ """Return a representation of the CompoundLocation object (with python counting)."""
1393
+ return "%s{%s}" % (self.operator, ", ".join(str(loc) for loc in self.parts))
1394
+
1395
+ def __repr__(self):
1396
+ """Represent the CompoundLocation object as string for debugging."""
1397
+ return f"{self.__class__.__name__}({self.parts!r}, {self.operator!r})"
1398
+
1399
+ def _get_strand(self):
1400
+ """Get function for the strand property (PRIVATE)."""
1401
+ # Historically a join on the reverse strand has been represented
1402
+ # in Biopython with both the parent SeqFeature and its children
1403
+ # (the exons for a CDS) all given a strand of -1. Likewise, for
1404
+ # a join feature on the forward strand they all have strand +1.
1405
+ # However, we must also consider evil mixed strand examples like
1406
+ # this, join(complement(69611..69724),139856..140087,140625..140650)
1407
+ if len({loc.strand for loc in self.parts}) == 1:
1408
+ return self.parts[0].strand
1409
+ else:
1410
+ return None # i.e. mixed strands
1411
+
1412
+ def _set_strand(self, value):
1413
+ """Set function for the strand property (PRIVATE)."""
1414
+ # Should this be allowed/encouraged?
1415
+ for loc in self.parts:
1416
+ loc.strand = value
1417
+
1418
+ strand = property(
1419
+ fget=_get_strand,
1420
+ fset=_set_strand,
1421
+ doc="""Overall strand of the compound location.
1422
+
1423
+ If all the parts have the same strand, that is returned. Otherwise
1424
+ for mixed strands, this returns None.
1425
+
1426
+ >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
1427
+ >>> f1 = SimpleLocation(15, 17, strand=1)
1428
+ >>> f2 = SimpleLocation(20, 30, strand=-1)
1429
+ >>> f = f1 + f2
1430
+ >>> f1.strand
1431
+ 1
1432
+ >>> f2.strand
1433
+ -1
1434
+ >>> f.strand
1435
+ >>> f.strand is None
1436
+ True
1437
+
1438
+ If you set the strand of a CompoundLocation, this is applied to
1439
+ all the parts - use with caution:
1440
+
1441
+ >>> f.strand = 1
1442
+ >>> f1.strand
1443
+ 1
1444
+ >>> f2.strand
1445
+ 1
1446
+ >>> f.strand
1447
+ 1
1448
+
1449
+ """,
1450
+ )
1451
+
1452
+ def __add__(self, other):
1453
+ """Combine locations, or shift the location by an integer offset.
1454
+
1455
+ >>> from Bio.SeqFeature import SimpleLocation
1456
+ >>> f1 = SimpleLocation(15, 17) + SimpleLocation(20, 30)
1457
+ >>> print(f1)
1458
+ join{[15:17], [20:30]}
1459
+
1460
+ You can add another SimpleLocation:
1461
+
1462
+ >>> print(f1 + SimpleLocation(40, 50))
1463
+ join{[15:17], [20:30], [40:50]}
1464
+ >>> print(SimpleLocation(5, 10) + f1)
1465
+ join{[5:10], [15:17], [20:30]}
1466
+
1467
+ You can also add another CompoundLocation:
1468
+
1469
+ >>> f2 = SimpleLocation(40, 50) + SimpleLocation(60, 70)
1470
+ >>> print(f2)
1471
+ join{[40:50], [60:70]}
1472
+ >>> print(f1 + f2)
1473
+ join{[15:17], [20:30], [40:50], [60:70]}
1474
+
1475
+ Also, as with the SimpleLocation, adding an integer shifts the
1476
+ location's coordinates by that offset:
1477
+
1478
+ >>> print(f1 + 100)
1479
+ join{[115:117], [120:130]}
1480
+ >>> print(200 + f1)
1481
+ join{[215:217], [220:230]}
1482
+ >>> print(f1 + (-5))
1483
+ join{[10:12], [15:25]}
1484
+ """
1485
+ if isinstance(other, SimpleLocation):
1486
+ return CompoundLocation(self.parts + [other], self.operator)
1487
+ elif isinstance(other, CompoundLocation):
1488
+ if self.operator != other.operator:
1489
+ # Handle join+order -> order as a special case?
1490
+ raise ValueError(
1491
+ f"Mixed operators {self.operator} and {other.operator}"
1492
+ )
1493
+ return CompoundLocation(self.parts + other.parts, self.operator)
1494
+ elif isinstance(other, int):
1495
+ return self._shift(other)
1496
+ else:
1497
+ raise NotImplementedError
1498
+
1499
+ def __radd__(self, other):
1500
+ """Add a feature to the left."""
1501
+ if isinstance(other, SimpleLocation):
1502
+ return CompoundLocation([other] + self.parts, self.operator)
1503
+ elif isinstance(other, int):
1504
+ return self._shift(other)
1505
+ else:
1506
+ raise NotImplementedError
1507
+
1508
+ def __contains__(self, value):
1509
+ """Check if an integer position is within the CompoundLocation object."""
1510
+ for loc in self.parts:
1511
+ if value in loc:
1512
+ return True
1513
+ return False
1514
+
1515
+ def __nonzero__(self):
1516
+ """Return True regardless of the length of the feature.
1517
+
1518
+ This behavior is for backwards compatibility, since until the
1519
+ __len__ method was added, a SimpleLocation always evaluated as True.
1520
+
1521
+ Note that in comparison, Seq objects, strings, lists, etc, will all
1522
+ evaluate to False if they have length zero.
1523
+
1524
+ WARNING: The SimpleLocation may in future evaluate to False when its
1525
+ length is zero (in order to better match normal python behavior)!
1526
+ """
1527
+ return True
1528
+
1529
+ def __len__(self):
1530
+ """Return the length of the CompoundLocation object."""
1531
+ return sum(len(loc) for loc in self.parts)
1532
+
1533
+ def __iter__(self):
1534
+ """Iterate over the parent positions within the CompoundLocation object."""
1535
+ for loc in self.parts:
1536
+ yield from loc
1537
+
1538
+ def __eq__(self, other):
1539
+ """Check if all parts of CompoundLocation are equal to all parts of other CompoundLocation."""
1540
+ if not isinstance(other, CompoundLocation):
1541
+ return False
1542
+ if len(self.parts) != len(other.parts):
1543
+ return False
1544
+ if self.operator != other.operator:
1545
+ return False
1546
+ for self_part, other_part in zip(self.parts, other.parts):
1547
+ if self_part != other_part:
1548
+ return False
1549
+ return True
1550
+
1551
+ def _shift(self, offset):
1552
+ """Return a copy of the CompoundLocation shifted by an offset (PRIVATE)."""
1553
+ return CompoundLocation(
1554
+ [loc._shift(offset) for loc in self.parts], self.operator
1555
+ )
1556
+
1557
+ def _flip(self, length):
1558
+ """Return a copy of the locations after the parent is reversed (PRIVATE).
1559
+
1560
+ Note that the order of the parts is NOT reversed unless all parts
1561
+ have strand=None, since the order has meaning for stranded features.
1562
+ Consider a CDS on the forward strand with exons small, medium
1563
+ and large (in length). Once we change the frame of reference
1564
+ to the reverse complement strand, the start codon is still part of
1565
+ the small exon, and the stop codon still part of the large exon -
1566
+ so the part order remains the same!
1567
+
1568
+ Here is an artificial example, were the features map to the two upper
1569
+ case regions and the lower case runs of n are not used:
1570
+
1571
+ >>> from Bio.Seq import Seq
1572
+ >>> from Bio.SeqFeature import SimpleLocation
1573
+ >>> dna = Seq("nnnnnAGCATCCTGCTGTACnnnnnnnnGAGAMTGCCATGCCCCTGGAGTGAnnnnn")
1574
+ >>> small = SimpleLocation(5, 20, strand=1)
1575
+ >>> large = SimpleLocation(28, 52, strand=1)
1576
+ >>> location = small + large
1577
+ >>> print(small)
1578
+ [5:20](+)
1579
+ >>> print(large)
1580
+ [28:52](+)
1581
+ >>> print(location)
1582
+ join{[5:20](+), [28:52](+)}
1583
+ >>> for part in location.parts:
1584
+ ... print(len(part))
1585
+ ...
1586
+ 15
1587
+ 24
1588
+
1589
+ As you can see, this is a silly example where each "exon" is a word:
1590
+
1591
+ >>> print(small.extract(dna).translate())
1592
+ SILLY
1593
+ >>> print(large.extract(dna).translate())
1594
+ EXAMPLE*
1595
+ >>> print(location.extract(dna).translate())
1596
+ SILLYEXAMPLE*
1597
+ >>> for part in location.parts:
1598
+ ... print(part.extract(dna).translate())
1599
+ ...
1600
+ SILLY
1601
+ EXAMPLE*
1602
+
1603
+ Now, let's look at this from the reverse strand frame of reference:
1604
+
1605
+ >>> flipped_dna = dna.reverse_complement()
1606
+ >>> flipped_location = location._flip(len(dna))
1607
+ >>> print(flipped_location.extract(flipped_dna).translate())
1608
+ SILLYEXAMPLE*
1609
+ >>> for part in flipped_location.parts:
1610
+ ... print(part.extract(flipped_dna).translate())
1611
+ ...
1612
+ SILLY
1613
+ EXAMPLE*
1614
+
1615
+ The key point here is the first part of the CompoundFeature is still the
1616
+ small exon, while the second part is still the large exon:
1617
+
1618
+ >>> for part in flipped_location.parts:
1619
+ ... print(len(part))
1620
+ ...
1621
+ 15
1622
+ 24
1623
+ >>> print(flipped_location)
1624
+ join{[37:52](-), [5:29](-)}
1625
+
1626
+ Notice the parts are not reversed. However, there was a bug here in older
1627
+ versions of Biopython which would have given join{[5:29](-), [37:52](-)}
1628
+ and the translation would have wrongly been "EXAMPLE*SILLY" instead.
1629
+
1630
+ When all the parts have strand None, the order of the parts is reversed.
1631
+ In principle this does not change the meaning of the location, but improves
1632
+ the representation of feature locations spanning the origin in circular
1633
+ molecules.
1634
+
1635
+ >>> loc = SimpleLocation(4, 6, None) + SimpleLocation(0, 1, None)
1636
+ >>> print(loc)
1637
+ join{[4:6], [0:1]}
1638
+ >>> print(loc._flip(6))
1639
+ join{[5:6], [0:2]}
1640
+
1641
+ join{[0:2], [5:6]} would not be properly represented in SnapGene, Benchling, etc.
1642
+ """
1643
+ if all(loc.strand is None for loc in self.parts):
1644
+ return CompoundLocation(
1645
+ [loc._flip(length) for loc in self.parts[::-1]], self.operator
1646
+ )
1647
+ else:
1648
+ return CompoundLocation(
1649
+ [loc._flip(length) for loc in self.parts], self.operator
1650
+ )
1651
+
1652
+ @property
1653
+ def start(self):
1654
+ """Start location - left most (minimum) value, regardless of strand.
1655
+
1656
+ Read only, returns an integer like position object, possibly a fuzzy
1657
+ position.
1658
+
1659
+ For the special case of a CompoundLocation wrapping the origin of a
1660
+ circular genome, this will return zero.
1661
+ """
1662
+ return min(loc.start for loc in self.parts)
1663
+
1664
+ @property
1665
+ def end(self):
1666
+ """End location - right most (maximum) value, regardless of strand.
1667
+
1668
+ Read only, returns an integer like position object, possibly a fuzzy
1669
+ position.
1670
+
1671
+ For the special case of a CompoundLocation wrapping the origin of
1672
+ a circular genome this will match the genome length.
1673
+ """
1674
+ return max(loc.end for loc in self.parts)
1675
+
1676
+ @property
1677
+ def ref(self):
1678
+ """Not present in CompoundLocation, dummy method for API compatibility."""
1679
+ return None
1680
+
1681
+ @property
1682
+ def ref_db(self):
1683
+ """Not present in CompoundLocation, dummy method for API compatibility."""
1684
+ return None
1685
+
1686
+ def extract(self, parent_sequence, references=None):
1687
+ """Extract the sequence from supplied parent sequence using the CompoundLocation object.
1688
+
1689
+ The parent_sequence can be a Seq like object or a string, and will
1690
+ generally return an object of the same type. The exception to this is
1691
+ a MutableSeq as the parent sequence will return a Seq object.
1692
+ If the location refers to other records, they must be supplied
1693
+ in the optional dictionary references.
1694
+
1695
+ >>> from Bio.Seq import Seq
1696
+ >>> from Bio.SeqFeature import SimpleLocation, CompoundLocation
1697
+ >>> seq = Seq("MKQHKAMIVALIVICITAVVAAL")
1698
+ >>> fl1 = SimpleLocation(2, 8)
1699
+ >>> fl2 = SimpleLocation(10, 15)
1700
+ >>> fl3 = CompoundLocation([fl1,fl2])
1701
+ >>> fl3.extract(seq)
1702
+ Seq('QHKAMILIVIC')
1703
+
1704
+ """
1705
+ # This copes with mixed strand features & all on reverse:
1706
+ parts = [
1707
+ loc.extract(parent_sequence, references=references) for loc in self.parts
1708
+ ]
1709
+ f_seq = functools.reduce(lambda x, y: x + y, parts)
1710
+ return f_seq
1711
+
1712
+
1713
+ class Position(ABC):
1714
+ """Abstract base class representing a position."""
1715
+
1716
+ @abstractmethod
1717
+ def __repr__(self):
1718
+ """Represent the Position object as a string for debugging."""
1719
+ return f"{self.__class__.__name__}(...)"
1720
+
1721
+ @staticmethod
1722
+ def fromstring(text, offset=0):
1723
+ """Build a Position object from the text string.
1724
+
1725
+ For an end position, leave offset as zero (default):
1726
+
1727
+ >>> Position.fromstring("5")
1728
+ ExactPosition(5)
1729
+
1730
+ For a start position, set offset to minus one (for Python counting):
1731
+
1732
+ >>> Position.fromstring("5", -1)
1733
+ ExactPosition(4)
1734
+
1735
+ This also covers fuzzy positions:
1736
+
1737
+ >>> p = Position.fromstring("<5")
1738
+ >>> p
1739
+ BeforePosition(5)
1740
+ >>> print(p)
1741
+ <5
1742
+ >>> int(p)
1743
+ 5
1744
+
1745
+ >>> Position.fromstring(">5")
1746
+ AfterPosition(5)
1747
+
1748
+ By default assumes an end position, so note the integer behavior:
1749
+
1750
+ >>> p = Position.fromstring("one-of(5,8,11)")
1751
+ >>> p
1752
+ OneOfPosition(11, choices=[ExactPosition(5), ExactPosition(8), ExactPosition(11)])
1753
+ >>> print(p)
1754
+ one-of(5,8,11)
1755
+ >>> int(p)
1756
+ 11
1757
+
1758
+ >>> Position.fromstring("(8.10)")
1759
+ WithinPosition(10, left=8, right=10)
1760
+
1761
+ Fuzzy start positions:
1762
+
1763
+ >>> p = Position.fromstring("<5", -1)
1764
+ >>> p
1765
+ BeforePosition(4)
1766
+ >>> print(p)
1767
+ <4
1768
+ >>> int(p)
1769
+ 4
1770
+
1771
+ Notice how the integer behavior changes too!
1772
+
1773
+ >>> p = Position.fromstring("one-of(5,8,11)", -1)
1774
+ >>> p
1775
+ OneOfPosition(4, choices=[ExactPosition(4), ExactPosition(7), ExactPosition(10)])
1776
+ >>> print(p)
1777
+ one-of(4,7,10)
1778
+ >>> int(p)
1779
+ 4
1780
+
1781
+ """
1782
+ if offset != 0 and offset != -1:
1783
+ raise ValueError(
1784
+ "To convert one-based indices to zero-based indices, offset must be either 0 (for end positions) or -1 (for start positions)."
1785
+ )
1786
+ if text == "?":
1787
+ return UnknownPosition()
1788
+ if text.startswith("?"):
1789
+ return UncertainPosition(int(text[1:]) + offset)
1790
+ if text.startswith("<"):
1791
+ return BeforePosition(int(text[1:]) + offset)
1792
+ if text.startswith(">"):
1793
+ return AfterPosition(int(text[1:]) + offset)
1794
+ m = _re_within_position.match(text)
1795
+ if m is not None:
1796
+ s, e = m.groups()
1797
+ s = int(s) + offset
1798
+ e = int(e) + offset
1799
+ if offset == -1:
1800
+ default = s
1801
+ else:
1802
+ default = e
1803
+ return WithinPosition(default, left=s, right=e)
1804
+ m = _re_oneof_position.match(text)
1805
+ if m is not None:
1806
+ positions = m.groups()[0]
1807
+ parts = [ExactPosition(int(pos) + offset) for pos in positions.split(",")]
1808
+ if offset == -1:
1809
+ default = min(int(pos) for pos in parts)
1810
+ else:
1811
+ default = max(int(pos) for pos in parts)
1812
+ return OneOfPosition(default, choices=parts)
1813
+ return ExactPosition(int(text) + offset)
1814
+
1815
+
1816
+ class ExactPosition(int, Position):
1817
+ """Specify the specific position of a boundary.
1818
+
1819
+ Arguments:
1820
+ - position - The position of the boundary.
1821
+ - extension - An optional argument which must be zero since we don't
1822
+ have an extension. The argument is provided so that the same number
1823
+ of arguments can be passed to all position types.
1824
+
1825
+ In this case, there is no fuzziness associated with the position.
1826
+
1827
+ >>> p = ExactPosition(5)
1828
+ >>> p
1829
+ ExactPosition(5)
1830
+ >>> print(p)
1831
+ 5
1832
+
1833
+ >>> isinstance(p, Position)
1834
+ True
1835
+ >>> isinstance(p, int)
1836
+ True
1837
+
1838
+ Integer comparisons and operations should work as expected:
1839
+
1840
+ >>> p == 5
1841
+ True
1842
+ >>> p < 6
1843
+ True
1844
+ >>> p <= 5
1845
+ True
1846
+ >>> p + 10
1847
+ ExactPosition(15)
1848
+
1849
+ """
1850
+
1851
+ def __new__(cls, position, extension=0):
1852
+ """Create an ExactPosition object."""
1853
+ if extension != 0:
1854
+ raise AttributeError(f"Non-zero extension {extension} for exact position.")
1855
+ return int.__new__(cls, position)
1856
+
1857
+ # Must define this on Python 3.8 onwards because we redefine __repr__
1858
+ def __str__(self):
1859
+ """Return a representation of the ExactPosition object (with python counting)."""
1860
+ return str(int(self))
1861
+
1862
+ def __repr__(self):
1863
+ """Represent the ExactPosition object as a string for debugging."""
1864
+ return "%s(%i)" % (self.__class__.__name__, int(self))
1865
+
1866
+ def __add__(self, offset):
1867
+ """Return a copy of the position object with its location shifted (PRIVATE)."""
1868
+ # By default preserve any subclass
1869
+ return self.__class__(int(self) + offset)
1870
+
1871
+ def _flip(self, length):
1872
+ """Return a copy of the location after the parent is reversed (PRIVATE)."""
1873
+ # By default preserve any subclass
1874
+ return self.__class__(length - int(self))
1875
+
1876
+
1877
+ class UncertainPosition(ExactPosition):
1878
+ """Specify a specific position which is uncertain.
1879
+
1880
+ This is used in UniProt, e.g. ?222 for uncertain position 222, or in the
1881
+ XML format explicitly marked as uncertain. Does not apply to GenBank/EMBL.
1882
+ """
1883
+
1884
+
1885
+ class UnknownPosition(Position):
1886
+ """Specify a specific position which is unknown (has no position).
1887
+
1888
+ This is used in UniProt, e.g. ? or in the XML as unknown.
1889
+ """
1890
+
1891
+ def __repr__(self):
1892
+ """Represent the UnknownPosition object as a string for debugging."""
1893
+ return f"{self.__class__.__name__}()"
1894
+
1895
+ def __hash__(self):
1896
+ """Return the hash value of the UnknownPosition object."""
1897
+ return hash(None)
1898
+
1899
+ def __add__(self, offset):
1900
+ """Return a copy of the position object with its location shifted (PRIVATE)."""
1901
+ return self
1902
+
1903
+ def _flip(self, length):
1904
+ """Return a copy of the location after the parent is reversed (PRIVATE)."""
1905
+ return self
1906
+
1907
+
1908
+ class WithinPosition(int, Position):
1909
+ """Specify the position of a boundary within some coordinates.
1910
+
1911
+ Arguments:
1912
+ - position - The default integer position
1913
+ - left - The start (left) position of the boundary
1914
+ - right - The end (right) position of the boundary
1915
+
1916
+ This allows dealing with a location like ((11.14)..100). This
1917
+ indicates that the start of the sequence is somewhere between 11
1918
+ and 14. Since this is a start coordinate, it should act like
1919
+ it is at position 11 (or in Python counting, 10).
1920
+
1921
+ >>> p = WithinPosition(10, 10, 13)
1922
+ >>> p
1923
+ WithinPosition(10, left=10, right=13)
1924
+ >>> print(p)
1925
+ (10.13)
1926
+ >>> int(p)
1927
+ 10
1928
+
1929
+ Basic integer comparisons and operations should work as though
1930
+ this were a plain integer:
1931
+
1932
+ >>> p == 10
1933
+ True
1934
+ >>> p in [9, 10, 11]
1935
+ True
1936
+ >>> p < 11
1937
+ True
1938
+ >>> p + 10
1939
+ WithinPosition(20, left=20, right=23)
1940
+
1941
+ >>> isinstance(p, WithinPosition)
1942
+ True
1943
+ >>> isinstance(p, Position)
1944
+ True
1945
+ >>> isinstance(p, int)
1946
+ True
1947
+
1948
+ Note this also applies for comparison to other position objects,
1949
+ where again the integer behavior is used:
1950
+
1951
+ >>> p == 10
1952
+ True
1953
+ >>> p == ExactPosition(10)
1954
+ True
1955
+ >>> p == BeforePosition(10)
1956
+ True
1957
+ >>> p == AfterPosition(10)
1958
+ True
1959
+
1960
+ If this were an end point, you would want the position to be 13
1961
+ (the right/larger value, not the left/smaller value as above):
1962
+
1963
+ >>> p2 = WithinPosition(13, 10, 13)
1964
+ >>> p2
1965
+ WithinPosition(13, left=10, right=13)
1966
+ >>> print(p2)
1967
+ (10.13)
1968
+ >>> int(p2)
1969
+ 13
1970
+ >>> p2 == 13
1971
+ True
1972
+ >>> p2 == ExactPosition(13)
1973
+ True
1974
+
1975
+ """
1976
+
1977
+ def __new__(cls, position, left, right):
1978
+ """Create a WithinPosition object."""
1979
+ if not (position == left or position == right):
1980
+ raise RuntimeError(
1981
+ "WithinPosition: %r should match left %r or "
1982
+ "right %r" % (position, left, right)
1983
+ )
1984
+ obj = int.__new__(cls, position)
1985
+ obj._left = left
1986
+ obj._right = right
1987
+ return obj
1988
+
1989
+ def __getnewargs__(self):
1990
+ """Return the arguments accepted by __new__.
1991
+
1992
+ Necessary to allow pickling and unpickling of class instances.
1993
+ """
1994
+ return (int(self), self._left, self._right)
1995
+
1996
+ def __repr__(self):
1997
+ """Represent the WithinPosition object as a string for debugging."""
1998
+ return "%s(%i, left=%i, right=%i)" % (
1999
+ self.__class__.__name__,
2000
+ int(self),
2001
+ self._left,
2002
+ self._right,
2003
+ )
2004
+
2005
+ def __str__(self):
2006
+ """Return a representation of the WithinPosition object (with python counting)."""
2007
+ return f"({self._left}.{self._right})"
2008
+
2009
+ def __add__(self, offset):
2010
+ """Return a copy of the position object with its location shifted."""
2011
+ return self.__class__(
2012
+ int(self) + offset, self._left + offset, self._right + offset
2013
+ )
2014
+
2015
+ def _flip(self, length):
2016
+ """Return a copy of the location after the parent is reversed (PRIVATE)."""
2017
+ return self.__class__(
2018
+ length - int(self), length - self._right, length - self._left
2019
+ )
2020
+
2021
+
2022
+ class BetweenPosition(int, Position):
2023
+ """Specify the position of a boundary between two coordinates (OBSOLETE?).
2024
+
2025
+ Arguments:
2026
+ - position - The default integer position
2027
+ - left - The start (left) position of the boundary
2028
+ - right - The end (right) position of the boundary
2029
+
2030
+ This allows dealing with a position like 123^456. This
2031
+ indicates that the start of the sequence is somewhere between
2032
+ 123 and 456. It is up to the parser to set the position argument
2033
+ to either boundary point (depending on if this is being used as
2034
+ a start or end of the feature). For example as a feature end:
2035
+
2036
+ >>> p = BetweenPosition(456, 123, 456)
2037
+ >>> p
2038
+ BetweenPosition(456, left=123, right=456)
2039
+ >>> print(p)
2040
+ (123^456)
2041
+ >>> int(p)
2042
+ 456
2043
+
2044
+ Integer equality and comparison use the given position,
2045
+
2046
+ >>> p == 456
2047
+ True
2048
+ >>> p in [455, 456, 457]
2049
+ True
2050
+ >>> p > 300
2051
+ True
2052
+
2053
+ The old legacy properties of position and extension give the
2054
+ starting/lower/left position as an integer, and the distance
2055
+ to the ending/higher/right position as an integer. Note that
2056
+ the position object will act like either the left or the right
2057
+ end-point depending on how it was created:
2058
+
2059
+ >>> p2 = BetweenPosition(123, left=123, right=456)
2060
+ >>> int(p) == int(p2)
2061
+ False
2062
+ >>> p == 456
2063
+ True
2064
+ >>> p2 == 123
2065
+ True
2066
+
2067
+ Note this potentially surprising behavior:
2068
+
2069
+ >>> BetweenPosition(123, left=123, right=456) == ExactPosition(123)
2070
+ True
2071
+ >>> BetweenPosition(123, left=123, right=456) == BeforePosition(123)
2072
+ True
2073
+ >>> BetweenPosition(123, left=123, right=456) == AfterPosition(123)
2074
+ True
2075
+
2076
+ i.e. For equality (and sorting) the position objects behave like
2077
+ integers.
2078
+
2079
+ """
2080
+
2081
+ def __new__(cls, position, left, right):
2082
+ """Create a new instance in BetweenPosition object."""
2083
+ assert position == left or position == right
2084
+ # TODO - public API for getting left/right, especially the unknown one
2085
+ obj = int.__new__(cls, position)
2086
+ obj._left = left
2087
+ obj._right = right
2088
+ return obj
2089
+
2090
+ def __getnewargs__(self):
2091
+ """Return the arguments accepted by __new__.
2092
+
2093
+ Necessary to allow pickling and unpickling of class instances.
2094
+ """
2095
+ return (int(self), self._left, self._right)
2096
+
2097
+ def __repr__(self):
2098
+ """Represent the BetweenPosition object as a string for debugging."""
2099
+ return "%s(%i, left=%i, right=%i)" % (
2100
+ self.__class__.__name__,
2101
+ int(self),
2102
+ self._left,
2103
+ self._right,
2104
+ )
2105
+
2106
+ def __str__(self):
2107
+ """Return a representation of the BetweenPosition object (with python counting)."""
2108
+ return f"({self._left}^{self._right})"
2109
+
2110
+ def __add__(self, offset):
2111
+ """Return a copy of the position object with its location shifted (PRIVATE)."""
2112
+ return self.__class__(
2113
+ int(self) + offset, self._left + offset, self._right + offset
2114
+ )
2115
+
2116
+ def _flip(self, length):
2117
+ """Return a copy of the location after the parent is reversed (PRIVATE)."""
2118
+ return self.__class__(
2119
+ length - int(self), length - self._right, length - self._left
2120
+ )
2121
+
2122
+
2123
+ class BeforePosition(int, Position):
2124
+ """Specify a position where the actual location occurs before it.
2125
+
2126
+ Arguments:
2127
+ - position - The upper boundary of where the location can occur.
2128
+ - extension - An optional argument which must be zero since we don't
2129
+ have an extension. The argument is provided so that the same number
2130
+ of arguments can be passed to all position types.
2131
+
2132
+ This is used to specify positions like (<10..100) where the location
2133
+ occurs somewhere before position 10.
2134
+
2135
+ >>> p = BeforePosition(5)
2136
+ >>> p
2137
+ BeforePosition(5)
2138
+ >>> print(p)
2139
+ <5
2140
+ >>> int(p)
2141
+ 5
2142
+ >>> p + 10
2143
+ BeforePosition(15)
2144
+
2145
+ Note this potentially surprising behavior:
2146
+
2147
+ >>> p == ExactPosition(5)
2148
+ True
2149
+ >>> p == AfterPosition(5)
2150
+ True
2151
+
2152
+ Just remember that for equality and sorting the position objects act
2153
+ like integers.
2154
+ """
2155
+
2156
+ # Subclasses int so can't use __init__
2157
+ def __new__(cls, position, extension=0):
2158
+ """Create a new instance in BeforePosition object."""
2159
+ if extension != 0:
2160
+ raise AttributeError(f"Non-zero extension {extension} for exact position.")
2161
+ return int.__new__(cls, position)
2162
+
2163
+ def __repr__(self):
2164
+ """Represent the location as a string for debugging."""
2165
+ return "%s(%i)" % (self.__class__.__name__, int(self))
2166
+
2167
+ def __str__(self):
2168
+ """Return a representation of the BeforePosition object (with python counting)."""
2169
+ return f"<{int(self)}"
2170
+
2171
+ def __add__(self, offset):
2172
+ """Return a copy of the position object with its location shifted (PRIVATE)."""
2173
+ return self.__class__(int(self) + offset)
2174
+
2175
+ def _flip(self, length):
2176
+ """Return a copy of the location after the parent is reversed (PRIVATE)."""
2177
+ return AfterPosition(length - int(self))
2178
+
2179
+
2180
+ class AfterPosition(int, Position):
2181
+ """Specify a position where the actual location is found after it.
2182
+
2183
+ Arguments:
2184
+ - position - The lower boundary of where the location can occur.
2185
+ - extension - An optional argument which must be zero since we don't
2186
+ have an extension. The argument is provided so that the same number
2187
+ of arguments can be passed to all position types.
2188
+
2189
+ This is used to specify positions like (>10..100) where the location
2190
+ occurs somewhere after position 10.
2191
+
2192
+ >>> p = AfterPosition(7)
2193
+ >>> p
2194
+ AfterPosition(7)
2195
+ >>> print(p)
2196
+ >7
2197
+ >>> int(p)
2198
+ 7
2199
+ >>> p + 10
2200
+ AfterPosition(17)
2201
+
2202
+ >>> isinstance(p, AfterPosition)
2203
+ True
2204
+ >>> isinstance(p, Position)
2205
+ True
2206
+ >>> isinstance(p, int)
2207
+ True
2208
+
2209
+ Note this potentially surprising behavior:
2210
+
2211
+ >>> p == ExactPosition(7)
2212
+ True
2213
+ >>> p == BeforePosition(7)
2214
+ True
2215
+
2216
+ Just remember that for equality and sorting the position objects act
2217
+ like integers.
2218
+ """
2219
+
2220
+ # Subclasses int so can't use __init__
2221
+ def __new__(cls, position, extension=0):
2222
+ """Create a new instance of the AfterPosition object."""
2223
+ if extension != 0:
2224
+ raise AttributeError(f"Non-zero extension {extension} for exact position.")
2225
+ return int.__new__(cls, position)
2226
+
2227
+ def __repr__(self):
2228
+ """Represent the location as a string for debugging."""
2229
+ return "%s(%i)" % (self.__class__.__name__, int(self))
2230
+
2231
+ def __str__(self):
2232
+ """Return a representation of the AfterPosition object (with python counting)."""
2233
+ return f">{int(self)}"
2234
+
2235
+ def __add__(self, offset):
2236
+ """Return a copy of the position object with its location shifted (PRIVATE)."""
2237
+ return self.__class__(int(self) + offset)
2238
+
2239
+ def _flip(self, length):
2240
+ """Return a copy of the location after the parent is reversed (PRIVATE)."""
2241
+ return BeforePosition(length - int(self))
2242
+
2243
+
2244
+ class OneOfPosition(int, Position):
2245
+ """Specify a position where the location can be multiple positions.
2246
+
2247
+ This models the GenBank 'one-of(1888,1901)' function, and tries
2248
+ to make this fit within the Biopython Position models. If this was
2249
+ a start position it should act like 1888, but as an end position 1901.
2250
+
2251
+ >>> p = OneOfPosition(1888, [ExactPosition(1888), ExactPosition(1901)])
2252
+ >>> p
2253
+ OneOfPosition(1888, choices=[ExactPosition(1888), ExactPosition(1901)])
2254
+ >>> int(p)
2255
+ 1888
2256
+
2257
+ Integer comparisons and operators act like using int(p),
2258
+
2259
+ >>> p == 1888
2260
+ True
2261
+ >>> p <= 1888
2262
+ True
2263
+ >>> p > 1888
2264
+ False
2265
+ >>> p + 100
2266
+ OneOfPosition(1988, choices=[ExactPosition(1988), ExactPosition(2001)])
2267
+
2268
+ >>> isinstance(p, OneOfPosition)
2269
+ True
2270
+ >>> isinstance(p, Position)
2271
+ True
2272
+ >>> isinstance(p, int)
2273
+ True
2274
+
2275
+ """
2276
+
2277
+ def __new__(cls, position, choices):
2278
+ """Initialize with a set of possible positions.
2279
+
2280
+ choices is a list of Position derived objects, specifying possible
2281
+ locations.
2282
+
2283
+ position is an integer specifying the default behavior.
2284
+ """
2285
+ if position not in choices:
2286
+ raise ValueError(
2287
+ f"OneOfPosition: {position!r} should match one of {choices!r}"
2288
+ )
2289
+ obj = int.__new__(cls, position)
2290
+ obj.position_choices = choices
2291
+ return obj
2292
+
2293
+ def __getnewargs__(self):
2294
+ """Return the arguments accepted by __new__.
2295
+
2296
+ Necessary to allow pickling and unpickling of class instances.
2297
+ """
2298
+ return (int(self), self.position_choices)
2299
+
2300
+ def __repr__(self):
2301
+ """Represent the OneOfPosition object as a string for debugging."""
2302
+ return "%s(%i, choices=%r)" % (
2303
+ self.__class__.__name__,
2304
+ int(self),
2305
+ self.position_choices,
2306
+ )
2307
+
2308
+ def __str__(self):
2309
+ """Return a representation of the OneOfPosition object (with python counting)."""
2310
+ out = "one-of("
2311
+ for position in self.position_choices:
2312
+ out += f"{position},"
2313
+ # replace the last comma with the closing parenthesis
2314
+ return out[:-1] + ")"
2315
+
2316
+ def __add__(self, offset):
2317
+ """Return a copy of the position object with its location shifted (PRIVATE)."""
2318
+ return self.__class__(
2319
+ int(self) + offset, [p + offset for p in self.position_choices]
2320
+ )
2321
+
2322
+ def _flip(self, length):
2323
+ """Return a copy of the location after the parent is reversed (PRIVATE)."""
2324
+ return self.__class__(
2325
+ length - int(self), [p._flip(length) for p in self.position_choices[::-1]]
2326
+ )
2327
+
2328
+
2329
+ if __name__ == "__main__":
2330
+ from Bio._utils import run_doctest
2331
+
2332
+ run_doctest()
.venv_haddock/lib/python3.12/site-packages/Bio/SeqRecord.py ADDED
@@ -0,0 +1,1541 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2000-2002 Andrew Dalke. All rights reserved.
2
+ # Copyright 2002-2004 Brad Chapman. All rights reserved.
3
+ # Copyright 2006-2023 by Peter Cock. All rights reserved.
4
+ # Copyright 2020 by Michael R. Crusoe
5
+ #
6
+ # This file is part of the Biopython distribution and governed by your
7
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
8
+ # Please see the LICENSE file that should have been included as part of this
9
+ # package.
10
+ """Represent a Sequence Record, a sequence with annotation."""
11
+
12
+ # NEEDS TO BE SYNCH WITH THE REST OF BIOPYTHON AND BIOPERL
13
+ # In particular, the SeqRecord and BioSQL.BioSeq.DBSeqRecord classes
14
+ # need to be in sync (this is the BioSQL "Database SeqRecord").
15
+ import numbers
16
+ from typing import Any
17
+ from typing import cast
18
+ from collections.abc import Iterator
19
+ from typing import NoReturn
20
+ from typing import Optional
21
+ from typing import overload
22
+ from collections.abc import Sequence
23
+ from typing import TYPE_CHECKING
24
+ from typing import Union
25
+
26
+ from Bio import StreamModeError
27
+ from Bio.Seq import MutableSeq
28
+ from Bio.Seq import Seq
29
+ from Bio.Seq import UndefinedSequenceError
30
+
31
+ if TYPE_CHECKING:
32
+ from Bio.SeqFeature import SeqFeature
33
+
34
+ _NO_SEQRECORD_COMPARISON = "SeqRecord comparison is deliberately not implemented. Explicitly compare the attributes of interest."
35
+
36
+
37
+ class _RestrictedDict(dict[str, Sequence[Any]]):
38
+ """Dict which only allows sequences of given length as values (PRIVATE).
39
+
40
+ This simple subclass of the Python dictionary is used in the SeqRecord
41
+ object for holding per-letter-annotations. This class is intended to
42
+ prevent simple errors by only allowing python sequences (e.g. lists,
43
+ strings and tuples) to be stored, and only if their length matches that
44
+ expected (the length of the SeqRecord's seq object). It cannot however
45
+ prevent the entries being edited in situ (for example appending entries
46
+ to a list).
47
+
48
+ >>> x = _RestrictedDict(5)
49
+ >>> x["test"] = "hello"
50
+ >>> x
51
+ {'test': 'hello'}
52
+
53
+ Adding entries which don't have the expected length are blocked:
54
+
55
+ >>> x["test"] = "hello world"
56
+ Traceback (most recent call last):
57
+ ...
58
+ TypeError: Any per-letter annotation should be a Python sequence (list, tuple or string) of the same length as the biological sequence, here 5.
59
+
60
+ The expected length is stored as a private attribute,
61
+
62
+ >>> x._length
63
+ 5
64
+
65
+ In order that the SeqRecord (and other objects using this class) can be
66
+ pickled, for example for use in the multiprocessing library, we need to
67
+ be able to pickle the restricted dictionary objects.
68
+
69
+ Using the default protocol, which is 3 on Python 3,
70
+
71
+ >>> import pickle
72
+ >>> y = pickle.loads(pickle.dumps(x))
73
+ >>> y
74
+ {'test': 'hello'}
75
+ >>> y._length
76
+ 5
77
+
78
+ Using the highest protocol, which is 4 on Python 3,
79
+
80
+ >>> import pickle
81
+ >>> z = pickle.loads(pickle.dumps(x, pickle.HIGHEST_PROTOCOL))
82
+ >>> z
83
+ {'test': 'hello'}
84
+ >>> z._length
85
+ 5
86
+ """
87
+
88
+ def __init__(self, length: int) -> None:
89
+ """Create an EMPTY restricted dictionary."""
90
+ dict.__init__(self)
91
+ self._length = int(length)
92
+
93
+ def __setitem__(self, key: str, value: Sequence[Any]) -> None:
94
+ # The check hasattr(self, "_length") is to cope with pickle protocol 2
95
+ # I couldn't seem to avoid this with __getstate__ and __setstate__
96
+ if (
97
+ not hasattr(value, "__len__")
98
+ or not hasattr(value, "__getitem__")
99
+ or (hasattr(self, "_length") and len(value) != self._length)
100
+ ):
101
+ raise TypeError(
102
+ "Any per-letter annotation should be a Python sequence "
103
+ "(list, tuple or string) of the same length as the "
104
+ f"biological sequence, here {self._length}."
105
+ )
106
+ dict.__setitem__(self, key, value)
107
+
108
+ def update(self, new_dict):
109
+ # Force this to go via our strict __setitem__ method
110
+ for key, value in new_dict.items():
111
+ self[key] = value
112
+
113
+
114
+ class SeqRecord:
115
+ """A SeqRecord object holds a sequence and information about it.
116
+
117
+ Main attributes:
118
+ - id - Identifier such as a locus tag (string)
119
+ - seq - The sequence itself (Seq object or similar)
120
+
121
+ Additional attributes:
122
+ - name - Sequence name, e.g. gene name (string)
123
+ - description - Additional text (string)
124
+ - dbxrefs - List of database cross references (list of strings)
125
+ - features - Any (sub)features defined (list of SeqFeature objects)
126
+ - annotations - Further information about the whole sequence (dictionary).
127
+ Most entries are strings, or lists of strings.
128
+ - letter_annotations - Per letter/symbol annotation (restricted
129
+ dictionary). This holds Python sequences (lists, strings
130
+ or tuples) whose length matches that of the sequence.
131
+ A typical use would be to hold a list of integers
132
+ representing sequencing quality scores, or a string
133
+ representing the secondary structure.
134
+
135
+ You will typically use Bio.SeqIO to read in sequences from files as
136
+ SeqRecord objects. However, you may want to create your own SeqRecord
137
+ objects directly (see the __init__ method for further details):
138
+
139
+ >>> from Bio.Seq import Seq
140
+ >>> from Bio.SeqRecord import SeqRecord
141
+ >>> record = SeqRecord(Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF"),
142
+ ... id="YP_025292.1", name="HokC",
143
+ ... description="toxic membrane protein")
144
+ >>> print(record)
145
+ ID: YP_025292.1
146
+ Name: HokC
147
+ Description: toxic membrane protein
148
+ Number of features: 0
149
+ Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF')
150
+
151
+ If you want to save SeqRecord objects to a sequence file, use Bio.SeqIO
152
+ for this. For the special case where you want the SeqRecord turned into
153
+ a string in a particular file format there is a format method which uses
154
+ Bio.SeqIO internally:
155
+
156
+ >>> print(record.format("fasta"))
157
+ >YP_025292.1 toxic membrane protein
158
+ MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF
159
+ <BLANKLINE>
160
+
161
+ You can also do things like slicing a SeqRecord, checking its length, etc
162
+
163
+ >>> len(record)
164
+ 44
165
+ >>> edited = record[:10] + record[11:]
166
+ >>> print(edited.seq)
167
+ MKQHKAMIVAIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF
168
+ >>> print(record.seq)
169
+ MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF
170
+
171
+ """
172
+
173
+ _AnnotationsDictValue = str | int
174
+ _AnnotationsDict = dict[str, _AnnotationsDictValue]
175
+
176
+ annotations: _AnnotationsDict
177
+ dbxrefs: list[str]
178
+ _per_letter_annotations: _RestrictedDict | None
179
+
180
+ def __init__(
181
+ self,
182
+ seq: Union["Seq", "MutableSeq"] | None,
183
+ id: str | None = "<unknown id>",
184
+ name: str = "<unknown name>",
185
+ description: str = "<unknown description>",
186
+ dbxrefs: list[str] | None = None,
187
+ features: list["SeqFeature"] | None = None,
188
+ annotations: _AnnotationsDict | None = None,
189
+ letter_annotations: dict[str, Sequence[Any]] | None = None,
190
+ ) -> None:
191
+ """Create a SeqRecord.
192
+
193
+ Arguments:
194
+ - seq - Sequence, required (Seq or MutableSeq)
195
+ - id - Sequence identifier, recommended (string)
196
+ - name - Sequence name, optional (string)
197
+ - description - Sequence description, optional (string)
198
+ - dbxrefs - Database cross references, optional (list of strings)
199
+ - features - Any (sub)features, optional (list of SeqFeature objects)
200
+ - annotations - Dictionary of annotations for the whole sequence
201
+ - letter_annotations - Dictionary of per-letter-annotations, values
202
+ should be strings, list or tuples of the same length as the full
203
+ sequence.
204
+
205
+ You will typically use Bio.SeqIO to read in sequences from files as
206
+ SeqRecord objects. However, you may want to create your own SeqRecord
207
+ objects directly.
208
+
209
+ Note that while an id is optional, we strongly recommend you supply a
210
+ unique id string for each record. This is especially important
211
+ if you wish to write your sequences to a file.
212
+
213
+ You can create a 'blank' SeqRecord object, and then populate the
214
+ attributes later.
215
+ """
216
+ if seq is not None and not isinstance(seq, (Seq, MutableSeq)):
217
+ raise TypeError("seq argument should be a Seq or MutableSeq object")
218
+ if id is not None and not isinstance(id, str):
219
+ # Lots of existing code uses id=None... this may be a bad idea.
220
+ raise TypeError("id argument should be a string")
221
+ if not isinstance(name, str):
222
+ raise TypeError("name argument should be a string")
223
+ if not isinstance(description, str):
224
+ raise TypeError("description argument should be a string")
225
+
226
+ self._seq = seq
227
+ self.id = id
228
+ self.name = name
229
+ self.description = description
230
+
231
+ # database cross references (for the whole sequence)
232
+ if dbxrefs is None:
233
+ dbxrefs = []
234
+ elif not isinstance(dbxrefs, list):
235
+ raise TypeError("dbxrefs argument should be a list (of strings)")
236
+ self.dbxrefs = dbxrefs
237
+
238
+ # annotations about the whole sequence
239
+ if annotations is None:
240
+ annotations = {}
241
+ elif not isinstance(annotations, dict):
242
+ raise TypeError("annotations argument must be a dict or None")
243
+ self.annotations = annotations
244
+
245
+ self._per_letter_annotations = None
246
+ if letter_annotations is not None:
247
+ # This will be handled via the property set function, which will
248
+ # turn this into a _RestrictedDict and thus ensure all the values
249
+ # in the dict are the right length
250
+ self.letter_annotations = letter_annotations
251
+
252
+ # annotations about parts of the sequence
253
+ if features is None:
254
+ features = []
255
+ elif not isinstance(features, list):
256
+ raise TypeError(
257
+ "features argument should be a list (of SeqFeature objects)"
258
+ )
259
+ self.features = features
260
+
261
+ @property
262
+ def letter_annotations(self) -> dict[str, Sequence[Any]]:
263
+ """Dictionary of per-letter-annotation for the sequence.
264
+
265
+ For example, this can hold quality scores used in FASTQ or QUAL files.
266
+ Consider this example using Bio.SeqIO to read in an example Solexa
267
+ variant FASTQ file as a SeqRecord:
268
+
269
+ >>> from Bio import SeqIO
270
+ >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa")
271
+ >>> print("%s %s" % (record.id, record.seq))
272
+ slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN
273
+ >>> print(list(record.letter_annotations))
274
+ ['solexa_quality']
275
+ >>> print(record.letter_annotations["solexa_quality"])
276
+ [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
277
+
278
+ The letter_annotations get sliced automatically if you slice the
279
+ parent SeqRecord, for example taking the last ten bases:
280
+
281
+ >>> sub_record = record[-10:]
282
+ >>> print("%s %s" % (sub_record.id, sub_record.seq))
283
+ slxa_0001_1_0001_01 ACGTNNNNNN
284
+ >>> print(sub_record.letter_annotations["solexa_quality"])
285
+ [4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
286
+
287
+ Any python sequence (i.e. list, tuple or string) can be recorded in
288
+ the SeqRecord's letter_annotations dictionary as long as the length
289
+ matches that of the SeqRecord's sequence. e.g.
290
+
291
+ >>> len(sub_record.letter_annotations)
292
+ 1
293
+ >>> sub_record.letter_annotations["dummy"] = "abcdefghij"
294
+ >>> len(sub_record.letter_annotations)
295
+ 2
296
+
297
+ You can delete entries from the letter_annotations dictionary as usual:
298
+
299
+ >>> del sub_record.letter_annotations["solexa_quality"]
300
+ >>> sub_record.letter_annotations
301
+ {'dummy': 'abcdefghij'}
302
+
303
+ You can completely clear the dictionary easily as follows:
304
+
305
+ >>> sub_record.letter_annotations = {}
306
+ >>> sub_record.letter_annotations
307
+ {}
308
+
309
+ Note that if replacing the record's sequence with a sequence of a
310
+ different length you must first clear the letter_annotations dict.
311
+ """
312
+ if self._per_letter_annotations is None:
313
+ length = 0 if self.seq is None else len(self.seq)
314
+ self._per_letter_annotations = _RestrictedDict(length=length)
315
+ return self._per_letter_annotations
316
+
317
+ # TODO - Just make this a read only property?
318
+ @letter_annotations.setter
319
+ def letter_annotations(self, value: dict[str, Sequence[Any]]) -> None:
320
+ if not isinstance(value, dict):
321
+ raise TypeError(
322
+ "The per-letter-annotations should be a (restricted) dictionary."
323
+ )
324
+ # Turn this into a restricted-dictionary (and check the entries)
325
+ length = 0 if self.seq is None else len(self.seq)
326
+ if any(len(val) != length for val in value.values()):
327
+ raise ValueError(
328
+ f"The per-letter-annotations have the same length as the sequence, but found: \n {','.join([f'{key}={val}' for key, val in value.items() if len(val) != length])}"
329
+ )
330
+ if self._per_letter_annotations is None:
331
+ self._per_letter_annotations = _RestrictedDict(length=length)
332
+ else:
333
+ self._per_letter_annotations.clear()
334
+ dict.update(self._per_letter_annotations, value) # type: ignore
335
+
336
+ @property
337
+ def seq(self) -> Union["Seq", "MutableSeq"] | None:
338
+ """The sequence itself, as a Seq or MutableSeq object."""
339
+ return self._seq
340
+
341
+ @seq.setter
342
+ def seq(self, value: Union["Seq", "MutableSeq"]) -> None:
343
+ # Adding this here for users who are not type-checking their code.
344
+ if value is not None and not isinstance(value, (Seq, MutableSeq)):
345
+ raise TypeError("seq must be a Seq or MutableSeq object")
346
+ # TODO - Add a deprecation warning that the seq should be write only?
347
+ if self._per_letter_annotations:
348
+ if len(self) != len(value):
349
+ # TODO - Make this a warning? Silently empty the dictionary?
350
+ raise ValueError("You must empty the letter annotations first!")
351
+ else:
352
+ # Leave the existing per letter annotations unchanged:
353
+ self._seq = value
354
+ else:
355
+ self._seq = value
356
+ # Reset the (empty) letter annotations dict with new length:
357
+ length = 0 if self.seq is None else len(self.seq)
358
+ self._per_letter_annotations = _RestrictedDict(length=length)
359
+
360
+ @classmethod
361
+ def _from_validated(
362
+ cls,
363
+ seq: Seq | MutableSeq | None,
364
+ id: str | None = "<unknown id>",
365
+ name: str = "<unknown name>",
366
+ description: str = "<unknown description>",
367
+ dbxrefs: list[str] | None = None,
368
+ features: list["SeqFeature"] | None = None,
369
+ annotations: dict[str, str | int] | None = None,
370
+ letter_annotations: dict[str, Sequence] | None = None,
371
+ ) -> "SeqRecord":
372
+ """Faster constructor for post-validated data like copies or validated parsed data"""
373
+
374
+ if cls is not SeqRecord:
375
+ # If we subclassed, we'll default to that class's initializer just to be careful
376
+ return cls(
377
+ seq,
378
+ id,
379
+ name,
380
+ description,
381
+ dbxrefs,
382
+ features,
383
+ annotations,
384
+ letter_annotations,
385
+ )
386
+
387
+ inst = cls.__new__(cls)
388
+
389
+ inst._seq = seq
390
+ inst.id = id
391
+ inst.name = name
392
+ inst.description = description
393
+ if dbxrefs is None:
394
+ dbxrefs = []
395
+ inst.dbxrefs = dbxrefs
396
+ if features is None:
397
+ features = []
398
+ inst.features = features
399
+ if annotations is None:
400
+ annotations = {}
401
+ inst.annotations = annotations
402
+
403
+ inst._per_letter_annotations = None
404
+ if letter_annotations is not None:
405
+ length = 0 if seq is None else len(seq)
406
+ inst._per_letter_annotations = _RestrictedDict(length=length)
407
+ dict.update(inst._per_letter_annotations, letter_annotations) # type: ignore
408
+ return inst
409
+
410
+ @overload
411
+ def __getitem__(self, index: int) -> str: ...
412
+
413
+ @overload
414
+ def __getitem__(self, index: slice) -> "SeqRecord": ...
415
+
416
+ def __getitem__(self, index):
417
+ """Return a sub-sequence or an individual letter.
418
+
419
+ Slicing, e.g. my_record[5:10], returns a new SeqRecord for
420
+ that sub-sequence with some annotation preserved as follows:
421
+
422
+ * The name, id and description are kept as-is.
423
+ * Any per-letter-annotations are sliced to match the requested
424
+ sub-sequence.
425
+ * Unless a stride is used, all those features which fall fully
426
+ within the subsequence are included (with their locations
427
+ adjusted accordingly). If you want to preserve any truncated
428
+ features (e.g. GenBank/EMBL source features), you must
429
+ explicitly add them to the new SeqRecord yourself.
430
+ * With the exception of any molecule type, the annotations
431
+ dictionary and the dbxrefs list are not used for the new
432
+ SeqRecord, as in general they may not apply to the
433
+ subsequence. If you want to preserve them, you must explicitly
434
+ copy them to the new SeqRecord yourself.
435
+
436
+ Using an integer index, e.g. my_record[5] is shorthand for
437
+ extracting that letter from the sequence, my_record.seq[5].
438
+
439
+ For example, consider this short protein and its secondary
440
+ structure as encoded by the PDB (e.g. H for alpha helices),
441
+ plus a simple feature for its histidine self phosphorylation
442
+ site:
443
+
444
+ >>> from Bio.Seq import Seq
445
+ >>> from Bio.SeqRecord import SeqRecord
446
+ >>> from Bio.SeqFeature import SeqFeature, SimpleLocation
447
+ >>> rec = SeqRecord(Seq("MAAGVKQLADDRTLLMAGVSHDLRTPLTRIRLAT"
448
+ ... "EMMSEQDGYLAESINKDIEECNAIIEQFIDYLR"),
449
+ ... id="1JOY", name="EnvZ",
450
+ ... description="Homodimeric domain of EnvZ from E. coli")
451
+ >>> rec.letter_annotations["secondary_structure"] = " S SSSSSSHHHHHTTTHHHHHHHHHHHHHHHHHHHHHHTHHHHHHHHHHHHHHHHHHHHHTT "
452
+ >>> rec.features.append(SeqFeature(SimpleLocation(20, 21),
453
+ ... type = "Site"))
454
+
455
+ Now let's have a quick look at the full record,
456
+
457
+ >>> print(rec)
458
+ ID: 1JOY
459
+ Name: EnvZ
460
+ Description: Homodimeric domain of EnvZ from E. coli
461
+ Number of features: 1
462
+ Per letter annotation for: secondary_structure
463
+ Seq('MAAGVKQLADDRTLLMAGVSHDLRTPLTRIRLATEMMSEQDGYLAESINKDIEE...YLR')
464
+ >>> rec.letter_annotations["secondary_structure"]
465
+ ' S SSSSSSHHHHHTTTHHHHHHHHHHHHHHHHHHHHHHTHHHHHHHHHHHHHHHHHHHHHTT '
466
+ >>> print(rec.features[0].location)
467
+ [20:21]
468
+
469
+ Now let's take a sub sequence, here chosen as the first (fractured)
470
+ alpha helix which includes the histidine phosphorylation site:
471
+
472
+ >>> sub = rec[11:41]
473
+ >>> print(sub)
474
+ ID: 1JOY
475
+ Name: EnvZ
476
+ Description: Homodimeric domain of EnvZ from E. coli
477
+ Number of features: 1
478
+ Per letter annotation for: secondary_structure
479
+ Seq('RTLLMAGVSHDLRTPLTRIRLATEMMSEQD')
480
+ >>> sub.letter_annotations["secondary_structure"]
481
+ 'HHHHHTTTHHHHHHHHHHHHHHHHHHHHHH'
482
+ >>> print(sub.features[0].location)
483
+ [9:10]
484
+
485
+ You can also of course omit the start or end values, for
486
+ example to get the first ten letters only:
487
+
488
+ >>> print(rec[:10])
489
+ ID: 1JOY
490
+ Name: EnvZ
491
+ Description: Homodimeric domain of EnvZ from E. coli
492
+ Number of features: 0
493
+ Per letter annotation for: secondary_structure
494
+ Seq('MAAGVKQLAD')
495
+
496
+ Or for the last ten letters:
497
+
498
+ >>> print(rec[-10:])
499
+ ID: 1JOY
500
+ Name: EnvZ
501
+ Description: Homodimeric domain of EnvZ from E. coli
502
+ Number of features: 0
503
+ Per letter annotation for: secondary_structure
504
+ Seq('IIEQFIDYLR')
505
+
506
+ If you omit both, then you get a copy of the original record (although
507
+ lacking the annotations and dbxrefs):
508
+
509
+ >>> print(rec[:])
510
+ ID: 1JOY
511
+ Name: EnvZ
512
+ Description: Homodimeric domain of EnvZ from E. coli
513
+ Number of features: 1
514
+ Per letter annotation for: secondary_structure
515
+ Seq('MAAGVKQLADDRTLLMAGVSHDLRTPLTRIRLATEMMSEQDGYLAESINKDIEE...YLR')
516
+
517
+ Finally, indexing with a simple integer is shorthand for pulling out
518
+ that letter from the sequence directly:
519
+
520
+ >>> rec[5]
521
+ 'K'
522
+ >>> rec.seq[5]
523
+ 'K'
524
+ """
525
+ if isinstance(index, numbers.Integral):
526
+ # NOTE - The sequence level annotation like the id, name, etc
527
+ # do not really apply to a single character. However, should
528
+ # we try and expose any per-letter-annotation here? If so how?
529
+ if self.seq is None:
530
+ raise ValueError(
531
+ "Seq in SeqRecord is None, it doesn't support indexing"
532
+ )
533
+ return self.seq[index]
534
+ elif isinstance(index, slice):
535
+ if self.seq is None:
536
+ raise ValueError("Seq in SeqRecord is None, we cannot slice it")
537
+ parent_length = len(self)
538
+ try:
539
+ from BioSQL.BioSeq import DBSeqRecord
540
+
541
+ biosql_available = True
542
+ except ImportError:
543
+ biosql_available = False
544
+
545
+ if biosql_available and isinstance(self, DBSeqRecord):
546
+ answer = SeqRecord._from_validated(
547
+ self.seq[index],
548
+ id=self.id,
549
+ name=self.name,
550
+ description=self.description,
551
+ )
552
+ else:
553
+ answer = self._from_validated(
554
+ self.seq[index],
555
+ id=self.id,
556
+ name=self.name,
557
+ description=self.description,
558
+ )
559
+ # TODO - The description may no longer apply.
560
+ # It would be safer to change it to something
561
+ # generic like "edited" or the default value.
562
+
563
+ # Don't copy the annotation dict and dbxefs list,
564
+ # they may not apply to a subsequence.
565
+ # answer.annotations = dict(self.annotations.items())
566
+ # answer.dbxrefs = self.dbxrefs[:]
567
+ # TODO - Review this in light of adding SeqRecord objects?
568
+
569
+ if "molecule_type" in self.annotations:
570
+ # This will still apply, and we need it for GenBank/EMBL etc output
571
+ answer.annotations["molecule_type"] = self.annotations["molecule_type"]
572
+
573
+ # TODO - Cope with strides by generating ambiguous locations?
574
+ start, stop, step = index.indices(parent_length)
575
+ if step == 1:
576
+ # Select relevant features, add them with shifted locations
577
+ # assert str(self.seq)[index] == str(self.seq)[start:stop]
578
+ for f in self.features:
579
+ if f.location.ref or f.location.ref_db:
580
+ # TODO - Implement this (with lots of tests)?
581
+ import warnings
582
+
583
+ warnings.warn(
584
+ "When slicing SeqRecord objects, any "
585
+ "SeqFeature referencing other sequences (e.g. "
586
+ "from segmented GenBank records) are ignored."
587
+ )
588
+ continue
589
+ try:
590
+ if start <= f.location.start and f.location.end <= stop:
591
+ answer.features.append(f._shift(-start))
592
+ except TypeError:
593
+ # Will fail on UnknownPosition
594
+ pass
595
+
596
+ # Slice all the values to match the sliced sequence
597
+ # (this should also work with strides, even negative strides):
598
+ for key, value in self.letter_annotations.items():
599
+ answer.letter_annotations[key] = value[index]
600
+
601
+ return answer
602
+ raise ValueError("Invalid index")
603
+
604
+ def __iter__(self) -> Iterator[str]:
605
+ """Iterate over the letters in the sequence.
606
+
607
+ For example, using Bio.SeqIO to read in a protein FASTA file:
608
+
609
+ >>> from Bio import SeqIO
610
+ >>> record = SeqIO.read("Fasta/loveliesbleeding.pro", "fasta")
611
+ >>> for amino in record:
612
+ ... print(amino)
613
+ ... if amino == "L": break
614
+ X
615
+ A
616
+ G
617
+ L
618
+ >>> print(record.seq[3])
619
+ L
620
+
621
+ This is just a shortcut for iterating over the sequence directly:
622
+
623
+ >>> for amino in record.seq:
624
+ ... print(amino)
625
+ ... if amino == "L": break
626
+ X
627
+ A
628
+ G
629
+ L
630
+ >>> print(record.seq[3])
631
+ L
632
+
633
+ Note that this does not facilitate iteration together with any
634
+ per-letter-annotation. However, you can achieve that using the
635
+ python zip function on the record (or its sequence) and the relevant
636
+ per-letter-annotation:
637
+
638
+ >>> from Bio import SeqIO
639
+ >>> rec = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa")
640
+ >>> print("%s %s" % (rec.id, rec.seq))
641
+ slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN
642
+ >>> print(list(rec.letter_annotations))
643
+ ['solexa_quality']
644
+ >>> for nuc, qual in zip(rec, rec.letter_annotations["solexa_quality"]):
645
+ ... if qual > 35:
646
+ ... print("%s %i" % (nuc, qual))
647
+ A 40
648
+ C 39
649
+ G 38
650
+ T 37
651
+ A 36
652
+
653
+ You may agree that using zip(rec.seq, ...) is more explicit than using
654
+ zip(rec, ...) as shown above.
655
+ """
656
+ if self._seq is None:
657
+ raise ValueError("Seq in SeqRecord is None, can't iterate over it")
658
+ return iter(self._seq)
659
+
660
+ def __contains__(self, char: str) -> bool:
661
+ """Implement the 'in' keyword, searches the sequence.
662
+
663
+ e.g.
664
+
665
+ >>> from Bio import SeqIO
666
+ >>> record = SeqIO.read("Fasta/sweetpea.nu", "fasta")
667
+ >>> "GAATTC" in record
668
+ False
669
+ >>> "AAA" in record
670
+ True
671
+
672
+ This essentially acts as a proxy for using "in" on the sequence:
673
+
674
+ >>> "GAATTC" in record.seq
675
+ False
676
+ >>> "AAA" in record.seq
677
+ True
678
+
679
+ Note that you can also use Seq objects as the query,
680
+
681
+ >>> from Bio.Seq import Seq
682
+ >>> Seq("AAA") in record
683
+ True
684
+
685
+ See also the Seq object's __contains__ method.
686
+ """
687
+ if self._seq is None:
688
+ raise ValueError("Seq in SeqRecord is None, can't convert to bytes")
689
+ return char in self._seq
690
+
691
+ def __bytes__(self) -> bytes:
692
+ if self._seq is None:
693
+ raise ValueError("Seq in SeqRecord is None, can't convert to bytes")
694
+ return bytes(self._seq)
695
+
696
+ def __str__(self) -> str:
697
+ """Return a human readable summary of the record and its annotation (string).
698
+
699
+ The python built in function str works by calling the object's __str__
700
+ method. e.g.
701
+
702
+ >>> from Bio.Seq import Seq
703
+ >>> from Bio.SeqRecord import SeqRecord
704
+ >>> record = SeqRecord(Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF"),
705
+ ... id="YP_025292.1", name="HokC",
706
+ ... description="toxic membrane protein, small")
707
+ >>> print(str(record))
708
+ ID: YP_025292.1
709
+ Name: HokC
710
+ Description: toxic membrane protein, small
711
+ Number of features: 0
712
+ Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF')
713
+
714
+ In this example you don't actually need to call str explicitly, as the
715
+ print command does this automatically:
716
+
717
+ >>> print(record)
718
+ ID: YP_025292.1
719
+ Name: HokC
720
+ Description: toxic membrane protein, small
721
+ Number of features: 0
722
+ Seq('MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF')
723
+
724
+ Note that long sequences are shown truncated.
725
+ """
726
+ lines: list[str] = []
727
+ if self.id:
728
+ lines.append(f"ID: {self.id}")
729
+ if self.name:
730
+ lines.append(f"Name: {self.name}")
731
+ if self.description:
732
+ lines.append(f"Description: {self.description}")
733
+ if self.dbxrefs:
734
+ lines.append("Database cross-references: " + ", ".join(self.dbxrefs))
735
+ lines.append(f"Number of features: {len(self.features)}")
736
+ for a in self.annotations:
737
+ lines.append(f"/{a}={self.annotations[a]!s}")
738
+ if self.letter_annotations:
739
+ lines.append(
740
+ "Per letter annotation for: " + ", ".join(self.letter_annotations)
741
+ )
742
+ if self.seq is not None:
743
+ try:
744
+ bytes(self.seq)
745
+ except UndefinedSequenceError:
746
+ lines.append(f"Undefined sequence of length {len(self.seq)}")
747
+ else:
748
+ # Don't want to include the entire sequence
749
+ seq = repr(self.seq)
750
+ lines.append(seq)
751
+ else:
752
+ lines.append("Missing Sequence (None)")
753
+
754
+ return "\n".join(lines)
755
+
756
+ def __repr__(self) -> str:
757
+ """Return a concise summary of the record for debugging (string).
758
+
759
+ The python built in function repr works by calling the object's __repr__
760
+ method. e.g.
761
+
762
+ >>> from Bio.Seq import Seq
763
+ >>> from Bio.SeqRecord import SeqRecord
764
+ >>> rec = SeqRecord(Seq("MASRGVNKVILVGNLGQDPEVRYMPNGGAVANITLATSESWRDKAT"
765
+ ... "GEMKEQTEWHRVVLFGKLAEVASEYLRKGSQVYIEGQLRTRKWTDQ"
766
+ ... "SGQDRYTTEVVVNVGGTMQMLGGRQGGGAPAGGNIGGGQPQGGWGQ"
767
+ ... "PQQPQGGNQFSGGAQSRPQQSAPAAPSNEPPMDFDDDIPF"),
768
+ ... id="NP_418483.1", name="b4059",
769
+ ... description="ssDNA-binding protein",
770
+ ... dbxrefs=["ASAP:13298", "GI:16131885", "GeneID:948570"])
771
+ >>> print(repr(rec))
772
+ SeqRecord(seq=Seq('MASRGVNKVILVGNLGQDPEVRYMPNGGAVANITLATSESWRDKATGEMKEQTE...IPF'), id='NP_418483.1', name='b4059', description='ssDNA-binding protein', dbxrefs=['ASAP:13298', 'GI:16131885', 'GeneID:948570'])
773
+
774
+ At the python prompt you can also use this shorthand:
775
+
776
+ >>> rec
777
+ SeqRecord(seq=Seq('MASRGVNKVILVGNLGQDPEVRYMPNGGAVANITLATSESWRDKATGEMKEQTE...IPF'), id='NP_418483.1', name='b4059', description='ssDNA-binding protein', dbxrefs=['ASAP:13298', 'GI:16131885', 'GeneID:948570'])
778
+
779
+ Note that long sequences are shown truncated. Also note that any
780
+ annotations, letter_annotations and features are not shown (as they
781
+ would lead to a very long string).
782
+ """
783
+ return (
784
+ f"{self.__class__.__name__}(seq={self.seq!r}, id={self.id!r},"
785
+ f" name={self.name!r}, description={self.description!r},"
786
+ f" dbxrefs={self.dbxrefs!r})"
787
+ )
788
+
789
+ def format(self, format: str) -> str:
790
+ r"""Return the record as a string in the specified file format.
791
+
792
+ The format should be a lower case string supported as an output
793
+ format by Bio.SeqIO, which is used to turn the SeqRecord into a
794
+ string. e.g.
795
+
796
+ >>> from Bio.Seq import Seq
797
+ >>> from Bio.SeqRecord import SeqRecord
798
+ >>> record = SeqRecord(Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF"),
799
+ ... id="YP_025292.1", name="HokC",
800
+ ... description="toxic membrane protein")
801
+ >>> record.format("fasta")
802
+ '>YP_025292.1 toxic membrane protein\nMKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF\n'
803
+ >>> print(record.format("fasta"))
804
+ >YP_025292.1 toxic membrane protein
805
+ MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF
806
+ <BLANKLINE>
807
+
808
+ The Python print function automatically appends a new line, meaning
809
+ in this example a blank line is shown. If you look at the string
810
+ representation you can see there is a trailing new line (shown as
811
+ slash n) which is important when writing to a file or if
812
+ concatenating multiple sequence strings together.
813
+
814
+ Note that this method will NOT work on every possible file format
815
+ supported by Bio.SeqIO (e.g. some are for multiple sequences only,
816
+ and binary formats are not supported).
817
+ """
818
+ # See also the __format__ method
819
+ return self.__format__(format)
820
+
821
+ def __format__(self, format_spec: str) -> str:
822
+ r"""Return the record as a string in the specified file format.
823
+
824
+ This method supports the Python format() function and f-strings.
825
+ The format_spec should be a lower case string supported by
826
+ Bio.SeqIO as a text output file format. Requesting a binary file
827
+ format raises a ValueError. e.g.
828
+
829
+ >>> from Bio.Seq import Seq
830
+ >>> from Bio.SeqRecord import SeqRecord
831
+ >>> record = SeqRecord(Seq("MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF"),
832
+ ... id="YP_025292.1", name="HokC",
833
+ ... description="toxic membrane protein")
834
+ ...
835
+ >>> format(record, "fasta")
836
+ '>YP_025292.1 toxic membrane protein\nMKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF\n'
837
+ >>> print(f"Here is {record.id} in FASTA format:\n{record:fasta}")
838
+ Here is YP_025292.1 in FASTA format:
839
+ >YP_025292.1 toxic membrane protein
840
+ MKQHKAMIVALIVICITAVVAALVTRKDLCEVHIRTGQTEVAVF
841
+ <BLANKLINE>
842
+
843
+ See also the SeqRecord's format() method.
844
+ """
845
+ if not format_spec:
846
+ # Follow python convention and default to using __str__
847
+ return str(self)
848
+ from Bio import SeqIO
849
+
850
+ cls = SeqIO._FormatToWriter[format_spec]
851
+ try:
852
+ return cls.to_string(self) # type: ignore
853
+ except StreamModeError:
854
+ raise ValueError(
855
+ "Binary format %s cannot be used with SeqRecord format method"
856
+ % format_spec
857
+ ) from None
858
+
859
+ def __len__(self) -> int:
860
+ """Return the length of the sequence.
861
+
862
+ For example, using Bio.SeqIO to read in a FASTA nucleotide file:
863
+
864
+ >>> from Bio import SeqIO
865
+ >>> record = SeqIO.read("Fasta/sweetpea.nu", "fasta")
866
+ >>> len(record)
867
+ 309
868
+ >>> len(record.seq)
869
+ 309
870
+ """
871
+ return len(self._seq) if self._seq is not None else 0
872
+
873
+ def __lt__(self, other: Any) -> NoReturn:
874
+ """Define the less-than operand (not implemented)."""
875
+ raise NotImplementedError(_NO_SEQRECORD_COMPARISON)
876
+
877
+ def __le__(self, other: Any) -> NoReturn:
878
+ """Define the less-than-or-equal-to operand (not implemented)."""
879
+ raise NotImplementedError(_NO_SEQRECORD_COMPARISON)
880
+
881
+ def __eq__(self, other: object) -> NoReturn:
882
+ """Define the equal-to operand (not implemented)."""
883
+ raise NotImplementedError(_NO_SEQRECORD_COMPARISON)
884
+
885
+ def __ne__(self, other: object) -> NoReturn:
886
+ """Define the not-equal-to operand (not implemented)."""
887
+ raise NotImplementedError(_NO_SEQRECORD_COMPARISON)
888
+
889
+ def __gt__(self, other: Any) -> NoReturn:
890
+ """Define the greater-than operand (not implemented)."""
891
+ raise NotImplementedError(_NO_SEQRECORD_COMPARISON)
892
+
893
+ def __ge__(self, other: Any) -> NoReturn:
894
+ """Define the greater-than-or-equal-to operand (not implemented)."""
895
+ raise NotImplementedError(_NO_SEQRECORD_COMPARISON)
896
+
897
+ def __bool__(self) -> bool:
898
+ """Boolean value of an instance of this class (True).
899
+
900
+ This behaviour is for backwards compatibility, since until the
901
+ __len__ method was added, a SeqRecord always evaluated as True.
902
+
903
+ Note that in comparison, a Seq object will evaluate to False if it
904
+ has a zero length sequence.
905
+
906
+ WARNING: The SeqRecord may in future evaluate to False when its
907
+ sequence is of zero length (in order to better match the Seq
908
+ object behaviour)!
909
+ """
910
+ return True
911
+
912
+ def __add__(
913
+ self, other: Union["SeqRecord", "Seq", "MutableSeq", str]
914
+ ) -> "SeqRecord":
915
+ """Add another sequence or string to this sequence.
916
+
917
+ The other sequence can be a SeqRecord object, a Seq object (or
918
+ similar, e.g. a MutableSeq) or a plain Python string. If you add
919
+ a plain string or a Seq (like) object, the new SeqRecord will simply
920
+ have this appended to the existing data. However, any per letter
921
+ annotation will be lost:
922
+
923
+ >>> from Bio import SeqIO
924
+ >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa")
925
+ >>> print("%s %s" % (record.id, record.seq))
926
+ slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN
927
+ >>> print(list(record.letter_annotations))
928
+ ['solexa_quality']
929
+
930
+ >>> new = record + "ACT"
931
+ >>> print("%s %s" % (new.id, new.seq))
932
+ slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNNACT
933
+ >>> print(list(new.letter_annotations))
934
+ []
935
+
936
+ The new record will attempt to combine the annotation, but for any
937
+ ambiguities (e.g. different names) it defaults to omitting that
938
+ annotation.
939
+
940
+ >>> from Bio import SeqIO
941
+ >>> with open("GenBank/pBAD30.gb") as handle:
942
+ ... plasmid = SeqIO.read(handle, "gb")
943
+ >>> print("%s %i" % (plasmid.id, len(plasmid)))
944
+ pBAD30 4923
945
+
946
+ Now let's cut the plasmid into two pieces, and join them back up the
947
+ other way round (i.e. shift the starting point on this plasmid, have
948
+ a look at the annotated features in the original file to see why this
949
+ particular split point might make sense):
950
+
951
+ >>> left = plasmid[:3765]
952
+ >>> right = plasmid[3765:]
953
+ >>> new = right + left
954
+ >>> print("%s %i" % (new.id, len(new)))
955
+ pBAD30 4923
956
+ >>> str(new.seq) == str(right.seq + left.seq)
957
+ True
958
+ >>> len(new.features) == len(left.features) + len(right.features)
959
+ True
960
+
961
+ When we add the left and right SeqRecord objects, their annotation
962
+ is all consistent, so it is all conserved in the new SeqRecord:
963
+
964
+ >>> new.id == left.id == right.id == plasmid.id
965
+ True
966
+ >>> new.name == left.name == right.name == plasmid.name
967
+ True
968
+ >>> new.description == plasmid.description
969
+ True
970
+ >>> new.annotations == left.annotations == right.annotations
971
+ True
972
+ >>> new.letter_annotations == plasmid.letter_annotations
973
+ True
974
+ >>> new.dbxrefs == left.dbxrefs == right.dbxrefs
975
+ True
976
+
977
+ However, we should point out that when we sliced the SeqRecord,
978
+ any annotations dictionary or dbxrefs list entries were lost.
979
+ You can explicitly copy them like this:
980
+
981
+ >>> new.annotations = plasmid.annotations.copy()
982
+ >>> new.dbxrefs = plasmid.dbxrefs[:]
983
+ """
984
+
985
+ if self._seq is None:
986
+ raise ValueError("Left operand seq=None, can't add")
987
+
988
+ if not isinstance(other, SeqRecord):
989
+ # Assume it is a string or a Seq.
990
+ # Note can't transfer any per-letter-annotations
991
+ return type(self)(
992
+ self._seq + other,
993
+ id=self.id,
994
+ name=self.name,
995
+ description=self.description,
996
+ features=self.features[:],
997
+ annotations=self.annotations.copy(),
998
+ dbxrefs=self.dbxrefs[:],
999
+ )
1000
+
1001
+ if other._seq is None:
1002
+ raise ValueError("Right SeqRecord has seq=None, can't add")
1003
+
1004
+ # Adding two SeqRecord objects... must merge annotation
1005
+ answer = self._from_validated(
1006
+ self._seq + other._seq, features=self.features[:], dbxrefs=self.dbxrefs[:]
1007
+ )
1008
+ # Will take all the features and all the db cross refs,
1009
+ length = len(self)
1010
+ for f in other.features:
1011
+ answer.features.append(f._shift(length))
1012
+ del length
1013
+ for ref in other.dbxrefs:
1014
+ if ref not in answer.dbxrefs:
1015
+ answer.dbxrefs.append(ref)
1016
+
1017
+ # Take common id/name/description/annotation
1018
+ if self.id == other.id:
1019
+ answer.id = self.id
1020
+ if self.name == other.name:
1021
+ answer.name = self.name
1022
+ if self.description == other.description:
1023
+ answer.description = self.description
1024
+ for k, v in self.annotations.items():
1025
+ if k in other.annotations and other.annotations[k] == v:
1026
+ answer.annotations[k] = v
1027
+ # Can append matching per-letter-annotation
1028
+ try:
1029
+ # To make this type safe, we would need to make sure the types are compatible, eg: no adding tuples and str
1030
+ for k, v in self.letter_annotations.items(): # type: ignore
1031
+ if k in other.letter_annotations:
1032
+ # avoid length checks, but otherwise equivalent to answer.letter_annotations[k] = v + other.letter_annotations[k]
1033
+ dict.__setitem__(
1034
+ answer.letter_annotations,
1035
+ k,
1036
+ v + other.letter_annotations[k], # type: ignore
1037
+ )
1038
+ except TypeError:
1039
+ print("Failed while try to concatenate letter annotations")
1040
+ raise
1041
+
1042
+ return answer
1043
+
1044
+ def __radd__(self, other: Union["Seq", "MutableSeq", str]) -> "SeqRecord":
1045
+ """Add another sequence or string to this sequence (from the left).
1046
+
1047
+ This method handles adding a Seq object (or similar, e.g. MutableSeq)
1048
+ or a plain Python string (on the left) to a SeqRecord (on the right).
1049
+ See the __add__ method for more details, but for example:
1050
+
1051
+ >>> from Bio import SeqIO
1052
+ >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa")
1053
+ >>> print("%s %s" % (record.id, record.seq))
1054
+ slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN
1055
+ >>> print(list(record.letter_annotations))
1056
+ ['solexa_quality']
1057
+
1058
+ >>> new = "ACT" + record
1059
+ >>> print("%s %s" % (new.id, new.seq))
1060
+ slxa_0001_1_0001_01 ACTACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN
1061
+ >>> print(list(new.letter_annotations))
1062
+ []
1063
+ """
1064
+ if isinstance(other, SeqRecord):
1065
+ raise RuntimeError(
1066
+ "This should have happened via the __add__ of "
1067
+ "the other SeqRecord being added!"
1068
+ )
1069
+ if self.seq is None:
1070
+ raise TypeError("Can't add (right hand side) SeqRecord with seq = None")
1071
+ # Assume it is a string or a Seq.
1072
+ # Note can't transfer any per-letter-annotations
1073
+ offset = len(other)
1074
+ return type(self)(
1075
+ cast(Seq | MutableSeq, other + self.seq),
1076
+ id=self.id,
1077
+ name=self.name,
1078
+ description=self.description,
1079
+ features=[f._shift(offset) for f in self.features],
1080
+ annotations=self.annotations.copy(),
1081
+ dbxrefs=self.dbxrefs[:],
1082
+ )
1083
+
1084
+ def count(self, sub, start=None, end=None):
1085
+ """Return the number of non-overlapping occurrences of sub in seq[start:end].
1086
+
1087
+ Optional arguments start and end are interpreted as in slice notation.
1088
+ This method behaves as the count method of Python strings.
1089
+ """
1090
+ if self._seq is None:
1091
+ raise ValueError(
1092
+ "seq is SeqRecord is None, assign it a sequence before applying count"
1093
+ )
1094
+ return self.seq.count(sub, start, end)
1095
+
1096
+ def upper(self) -> "SeqRecord":
1097
+ """Return a copy of the record with an upper case sequence.
1098
+
1099
+ All the annotation is preserved unchanged. e.g.
1100
+
1101
+ >>> from Bio.Seq import Seq
1102
+ >>> from Bio.SeqRecord import SeqRecord
1103
+ >>> record = SeqRecord(Seq("acgtACGT"), id="Test",
1104
+ ... description = "Made up for this example")
1105
+ >>> record.letter_annotations["phred_quality"] = [1, 2, 3, 4, 5, 6, 7, 8]
1106
+ >>> print(record.upper().format("fastq"))
1107
+ @Test Made up for this example
1108
+ ACGTACGT
1109
+ +
1110
+ "#$%&'()
1111
+ <BLANKLINE>
1112
+
1113
+ Naturally, there is a matching lower method:
1114
+
1115
+ >>> print(record.lower().format("fastq"))
1116
+ @Test Made up for this example
1117
+ acgtacgt
1118
+ +
1119
+ "#$%&'()
1120
+ <BLANKLINE>
1121
+ """
1122
+ if self.seq is None:
1123
+ raise ValueError(
1124
+ "seq is SeqRecord is None, assign it a sequence before applying upper"
1125
+ )
1126
+ return self._from_validated(
1127
+ self.seq.upper(),
1128
+ id=self.id,
1129
+ name=self.name,
1130
+ description=self.description,
1131
+ dbxrefs=self.dbxrefs[:],
1132
+ features=self.features[:],
1133
+ annotations=self.annotations.copy(),
1134
+ letter_annotations=(
1135
+ None
1136
+ if self._per_letter_annotations is None
1137
+ else self.letter_annotations.copy()
1138
+ ),
1139
+ )
1140
+
1141
+ def lower(self) -> "SeqRecord":
1142
+ """Return a copy of the record with a lower case sequence.
1143
+
1144
+ All the annotation is preserved unchanged. e.g.
1145
+
1146
+ >>> from Bio import SeqIO
1147
+ >>> record = SeqIO.read("Fasta/aster.pro", "fasta")
1148
+ >>> print(record.format("fasta"))
1149
+ >gi|3298468|dbj|BAA31520.1| SAMIPF
1150
+ GGHVNPAVTFGAFVGGNITLLRGIVYIIAQLLGSTVACLLLKFVTNDMAVGVFSLSAGVG
1151
+ VTNALVFEIVMTFGLVYTVYATAIDPKKGSLGTIAPIAIGFIVGANI
1152
+ <BLANKLINE>
1153
+ >>> print(record.lower().format("fasta"))
1154
+ >gi|3298468|dbj|BAA31520.1| SAMIPF
1155
+ gghvnpavtfgafvggnitllrgivyiiaqllgstvaclllkfvtndmavgvfslsagvg
1156
+ vtnalvfeivmtfglvytvyataidpkkgslgtiapiaigfivgani
1157
+ <BLANKLINE>
1158
+
1159
+ To take a more annotation rich example,
1160
+
1161
+ >>> from Bio import SeqIO
1162
+ >>> old = SeqIO.read("EMBL/TRBG361.embl", "embl")
1163
+ >>> len(old.features)
1164
+ 3
1165
+ >>> new = old.lower()
1166
+ >>> len(old.features) == len(new.features)
1167
+ True
1168
+ >>> old.annotations["organism"] == new.annotations["organism"]
1169
+ True
1170
+ >>> old.dbxrefs == new.dbxrefs
1171
+ True
1172
+ """
1173
+ if self.seq is None:
1174
+ raise ValueError(
1175
+ "seq is SeqRecord is None, assign it a sequence before applying lower"
1176
+ )
1177
+ return self._from_validated(
1178
+ self.seq.lower(),
1179
+ id=self.id,
1180
+ name=self.name,
1181
+ description=self.description,
1182
+ dbxrefs=self.dbxrefs[:],
1183
+ features=self.features[:],
1184
+ annotations=self.annotations.copy(),
1185
+ letter_annotations=(
1186
+ None
1187
+ if self._per_letter_annotations is None
1188
+ else self.letter_annotations.copy()
1189
+ ),
1190
+ )
1191
+
1192
+ def isupper(self):
1193
+ """Return True if all ASCII characters in the record's sequence are uppercase.
1194
+
1195
+ If there are no cased characters, the method returns False.
1196
+ """
1197
+ return self.seq.isupper()
1198
+
1199
+ def islower(self):
1200
+ """Return True if all ASCII characters in the record's sequence are lowercase.
1201
+
1202
+ If there are no cased characters, the method returns False.
1203
+ """
1204
+ return self.seq.islower()
1205
+
1206
+ def reverse_complement(
1207
+ self,
1208
+ id: bool = False,
1209
+ name: bool = False,
1210
+ description: bool = False,
1211
+ features: bool = True,
1212
+ annotations: bool = False,
1213
+ letter_annotations: bool = True,
1214
+ dbxrefs: bool = False,
1215
+ ) -> "SeqRecord":
1216
+ """Return new SeqRecord with reverse complement sequence.
1217
+
1218
+ By default the new record does NOT preserve the sequence identifier,
1219
+ name, description, general annotation or database cross-references -
1220
+ these are unlikely to apply to the reversed sequence.
1221
+
1222
+ You can specify the returned record's id, name and description as
1223
+ strings, or True to keep that of the parent, or False for a default.
1224
+
1225
+ You can specify the returned record's features with a list of
1226
+ SeqFeature objects, or True to keep that of the parent, or False to
1227
+ omit them. The default is to keep the original features (with the
1228
+ strand and locations adjusted).
1229
+
1230
+ You can also specify both the returned record's annotations and
1231
+ letter_annotations as dictionaries, True to keep that of the parent,
1232
+ or False to omit them. The default is to keep the original
1233
+ annotations (with the letter annotations reversed).
1234
+
1235
+ To show what happens to the pre-letter annotations, consider an
1236
+ example Solexa variant FASTQ file with a single entry, which we'll
1237
+ read in as a SeqRecord:
1238
+
1239
+ >>> from Bio import SeqIO
1240
+ >>> record = SeqIO.read("Quality/solexa_faked.fastq", "fastq-solexa")
1241
+ >>> print("%s %s" % (record.id, record.seq))
1242
+ slxa_0001_1_0001_01 ACGTACGTACGTACGTACGTACGTACGTACGTACGTACGTNNNNNN
1243
+ >>> print(list(record.letter_annotations))
1244
+ ['solexa_quality']
1245
+ >>> print(record.letter_annotations["solexa_quality"])
1246
+ [40, 39, 38, 37, 36, 35, 34, 33, 32, 31, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5]
1247
+
1248
+ Now take the reverse complement, here we explicitly give a new
1249
+ identifier (the old identifier with a suffix):
1250
+
1251
+ >>> rc_record = record.reverse_complement(id=record.id + "_rc")
1252
+ >>> print("%s %s" % (rc_record.id, rc_record.seq))
1253
+ slxa_0001_1_0001_01_rc NNNNNNACGTACGTACGTACGTACGTACGTACGTACGTACGTACGT
1254
+
1255
+ Notice that the per-letter-annotations have also been reversed,
1256
+ although this may not be appropriate for all cases.
1257
+
1258
+ >>> print(rc_record.letter_annotations["solexa_quality"])
1259
+ [-5, -4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40]
1260
+
1261
+ Now for the features, we need a different example. Parsing a GenBank
1262
+ file is probably the easiest way to get an nice example with features
1263
+ in it...
1264
+
1265
+ >>> from Bio import SeqIO
1266
+ >>> with open("GenBank/pBAD30.gb") as handle:
1267
+ ... plasmid = SeqIO.read(handle, "gb")
1268
+ >>> print("%s %i" % (plasmid.id, len(plasmid)))
1269
+ pBAD30 4923
1270
+ >>> plasmid.seq
1271
+ Seq('GCTAGCGGAGTGTATACTGGCTTACTATGTTGGCACTGATGAGGGTGTCAGTGA...ATG')
1272
+ >>> len(plasmid.features)
1273
+ 13
1274
+
1275
+ Now, let's take the reverse complement of this whole plasmid:
1276
+
1277
+ >>> rc_plasmid = plasmid.reverse_complement(id=plasmid.id+"_rc")
1278
+ >>> print("%s %i" % (rc_plasmid.id, len(rc_plasmid)))
1279
+ pBAD30_rc 4923
1280
+ >>> rc_plasmid.seq
1281
+ Seq('CATGGGCAAATATTATACGCAAGGCGACAAGGTGCTGATGCCGCTGGCGATTCA...AGC')
1282
+ >>> len(rc_plasmid.features)
1283
+ 13
1284
+
1285
+ Let's compare the first CDS feature - it has gone from being the
1286
+ second feature (index 1) to the second last feature (index -2), its
1287
+ strand has changed, and the location switched round.
1288
+
1289
+ >>> print(plasmid.features[1])
1290
+ type: CDS
1291
+ location: [1081:1960](-)
1292
+ qualifiers:
1293
+ Key: label, Value: ['araC']
1294
+ Key: note, Value: ['araC regulator of the arabinose BAD promoter']
1295
+ Key: vntifkey, Value: ['4']
1296
+ <BLANKLINE>
1297
+ >>> print(rc_plasmid.features[-2])
1298
+ type: CDS
1299
+ location: [2963:3842](+)
1300
+ qualifiers:
1301
+ Key: label, Value: ['araC']
1302
+ Key: note, Value: ['araC regulator of the arabinose BAD promoter']
1303
+ Key: vntifkey, Value: ['4']
1304
+ <BLANKLINE>
1305
+
1306
+ You can check this new location, based on the length of the plasmid:
1307
+
1308
+ >>> len(plasmid) - 1081
1309
+ 3842
1310
+ >>> len(plasmid) - 1960
1311
+ 2963
1312
+
1313
+ Note that if the SeqFeature annotation includes any strand specific
1314
+ information (e.g. base changes for a SNP), this information is not
1315
+ amended, and would need correction after the reverse complement.
1316
+
1317
+ Note trying to reverse complement a protein SeqRecord raises an
1318
+ exception:
1319
+
1320
+ >>> from Bio.Seq import Seq
1321
+ >>> from Bio.SeqRecord import SeqRecord
1322
+ >>> protein_rec = SeqRecord(Seq("MAIVMGR"), id="Test",
1323
+ ... annotations={"molecule_type": "protein"})
1324
+ >>> protein_rec.reverse_complement()
1325
+ Traceback (most recent call last):
1326
+ ...
1327
+ ValueError: Proteins do not have complements!
1328
+
1329
+ If you have RNA without any U bases, it must be annotated as RNA
1330
+ otherwise it will be treated as DNA by default with A mapped to T:
1331
+
1332
+ >>> from Bio.Seq import Seq
1333
+ >>> from Bio.SeqRecord import SeqRecord
1334
+ >>> rna1 = SeqRecord(Seq("ACG"), id="Test")
1335
+ >>> rna2 = SeqRecord(Seq("ACG"), id="Test", annotations={"molecule_type": "RNA"})
1336
+ >>> print(rna1.reverse_complement(id="RC", description="unk").format("fasta"))
1337
+ >RC unk
1338
+ CGT
1339
+ <BLANKLINE>
1340
+ >>> print(rna2.reverse_complement(id="RC", description="RNA").format("fasta"))
1341
+ >RC RNA
1342
+ CGU
1343
+ <BLANKLINE>
1344
+
1345
+ Also note you can reverse complement a SeqRecord using a MutableSeq:
1346
+
1347
+ >>> from Bio.Seq import MutableSeq
1348
+ >>> from Bio.SeqRecord import SeqRecord
1349
+ >>> rec = SeqRecord(MutableSeq("ACGT"), id="Test")
1350
+ >>> rec.seq[0] = "T"
1351
+ >>> print("%s %s" % (rec.id, rec.seq))
1352
+ Test TCGT
1353
+ >>> rc = rec.reverse_complement(id=True)
1354
+ >>> print("%s %s" % (rc.id, rc.seq))
1355
+ Test ACGA
1356
+ """
1357
+
1358
+ if self.seq is None:
1359
+ raise ValueError(
1360
+ "Seq in SeqRecord is None, so can't construct the reverse_complement. Please assign it a sequence first"
1361
+ )
1362
+
1363
+ if "protein" in cast(str, self.annotations.get("molecule_type", "")):
1364
+ raise ValueError("Proteins do not have complements!")
1365
+ if "RNA" in cast(str, self.annotations.get("molecule_type", "")):
1366
+ seq = self.seq.reverse_complement_rna()
1367
+ else:
1368
+ # Default to DNA
1369
+ seq = self.seq.reverse_complement()
1370
+ if isinstance(self.seq, MutableSeq):
1371
+ seq = Seq(seq)
1372
+ answer = self._from_validated(seq)
1373
+ if isinstance(id, str):
1374
+ answer.id = id
1375
+ elif id:
1376
+ answer.id = self.id
1377
+ if isinstance(name, str):
1378
+ answer.name = name
1379
+ elif name:
1380
+ answer.name = self.name
1381
+ if isinstance(description, str):
1382
+ answer.description = description
1383
+ elif description:
1384
+ answer.description = self.description
1385
+ if isinstance(dbxrefs, list):
1386
+ answer.dbxrefs = dbxrefs
1387
+ elif dbxrefs:
1388
+ # Copy the old dbxrefs
1389
+ answer.dbxrefs = self.dbxrefs[:]
1390
+ if isinstance(features, list):
1391
+ answer.features = features
1392
+ elif features:
1393
+ # Copy the old features, adjusting location and string
1394
+ length = len(answer)
1395
+ answer.features = [f._flip(length) for f in self.features]
1396
+
1397
+ # The old list should have been sorted by start location,
1398
+ # reversing it will leave it sorted by what is now the end position,
1399
+ # so we need to resort in case of overlapping features.
1400
+ # NOTE - In the common case of gene before CDS (and similar) with
1401
+ # the exact same locations, this will still maintain gene before CDS
1402
+
1403
+ def key_fun(f):
1404
+ """Sort on start position."""
1405
+ try:
1406
+ return int(f.location.start)
1407
+ except TypeError: # Expected for UnknownPosition
1408
+ return None
1409
+
1410
+ answer.features.sort(key=key_fun)
1411
+ if isinstance(annotations, dict):
1412
+ answer.annotations = annotations
1413
+ elif annotations:
1414
+ # Copy the old annotations,
1415
+ answer.annotations = self.annotations.copy()
1416
+ if self._per_letter_annotations is not None:
1417
+ if isinstance(letter_annotations, dict):
1418
+ answer.letter_annotations = letter_annotations
1419
+ elif letter_annotations:
1420
+ # Copy the old per letter annotations, reversing them
1421
+ for key, value in self.letter_annotations.items():
1422
+ answer.letter_annotations[key] = value[::-1]
1423
+ return answer
1424
+
1425
+ def translate(
1426
+ self,
1427
+ # Seq translation arguments:
1428
+ table: str = "Standard",
1429
+ stop_symbol: str = "*",
1430
+ to_stop: bool = False,
1431
+ cds: bool = False,
1432
+ gap: str | None = None,
1433
+ # SeqRecord annotation arguments:
1434
+ id: bool = False,
1435
+ name: bool = False,
1436
+ description: bool = False,
1437
+ features: bool = False,
1438
+ annotations: bool = False,
1439
+ letter_annotations: bool = False,
1440
+ dbxrefs: bool = False,
1441
+ ) -> "SeqRecord":
1442
+ """Return new SeqRecord with translated sequence.
1443
+
1444
+ This calls the record's .seq.translate() method (which describes
1445
+ the translation related arguments, like table for the genetic code),
1446
+
1447
+ By default the new record does NOT preserve the sequence identifier,
1448
+ name, description, general annotation or database cross-references -
1449
+ these are unlikely to apply to the translated sequence.
1450
+
1451
+ You can specify the returned record's id, name and description as
1452
+ strings, or True to keep that of the parent, or False for a default.
1453
+
1454
+ You can specify the returned record's features with a list of
1455
+ SeqFeature objects, or False (default) to omit them.
1456
+
1457
+ You can also specify both the returned record's annotations and
1458
+ letter_annotations as dictionaries, True to keep that of the parent
1459
+ (annotations only), or False (default) to omit them.
1460
+
1461
+ e.g. Loading a FASTA gene and translating it,
1462
+
1463
+ >>> from Bio import SeqIO
1464
+ >>> gene_record = SeqIO.read("Fasta/sweetpea.nu", "fasta")
1465
+ >>> print(gene_record.format("fasta"))
1466
+ >gi|3176602|gb|U78617.1|LOU78617 Lathyrus odoratus phytochrome A (PHYA) gene, partial cds
1467
+ CAGGCTGCGCGGTTTCTATTTATGAAGAACAAGGTCCGTATGATAGTTGATTGTCATGCA
1468
+ AAACATGTGAAGGTTCTTCAAGACGAAAAACTCCCATTTGATTTGACTCTGTGCGGTTCG
1469
+ ACCTTAAGAGCTCCACATAGTTGCCATTTGCAGTACATGGCTAACATGGATTCAATTGCT
1470
+ TCATTGGTTATGGCAGTGGTCGTCAATGACAGCGATGAAGATGGAGATAGCCGTGACGCA
1471
+ GTTCTACCACAAAAGAAAAAGAGACTTTGGGGTTTGGTAGTTTGTCATAACACTACTCCG
1472
+ AGGTTTGTT
1473
+ <BLANKLINE>
1474
+
1475
+ And now translating the record, specifying the new ID and description:
1476
+
1477
+ >>> protein_record = gene_record.translate(table=11,
1478
+ ... id="phya",
1479
+ ... description="translation")
1480
+ >>> print(protein_record.format("fasta"))
1481
+ >phya translation
1482
+ QAARFLFMKNKVRMIVDCHAKHVKVLQDEKLPFDLTLCGSTLRAPHSCHLQYMANMDSIA
1483
+ SLVMAVVVNDSDEDGDSRDAVLPQKKKRLWGLVVCHNTTPRFV
1484
+ <BLANKLINE>
1485
+
1486
+ """
1487
+ if "protein" == self.annotations.get("molecule_type", ""):
1488
+ raise ValueError("Proteins cannot be translated!")
1489
+
1490
+ if self.seq is None:
1491
+ raise ValueError("Seq in SeqRecord is None, can't be translated")
1492
+
1493
+ answer = SeqRecord(
1494
+ self.seq.translate(
1495
+ table=table, stop_symbol=stop_symbol, to_stop=to_stop, cds=cds, gap=gap
1496
+ )
1497
+ )
1498
+ if isinstance(id, str):
1499
+ answer.id = id
1500
+ elif id:
1501
+ answer.id = self.id
1502
+ if isinstance(name, str):
1503
+ answer.name = name
1504
+ elif name:
1505
+ answer.name = self.name
1506
+ if isinstance(description, str):
1507
+ answer.description = description
1508
+ elif description:
1509
+ answer.description = self.description
1510
+ if isinstance(dbxrefs, list):
1511
+ answer.dbxrefs = dbxrefs
1512
+ elif dbxrefs:
1513
+ # Copy the old dbxrefs
1514
+ answer.dbxrefs = self.dbxrefs[:]
1515
+ if isinstance(features, list):
1516
+ answer.features = features
1517
+ elif features:
1518
+ # Does not make sense to copy old features as locations wrong
1519
+ raise TypeError(f"Unexpected features argument {features!r}")
1520
+ if isinstance(annotations, dict):
1521
+ answer.annotations = annotations
1522
+ elif annotations:
1523
+ # Copy the old annotations
1524
+ answer.annotations = self.annotations.copy()
1525
+ # Set/update to protein:
1526
+ answer.annotations["molecule_type"] = "protein"
1527
+ if self._per_letter_annotations is not None:
1528
+ if isinstance(letter_annotations, dict):
1529
+ answer.letter_annotations = letter_annotations
1530
+ elif letter_annotations:
1531
+ # Does not make sense to copy these as length now wrong
1532
+ raise TypeError(
1533
+ f"Unexpected letter_annotations argument {letter_annotations!r}"
1534
+ )
1535
+ return answer
1536
+
1537
+
1538
+ if __name__ == "__main__":
1539
+ from Bio._utils import run_doctest
1540
+
1541
+ run_doctest()
.venv_haddock/lib/python3.12/site-packages/Bio/__init__.py ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 1999-2003 by Jeffrey Chang. All rights reserved.
2
+ #
3
+ # This file is part of the Biopython distribution and governed by your
4
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
5
+ # Please see the LICENSE file that should have been included as part of this
6
+ # package.
7
+ """Collection of modules for dealing with biological data in Python.
8
+
9
+ The Biopython Project is an international association of developers
10
+ of freely available Python tools for computational molecular biology.
11
+
12
+ https://biopython.org
13
+ """
14
+
15
+ import os
16
+ import warnings
17
+
18
+ __version__ = "1.87"
19
+
20
+
21
+ class MissingExternalDependencyError(Exception):
22
+ """Missing an external dependency.
23
+
24
+ Used for things like missing command line tools. Important for our unit
25
+ tests to allow skipping tests with missing external dependencies.
26
+ """
27
+
28
+
29
+ class MissingPythonDependencyError(MissingExternalDependencyError, ImportError):
30
+ """Missing an external python dependency (subclass of ImportError).
31
+
32
+ Used for missing Python modules (rather than just a typical ImportError).
33
+ Important for our unit tests to allow skipping tests with missing external
34
+ python dependencies, while also allowing the exception to be caught as an
35
+ ImportError.
36
+ """
37
+
38
+
39
+ class StreamModeError(ValueError):
40
+ """Incorrect stream mode (text vs binary).
41
+
42
+ This error should be raised when a stream (file or file-like object)
43
+ argument is in text mode while the receiving function expects binary mode,
44
+ or vice versa.
45
+ """
46
+
47
+
48
+ class BiopythonWarning(Warning):
49
+ """Biopython warning.
50
+
51
+ Biopython should use this warning (or subclasses of it), making it easy to
52
+ silence all our warning messages should you wish to:
53
+
54
+ >>> import warnings
55
+ >>> from Bio import BiopythonWarning
56
+ >>> warnings.simplefilter('ignore', BiopythonWarning)
57
+
58
+ Consult the warnings module documentation for more details.
59
+ """
60
+
61
+
62
+ class BiopythonParserWarning(BiopythonWarning):
63
+ """Biopython parser warning.
64
+
65
+ Some in-valid data files cannot be parsed and will trigger an exception.
66
+ Where a reasonable interpretation is possible, Biopython will issue this
67
+ warning to indicate a potential problem. To silence these warnings, use:
68
+
69
+ >>> import warnings
70
+ >>> from Bio import BiopythonParserWarning
71
+ >>> warnings.simplefilter('ignore', BiopythonParserWarning)
72
+
73
+ Consult the warnings module documentation for more details.
74
+ """
75
+
76
+
77
+ class BiopythonDeprecationWarning(BiopythonWarning):
78
+ """Biopython deprecation warning.
79
+
80
+ Biopython uses this warning instead of the built in DeprecationWarning
81
+ since those are ignored by default since Python 2.7.
82
+
83
+ To silence all our deprecation warning messages, use:
84
+
85
+ >>> import warnings
86
+ >>> from Bio import BiopythonDeprecationWarning
87
+ >>> warnings.simplefilter('ignore', BiopythonDeprecationWarning)
88
+
89
+ Code marked as deprecated is likely to be removed in a future version
90
+ of Biopython. To avoid removal of this code, please contact the Biopython
91
+ developers via the mailing list or GitHub.
92
+ """
93
+
94
+
95
+ class BiopythonExperimentalWarning(BiopythonWarning):
96
+ """Biopython experimental code warning.
97
+
98
+ Biopython uses this warning for experimental code ('alpha' or 'beta'
99
+ level code) which is released as part of the standard releases to mark
100
+ sub-modules or functions for early adopters to test & give feedback.
101
+
102
+ Code issuing this warning is likely to change (or even be removed) in
103
+ a subsequent release of Biopython. Such code should NOT be used for
104
+ production/stable code. It should only be used if:
105
+
106
+ - You are running the latest release of Biopython, or ideally the
107
+ latest code from our repository.
108
+ - You are subscribed to the biopython-dev mailing list to provide
109
+ feedback on this code, and to be alerted of changes to it.
110
+
111
+ If all goes well, experimental code would be promoted to stable in
112
+ a subsequent release, and this warning removed from it.
113
+ """
114
+
115
+
116
+ _parent_dir = os.path.dirname(os.path.dirname(__file__))
117
+ if os.path.exists(os.path.join(_parent_dir, "pyproject.toml")):
118
+ # Looks like we are running from our source directory,
119
+ # a bad idea except if installed in development mode.
120
+ #
121
+ # See https://setuptools.readthedocs.io/en/latest/userguide/development_mode.html
122
+ # Do we have .../site-packages/biopython.egg-link present?
123
+ #
124
+ # Note "pip install -e ." currently calls setuptools internally
125
+ import site
126
+
127
+ _dev_mode = False
128
+ for _p in site.getsitepackages():
129
+ if os.path.isfile(os.path.join(_p, "biopython.egg-link")):
130
+ _dev_mode = True
131
+ break
132
+ # Also check the user specific site packages
133
+ if not _dev_mode and os.path.isfile(
134
+ os.path.join(site.getusersitepackages(), "biopython.egg-link")
135
+ ):
136
+ _dev_mode = True
137
+ if not _dev_mode:
138
+ warnings.warn(
139
+ "You may be importing Biopython from inside the source tree."
140
+ " This is bad practice and might lead to downstream issues."
141
+ " In particular, you might encounter ImportErrors due to"
142
+ " missing compiled C extensions. We recommend that you"
143
+ " try running your code from outside the source tree."
144
+ " If you are outside the source tree then you have a"
145
+ " pyproject.toml file in an unexpected directory: " + _parent_dir,
146
+ BiopythonWarning,
147
+ )
.venv_haddock/lib/python3.12/site-packages/Bio/_utils.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2010 by Eric Talevich. All rights reserved.
2
+ # Copyright 2012 by Wibowo Arindrarto. All rights reserved.
3
+ #
4
+ # This file is part of the Biopython distribution and governed by your
5
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
6
+ # Please see the LICENSE file that should have been included as part of this
7
+ # package.
8
+ """Common utility functions for various Bio submodules."""
9
+
10
+ import os
11
+ from typing import Any
12
+ from collections.abc import Callable
13
+ from typing import cast
14
+ from typing import Optional
15
+ from typing import Protocol
16
+ from typing import TypeVar
17
+
18
+ # workaround type checking method attributes from https://github.com/python/mypy/issues/2087#issuecomment-587741762
19
+
20
+ F = TypeVar("F", bound=Callable[..., object])
21
+
22
+
23
+ class _FunctionWithPrevious(Protocol[F]):
24
+ previous: int | None
25
+ __call__: F
26
+
27
+
28
+ def function_with_previous(func: F) -> _FunctionWithPrevious[F]:
29
+ """Decorate a function as having an attribute named 'previous'."""
30
+ function_with_previous = cast(_FunctionWithPrevious[F], func)
31
+ # Make sure the cast isn't a lie.
32
+ function_with_previous.previous = None
33
+ return function_with_previous
34
+
35
+
36
+ def find_test_dir(start_dir: str | None = None) -> str:
37
+ """Find the absolute path of Biopython's Tests directory.
38
+
39
+ Arguments:
40
+ start_dir -- Initial directory to begin lookup (default to current dir)
41
+
42
+ If the directory is not found up the filesystem's root directory, an
43
+ exception will be raised.
44
+
45
+ """
46
+ if not start_dir:
47
+ # no callbacks in function signatures!
48
+ # defaults to the current directory
49
+ # (using __file__ would give the installed Biopython)
50
+ start_dir = "."
51
+
52
+ target = os.path.abspath(start_dir)
53
+ while True:
54
+ if os.path.isdir(os.path.join(target, "Bio")) and os.path.isdir(
55
+ os.path.join(target, "Tests")
56
+ ):
57
+ # Good, we're in the Biopython root now
58
+ return os.path.abspath(os.path.join(target, "Tests"))
59
+ # Recurse up the tree
60
+ # TODO - Test this on Windows
61
+ new, tmp = os.path.split(target)
62
+ if target == new:
63
+ # Reached root
64
+ break
65
+ target = new
66
+ raise ValueError(
67
+ f"Not within Biopython source tree: {os.path.abspath(start_dir)!r}"
68
+ )
69
+
70
+
71
+ def run_doctest(target_dir: str | None = None, *args: Any, **kwargs: Any) -> None:
72
+ """Run doctest for the importing module."""
73
+ import doctest
74
+
75
+ # default doctest options
76
+ doctest_attributes: dict[str, Any] = {"optionflags": doctest.ELLIPSIS}
77
+ doctest_attributes.update(kwargs)
78
+
79
+ cur_dir = os.path.abspath(os.curdir)
80
+
81
+ print("Running doctests...")
82
+ try:
83
+ os.chdir(find_test_dir(target_dir))
84
+ doctest.testmod(*args, **doctest_attributes)
85
+ finally:
86
+ # and revert back to initial directory
87
+ os.chdir(cur_dir)
88
+ print("Done")
89
+
90
+
91
+ if __name__ == "__main__":
92
+ run_doctest()
.venv_haddock/lib/python3.12/site-packages/Bio/bgzf.py ADDED
@@ -0,0 +1,960 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # Copyright 2010-2018 by Peter Cock.
3
+ # All rights reserved.
4
+ #
5
+ # This file is part of the Biopython distribution and governed by your
6
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
7
+ # Please see the LICENSE file that should have been included as part of this
8
+ # package.
9
+ r"""Read and write BGZF compressed files (the GZIP variant used in BAM).
10
+
11
+ The SAM/BAM file format (Sequence Alignment/Map) comes in a plain text
12
+ format (SAM), and a compressed binary format (BAM). The latter uses a
13
+ modified form of gzip compression called BGZF (Blocked GNU Zip Format),
14
+ which can be applied to any file format to provide compression with
15
+ efficient random access. BGZF is described together with the SAM/BAM
16
+ file format at https://samtools.sourceforge.net/SAM1.pdf
17
+
18
+ Please read the text below about 'virtual offsets' before using BGZF
19
+ files for random access.
20
+
21
+ Aim of this module
22
+ ------------------
23
+ The Python gzip library can be used to read BGZF files, since for
24
+ decompression they are just (specialised) gzip files. What this
25
+ module aims to facilitate is random access to BGZF files (using the
26
+ 'virtual offset' idea), and writing BGZF files (which means using
27
+ suitably sized gzip blocks and writing the extra 'BC' field in the
28
+ gzip headers). As in the gzip library, the zlib library is used
29
+ internally.
30
+
31
+ In addition to being required for random access to and writing of
32
+ BAM files, the BGZF format can also be used on other sequential
33
+ data (in the sense of one record after another), such as most of
34
+ the sequence data formats supported in Bio.SeqIO (like FASTA,
35
+ FASTQ, GenBank, etc) or large MAF alignments.
36
+
37
+ The Bio.SeqIO indexing functions use this module to support BGZF files.
38
+
39
+ Technical Introduction to BGZF
40
+ ------------------------------
41
+ The gzip file format allows multiple compressed blocks, each of which
42
+ could be a stand alone gzip file. As an interesting bonus, this means
43
+ you can use Unix ``cat`` to combine two or more gzip files into one by
44
+ concatenating them. Also, each block can have one of several compression
45
+ levels (including uncompressed, which actually takes up a little bit
46
+ more space due to the gzip header).
47
+
48
+ What the BAM designers realised was that while random access to data
49
+ stored in traditional gzip files was slow, breaking the file into
50
+ gzip blocks would allow fast random access to each block. To access
51
+ a particular piece of the decompressed data, you just need to know
52
+ which block it starts in (the offset of the gzip block start), and
53
+ how far into the (decompressed) contents of the block you need to
54
+ read.
55
+
56
+ One problem with this is finding the gzip block sizes efficiently.
57
+ You can do it with a standard gzip file, but it requires every block
58
+ to be decompressed -- and that would be rather slow. Additionally
59
+ typical gzip files may use very large blocks.
60
+
61
+ All that differs in BGZF is that compressed size of each gzip block
62
+ is limited to 2^16 bytes, and an extra 'BC' field in the gzip header
63
+ records this size. Traditional decompression tools can ignore this,
64
+ and unzip the file just like any other gzip file.
65
+
66
+ The point of this is you can look at the first BGZF block, find out
67
+ how big it is from this 'BC' header, and thus seek immediately to
68
+ the second block, and so on.
69
+
70
+ The BAM indexing scheme records read positions using a 64 bit
71
+ 'virtual offset', comprising ``coffset << 16 | uoffset``, where ``coffset``
72
+ is the file offset of the BGZF block containing the start of the read
73
+ (unsigned integer using up to 64-16 = 48 bits), and ``uoffset`` is the
74
+ offset within the (decompressed) block (unsigned 16 bit integer).
75
+
76
+ This limits you to BAM files where the last block starts by 2^48
77
+ bytes, or 256 petabytes, and the decompressed size of each block
78
+ is at most 2^16 bytes, or 64kb. Note that this matches the BGZF
79
+ 'BC' field size which limits the compressed size of each block to
80
+ 2^16 bytes, allowing for BAM files to use BGZF with no gzip
81
+ compression (useful for intermediate files in memory to reduce
82
+ CPU load).
83
+
84
+ Warning about namespaces
85
+ ------------------------
86
+ It is considered a bad idea to use "from XXX import ``*``" in Python, because
87
+ it pollutes the namespace. This is a real issue with Bio.bgzf (and the
88
+ standard Python library gzip) because they contain a function called open
89
+ i.e. Suppose you do this:
90
+
91
+ >>> from Bio.bgzf import *
92
+ >>> print(open.__module__)
93
+ Bio.bgzf
94
+
95
+ Or,
96
+
97
+ >>> from gzip import *
98
+ >>> print(open.__module__)
99
+ gzip
100
+
101
+ Notice that the open function has been replaced. You can "fix" this if you
102
+ need to by importing the built-in open function:
103
+
104
+ >>> from builtins import open
105
+
106
+ However, what we recommend instead is to use the explicit namespace, e.g.
107
+
108
+ >>> from Bio import bgzf
109
+ >>> print(bgzf.open.__module__)
110
+ Bio.bgzf
111
+
112
+
113
+ Examples
114
+ --------
115
+ This is an ordinary GenBank file compressed using BGZF, so it can
116
+ be decompressed using gzip,
117
+
118
+ >>> import gzip
119
+ >>> handle = gzip.open("GenBank/NC_000932.gb.bgz", "r")
120
+ >>> assert 0 == handle.tell()
121
+ >>> line = handle.readline()
122
+ >>> assert 80 == handle.tell()
123
+ >>> line = handle.readline()
124
+ >>> assert 143 == handle.tell()
125
+ >>> data = handle.read(70000)
126
+ >>> assert 70143 == handle.tell()
127
+ >>> handle.close()
128
+
129
+ We can also access the file using the BGZF reader - but pay
130
+ attention to the file offsets which will be explained below:
131
+
132
+ >>> handle = BgzfReader("GenBank/NC_000932.gb.bgz", "r")
133
+ >>> assert 0 == handle.tell()
134
+ >>> print(handle.readline().rstrip())
135
+ LOCUS NC_000932 154478 bp DNA circular PLN 15-APR-2009
136
+ >>> assert 80 == handle.tell()
137
+ >>> print(handle.readline().rstrip())
138
+ DEFINITION Arabidopsis thaliana chloroplast, complete genome.
139
+ >>> assert 143 == handle.tell()
140
+ >>> data = handle.read(70000)
141
+ >>> assert 987828735 == handle.tell()
142
+ >>> print(handle.readline().rstrip())
143
+ f="GeneID:844718"
144
+ >>> print(handle.readline().rstrip())
145
+ CDS complement(join(84337..84771,85454..85843))
146
+ >>> offset = handle.seek(make_virtual_offset(55074, 126))
147
+ >>> print(handle.readline().rstrip())
148
+ 68521 tatgtcattc gaaattgtat aaagacaact cctatttaat agagctattt gtgcaagtat
149
+ >>> handle.close()
150
+
151
+ Notice the handle's offset looks different as a BGZF file. This
152
+ brings us to the key point about BGZF, which is the block structure:
153
+
154
+ >>> handle = open("GenBank/NC_000932.gb.bgz", "rb")
155
+ >>> for values in BgzfBlocks(handle):
156
+ ... print("Raw start %i, raw length %i; data start %i, data length %i" % values)
157
+ Raw start 0, raw length 15073; data start 0, data length 65536
158
+ Raw start 15073, raw length 17857; data start 65536, data length 65536
159
+ Raw start 32930, raw length 22144; data start 131072, data length 65536
160
+ Raw start 55074, raw length 22230; data start 196608, data length 65536
161
+ Raw start 77304, raw length 14939; data start 262144, data length 43478
162
+ Raw start 92243, raw length 28; data start 305622, data length 0
163
+ >>> handle.close()
164
+
165
+ In this example the first three blocks are 'full' and hold 65536 bytes
166
+ of uncompressed data. The fourth block isn't full and holds 43478 bytes.
167
+ Finally there is a special empty fifth block which takes 28 bytes on
168
+ disk and serves as an 'end of file' (EOF) marker. If this is missing,
169
+ it is possible your BGZF file is incomplete.
170
+
171
+ By reading ahead 70,000 bytes we moved into the second BGZF block,
172
+ and at that point the BGZF virtual offsets start to look different
173
+ to a simple offset into the decompressed data as exposed by the gzip
174
+ library.
175
+
176
+ As an example, consider seeking to the decompressed position 196734.
177
+ Since 196734 = 65536 + 65536 + 65536 + 126 = 65536*3 + 126, this
178
+ is equivalent to jumping the first three blocks (which in this
179
+ specific example are all size 65536 after decompression - which
180
+ does not always hold) and starting at byte 126 of the fourth block
181
+ (after decompression). For BGZF, we need to know the fourth block's
182
+ offset of 55074 and the offset within the block of 126 to get the
183
+ BGZF virtual offset.
184
+
185
+ >>> print(55074 << 16 | 126)
186
+ 3609329790
187
+ >>> print(bgzf.make_virtual_offset(55074, 126))
188
+ 3609329790
189
+
190
+ Thus for this BGZF file, decompressed position 196734 corresponds
191
+ to the virtual offset 3609329790. However, another BGZF file with
192
+ different contents would have compressed more or less efficiently,
193
+ so the compressed blocks would be different sizes. What this means
194
+ is the mapping between the uncompressed offset and the compressed
195
+ virtual offset depends on the BGZF file you are using.
196
+
197
+ If you are accessing a BGZF file via this module, just use the
198
+ handle.tell() method to note the virtual offset of a position you
199
+ may later want to return to using handle.seek().
200
+
201
+ The catch with BGZF virtual offsets is while they can be compared
202
+ (which offset comes first in the file), you cannot safely subtract
203
+ them to get the size of the data between them, nor add/subtract
204
+ a relative offset.
205
+
206
+ Of course you can parse this file with Bio.SeqIO using BgzfReader,
207
+ although there isn't any benefit over using gzip.open(...), unless
208
+ you want to index BGZF compressed sequence files:
209
+
210
+ >>> from Bio import SeqIO
211
+ >>> handle = BgzfReader("GenBank/NC_000932.gb.bgz")
212
+ >>> record = SeqIO.read(handle, "genbank")
213
+ >>> handle.close()
214
+ >>> print(record.id)
215
+ NC_000932.1
216
+
217
+ Text Mode
218
+ ---------
219
+
220
+ Like the standard library gzip.open(...), the BGZF code defaults to opening
221
+ files in binary mode.
222
+
223
+ You can request the file be opened in text mode, but beware that this is hard
224
+ coded to the simple "latin1" (aka "iso-8859-1") encoding (which includes all
225
+ the ASCII characters), which works well with most Western European languages.
226
+ However, it is not fully compatible with the more widely used UTF-8 encoding.
227
+
228
+ In variable width encodings like UTF-8, some single characters in the unicode
229
+ text output are represented by multiple bytes in the raw binary form. This is
230
+ problematic with BGZF, as we cannot always decode each block in isolation - a
231
+ single unicode character could be split over two blocks. This can even happen
232
+ with fixed width unicode encodings, as the BGZF block size is not fixed.
233
+
234
+ Therefore, this module is currently restricted to only support single byte
235
+ unicode encodings, such as ASCII, "latin1" (which is a superset of ASCII), or
236
+ potentially other character maps (not implemented).
237
+
238
+ Furthermore, unlike the default text mode on Python 3, we do not attempt to
239
+ implement universal new line mode. This transforms the various operating system
240
+ new line conventions like Windows (CR LF or "\r\n"), Unix (just LF, "\n"), or
241
+ old Macs (just CR, "\r"), into just LF ("\n"). Here we have the same problem -
242
+ is "\r" at the end of a block an incomplete Windows style new line?
243
+
244
+ Instead, you will get the CR ("\r") and LF ("\n") characters as is.
245
+
246
+ If your data is in UTF-8 or any other incompatible encoding, you must use
247
+ binary mode, and decode the appropriate fragments yourself.
248
+ """
249
+
250
+ import io
251
+ import struct
252
+ import sys
253
+ import zlib
254
+ from builtins import open as _open
255
+
256
+ _bgzf_magic = b"\x1f\x8b\x08\x04"
257
+ _bgzf_header = b"\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00\x42\x43\x02\x00"
258
+ _bgzf_eof = b"\x1f\x8b\x08\x04\x00\x00\x00\x00\x00\xff\x06\x00BC\x02\x00\x1b\x00\x03\x00\x00\x00\x00\x00\x00\x00\x00\x00"
259
+ _bytes_BC = b"BC"
260
+
261
+
262
+ def open(filename, mode="rb"):
263
+ r"""Open a BGZF file for reading, writing or appending.
264
+
265
+ If text mode is requested, in order to avoid multi-byte characters, this is
266
+ hard coded to use the "latin1" encoding, and "\r" and "\n" are passed as is
267
+ (without implementing universal new line mode).
268
+
269
+ If your data is in UTF-8 or any other incompatible encoding, you must use
270
+ binary mode, and decode the appropriate fragments yourself.
271
+ """
272
+ if "r" in mode.lower():
273
+ return BgzfReader(filename, mode)
274
+ elif "w" in mode.lower() or "a" in mode.lower():
275
+ return BgzfWriter(filename, mode)
276
+ else:
277
+ raise ValueError(f"Bad mode {mode!r}")
278
+
279
+
280
+ def make_virtual_offset(block_start_offset, within_block_offset):
281
+ """Compute a BGZF virtual offset from block start and within block offsets.
282
+
283
+ The BAM indexing scheme records read positions using a 64 bit
284
+ 'virtual offset', comprising in C terms:
285
+
286
+ block_start_offset << 16 | within_block_offset
287
+
288
+ Here block_start_offset is the file offset of the BGZF block
289
+ start (unsigned integer using up to 64-16 = 48 bits), and
290
+ within_block_offset within the (decompressed) block (unsigned
291
+ 16 bit integer).
292
+
293
+ >>> make_virtual_offset(0, 0)
294
+ 0
295
+ >>> make_virtual_offset(0, 1)
296
+ 1
297
+ >>> make_virtual_offset(0, 2**16 - 1)
298
+ 65535
299
+ >>> make_virtual_offset(0, 2**16)
300
+ Traceback (most recent call last):
301
+ ...
302
+ ValueError: Require 0 <= within_block_offset < 2**16, got 65536
303
+
304
+ >>> 65536 == make_virtual_offset(1, 0)
305
+ True
306
+ >>> 65537 == make_virtual_offset(1, 1)
307
+ True
308
+ >>> 131071 == make_virtual_offset(1, 2**16 - 1)
309
+ True
310
+
311
+ >>> 6553600000 == make_virtual_offset(100000, 0)
312
+ True
313
+ >>> 6553600001 == make_virtual_offset(100000, 1)
314
+ True
315
+ >>> 6553600010 == make_virtual_offset(100000, 10)
316
+ True
317
+
318
+ >>> make_virtual_offset(2**48, 0)
319
+ Traceback (most recent call last):
320
+ ...
321
+ ValueError: Require 0 <= block_start_offset < 2**48, got 281474976710656
322
+
323
+ """
324
+ if within_block_offset < 0 or within_block_offset >= 65536:
325
+ raise ValueError(
326
+ "Require 0 <= within_block_offset < 2**16, got %i" % within_block_offset
327
+ )
328
+ if block_start_offset < 0 or block_start_offset >= 281474976710656:
329
+ raise ValueError(
330
+ "Require 0 <= block_start_offset < 2**48, got %i" % block_start_offset
331
+ )
332
+ return (block_start_offset << 16) | within_block_offset
333
+
334
+
335
+ def split_virtual_offset(virtual_offset):
336
+ """Divides a 64-bit BGZF virtual offset into block start & within block offsets.
337
+
338
+ >>> (100000, 0) == split_virtual_offset(6553600000)
339
+ True
340
+ >>> (100000, 10) == split_virtual_offset(6553600010)
341
+ True
342
+
343
+ """
344
+ start = virtual_offset >> 16
345
+ return start, virtual_offset ^ (start << 16)
346
+
347
+
348
+ def BgzfBlocks(handle):
349
+ """Low level debugging function to inspect BGZF blocks.
350
+
351
+ Expects a BGZF compressed file opened in binary read mode using
352
+ the builtin open function. Do not use a handle from this bgzf
353
+ module or the gzip module's open function which will decompress
354
+ the file.
355
+
356
+ Returns the block start offset (see virtual offsets), the block
357
+ length (add these for the start of the next block), and the
358
+ decompressed length of the blocks contents (limited to 65536 in
359
+ BGZF), as an iterator - one tuple per BGZF block.
360
+
361
+ >>> from builtins import open
362
+ >>> handle = open("SamBam/ex1.bam", "rb")
363
+ >>> for values in BgzfBlocks(handle):
364
+ ... print("Raw start %i, raw length %i; data start %i, data length %i" % values)
365
+ Raw start 0, raw length 18239; data start 0, data length 65536
366
+ Raw start 18239, raw length 18223; data start 65536, data length 65536
367
+ Raw start 36462, raw length 18017; data start 131072, data length 65536
368
+ Raw start 54479, raw length 17342; data start 196608, data length 65536
369
+ Raw start 71821, raw length 17715; data start 262144, data length 65536
370
+ Raw start 89536, raw length 17728; data start 327680, data length 65536
371
+ Raw start 107264, raw length 17292; data start 393216, data length 63398
372
+ Raw start 124556, raw length 28; data start 456614, data length 0
373
+ >>> handle.close()
374
+
375
+ Indirectly we can tell this file came from an old version of
376
+ samtools because all the blocks (except the final one and the
377
+ dummy empty EOF marker block) are 65536 bytes. Later versions
378
+ avoid splitting a read between two blocks, and give the header
379
+ its own block (useful to speed up replacing the header). You
380
+ can see this in ex1_refresh.bam created using samtools 0.1.18:
381
+
382
+ samtools view -b ex1.bam > ex1_refresh.bam
383
+
384
+ >>> handle = open("SamBam/ex1_refresh.bam", "rb")
385
+ >>> for values in BgzfBlocks(handle):
386
+ ... print("Raw start %i, raw length %i; data start %i, data length %i" % values)
387
+ Raw start 0, raw length 53; data start 0, data length 38
388
+ Raw start 53, raw length 18195; data start 38, data length 65434
389
+ Raw start 18248, raw length 18190; data start 65472, data length 65409
390
+ Raw start 36438, raw length 18004; data start 130881, data length 65483
391
+ Raw start 54442, raw length 17353; data start 196364, data length 65519
392
+ Raw start 71795, raw length 17708; data start 261883, data length 65411
393
+ Raw start 89503, raw length 17709; data start 327294, data length 65466
394
+ Raw start 107212, raw length 17390; data start 392760, data length 63854
395
+ Raw start 124602, raw length 28; data start 456614, data length 0
396
+ >>> handle.close()
397
+
398
+ The above example has no embedded SAM header (thus the first block
399
+ is very small at just 38 bytes of decompressed data), while the next
400
+ example does (a larger block of 103 bytes). Notice that the rest of
401
+ the blocks show the same sizes (they contain the same read data):
402
+
403
+ >>> handle = open("SamBam/ex1_header.bam", "rb")
404
+ >>> for values in BgzfBlocks(handle):
405
+ ... print("Raw start %i, raw length %i; data start %i, data length %i" % values)
406
+ Raw start 0, raw length 104; data start 0, data length 103
407
+ Raw start 104, raw length 18195; data start 103, data length 65434
408
+ Raw start 18299, raw length 18190; data start 65537, data length 65409
409
+ Raw start 36489, raw length 18004; data start 130946, data length 65483
410
+ Raw start 54493, raw length 17353; data start 196429, data length 65519
411
+ Raw start 71846, raw length 17708; data start 261948, data length 65411
412
+ Raw start 89554, raw length 17709; data start 327359, data length 65466
413
+ Raw start 107263, raw length 17390; data start 392825, data length 63854
414
+ Raw start 124653, raw length 28; data start 456679, data length 0
415
+ >>> handle.close()
416
+
417
+ """
418
+ if isinstance(handle, BgzfReader):
419
+ raise TypeError("Function BgzfBlocks expects a binary handle")
420
+ data_start = 0
421
+ while True:
422
+ start_offset = handle.tell()
423
+ try:
424
+ block_length, data = _load_bgzf_block(handle)
425
+ except StopIteration:
426
+ break
427
+ data_len = len(data)
428
+ yield start_offset, block_length, data_start, data_len
429
+ data_start += data_len
430
+
431
+
432
+ def _load_bgzf_block(handle, text_mode=False):
433
+ """Load the next BGZF block of compressed data (PRIVATE).
434
+
435
+ Returns a tuple (block size and data), or at end of file
436
+ will raise StopIteration.
437
+ """
438
+ magic = handle.read(4)
439
+ if not magic:
440
+ # End of file - should we signal this differently now?
441
+ # See https://www.python.org/dev/peps/pep-0479/
442
+ raise StopIteration
443
+ if magic != _bgzf_magic:
444
+ raise ValueError(
445
+ r"A BGZF block should start with %r, not %r; handle.tell() now says %r"
446
+ % (_bgzf_magic, magic, handle.tell())
447
+ )
448
+ gzip_mod_time, gzip_extra_flags, gzip_os, extra_len = struct.unpack(
449
+ "<LBBH", handle.read(8)
450
+ )
451
+
452
+ block_size = None
453
+ x_len = 0
454
+ while x_len < extra_len:
455
+ subfield_id = handle.read(2)
456
+ subfield_len = struct.unpack("<H", handle.read(2))[0] # uint16_t
457
+ subfield_data = handle.read(subfield_len)
458
+ x_len += subfield_len + 4
459
+ if subfield_id == _bytes_BC:
460
+ if subfield_len != 2:
461
+ raise ValueError("Wrong BC payload length")
462
+ if block_size is not None:
463
+ raise ValueError("Two BC subfields?")
464
+ block_size = struct.unpack("<H", subfield_data)[0] + 1 # uint16_t
465
+ if x_len != extra_len:
466
+ raise ValueError(f"x_len and extra_len differ {x_len}, {extra_len}")
467
+ if block_size is None:
468
+ raise ValueError("Missing BC, this isn't a BGZF file!")
469
+ # Now comes the compressed data, CRC, and length of uncompressed data.
470
+ deflate_size = block_size - 1 - extra_len - 19
471
+ d = zlib.decompressobj(-15) # Negative window size means no headers
472
+ data = d.decompress(handle.read(deflate_size)) + d.flush()
473
+ expected_crc = handle.read(4)
474
+ expected_size = struct.unpack("<I", handle.read(4))[0]
475
+ if expected_size != len(data):
476
+ raise RuntimeError("Decompressed to %i, not %i" % (len(data), expected_size))
477
+ # Should cope with a mix of Python platforms...
478
+ crc = zlib.crc32(data)
479
+ if crc < 0:
480
+ crc = struct.pack("<i", crc)
481
+ else:
482
+ crc = struct.pack("<I", crc)
483
+ if expected_crc != crc:
484
+ raise RuntimeError(f"CRC is {crc}, not {expected_crc}")
485
+ if text_mode:
486
+ # Note ISO-8859-1 aka Latin-1 preserves first 256 chars
487
+ # (i.e. ASCII), but critically is a single byte encoding
488
+ return block_size, data.decode("latin-1")
489
+ else:
490
+ return block_size, data
491
+
492
+
493
+ class BgzfReader:
494
+ r"""BGZF reader, acts like a read only handle but seek/tell differ.
495
+
496
+ Let's use the BgzfBlocks function to have a peek at the BGZF blocks
497
+ in an example BAM file,
498
+
499
+ >>> from builtins import open
500
+ >>> handle = open("SamBam/ex1.bam", "rb")
501
+ >>> for values in BgzfBlocks(handle):
502
+ ... print("Raw start %i, raw length %i; data start %i, data length %i" % values)
503
+ Raw start 0, raw length 18239; data start 0, data length 65536
504
+ Raw start 18239, raw length 18223; data start 65536, data length 65536
505
+ Raw start 36462, raw length 18017; data start 131072, data length 65536
506
+ Raw start 54479, raw length 17342; data start 196608, data length 65536
507
+ Raw start 71821, raw length 17715; data start 262144, data length 65536
508
+ Raw start 89536, raw length 17728; data start 327680, data length 65536
509
+ Raw start 107264, raw length 17292; data start 393216, data length 63398
510
+ Raw start 124556, raw length 28; data start 456614, data length 0
511
+ >>> handle.close()
512
+
513
+ Now let's see how to use this block information to jump to
514
+ specific parts of the decompressed BAM file:
515
+
516
+ >>> handle = BgzfReader("SamBam/ex1.bam", "rb")
517
+ >>> assert 0 == handle.tell()
518
+ >>> magic = handle.read(4)
519
+ >>> assert 4 == handle.tell()
520
+
521
+ So far nothing so strange, we got the magic marker used at the
522
+ start of a decompressed BAM file, and the handle position makes
523
+ sense. Now however, let's jump to the end of this block and 4
524
+ bytes into the next block by reading 65536 bytes,
525
+
526
+ >>> data = handle.read(65536)
527
+ >>> len(data)
528
+ 65536
529
+ >>> assert 1195311108 == handle.tell()
530
+
531
+ Expecting 4 + 65536 = 65540 were you? Well this is a BGZF 64-bit
532
+ virtual offset, which means:
533
+
534
+ >>> split_virtual_offset(1195311108)
535
+ (18239, 4)
536
+
537
+ You should spot 18239 as the start of the second BGZF block, while
538
+ the 4 is the offset into this block. See also make_virtual_offset,
539
+
540
+ >>> make_virtual_offset(18239, 4)
541
+ 1195311108
542
+
543
+ Let's jump back to almost the start of the file,
544
+
545
+ >>> make_virtual_offset(0, 2)
546
+ 2
547
+ >>> handle.seek(2)
548
+ 2
549
+ >>> handle.close()
550
+
551
+ Note that you can use the max_cache argument to limit the number of
552
+ BGZF blocks cached in memory. The default is 100, and since each
553
+ block can be up to 64kb, the default cache could take up to 6MB of
554
+ RAM. The cache is not important for reading through the file in one
555
+ pass, but is important for improving performance of random access.
556
+ """
557
+
558
+ def __init__(self, filename=None, mode="r", fileobj=None, max_cache=100):
559
+ r"""Initialize the class for reading a BGZF file.
560
+
561
+ You would typically use the top level ``bgzf.open(...)`` function
562
+ which will call this class internally. Direct use is discouraged.
563
+
564
+ Either the ``filename`` (string) or ``fileobj`` (input file object in
565
+ binary mode) arguments must be supplied, but not both.
566
+
567
+ Argument ``mode`` controls if the data will be returned as strings in
568
+ text mode ("rt", "tr", or default "r"), or bytes binary mode ("rb"
569
+ or "br"). The argument name matches the built-in ``open(...)`` and
570
+ standard library ``gzip.open(...)`` function.
571
+
572
+ If text mode is requested, in order to avoid multi-byte characters,
573
+ this is hard coded to use the "latin1" encoding, and "\r" and "\n"
574
+ are passed as is (without implementing universal new line mode). There
575
+ is no ``encoding`` argument.
576
+
577
+ If your data is in UTF-8 or any other incompatible encoding, you must
578
+ use binary mode, and decode the appropriate fragments yourself.
579
+
580
+ Argument ``max_cache`` controls the maximum number of BGZF blocks to
581
+ cache in memory. Each can be up to 64kb thus the default of 100 blocks
582
+ could take up to 6MB of RAM. This is important for efficient random
583
+ access, a small value is fine for reading the file in one pass.
584
+ """
585
+ # TODO - Assuming we can seek, check for 28 bytes EOF empty block
586
+ # and if missing warn about possible truncation (as in samtools)?
587
+ if max_cache < 1:
588
+ raise ValueError("Use max_cache with a minimum of 1")
589
+ # Must open the BGZF file in binary mode, but we may want to
590
+ # treat the contents as either text or binary (unicode or
591
+ # bytes under Python 3)
592
+ if filename and fileobj:
593
+ raise ValueError("Supply either filename or fileobj, not both")
594
+ # Want to reject output modes like w, a, x, +
595
+ if mode.lower() not in ("r", "tr", "rt", "rb", "br"):
596
+ raise ValueError(
597
+ "Must use a read mode like 'r' (default), 'rt', or 'rb' for binary"
598
+ )
599
+ # If an open file was passed, make sure it was opened in binary mode.
600
+ if fileobj:
601
+ if fileobj.read(0) != b"":
602
+ raise ValueError("fileobj not opened in binary mode")
603
+ handle = fileobj
604
+ else:
605
+ handle = _open(filename, "rb")
606
+ self._text = "b" not in mode.lower()
607
+ if self._text:
608
+ self._newline = "\n"
609
+ else:
610
+ self._newline = b"\n"
611
+ self._handle = handle
612
+ self.max_cache = max_cache
613
+ self._buffers = {}
614
+ self._block_start_offset = None
615
+ self._block_raw_length = None
616
+ self._load_block(handle.tell())
617
+
618
+ def _load_block(self, start_offset=None):
619
+ if start_offset is None:
620
+ # If the file is being read sequentially, then _handle.tell()
621
+ # should be pointing at the start of the next block.
622
+ # However, if seek has been used, we can't assume that.
623
+ start_offset = self._block_start_offset + self._block_raw_length
624
+ if start_offset == self._block_start_offset:
625
+ self._within_block_offset = 0
626
+ return
627
+ elif start_offset in self._buffers:
628
+ # Already in cache
629
+ self._buffer, self._block_raw_length = self._buffers[start_offset]
630
+ self._within_block_offset = 0
631
+ self._block_start_offset = start_offset
632
+ return
633
+ # Must hit the disk... first check cache limits,
634
+ while len(self._buffers) >= self.max_cache:
635
+ # TODO - Implement LRU cache removal?
636
+ self._buffers.popitem()
637
+ # Now load the block
638
+ handle = self._handle
639
+ if start_offset is not None:
640
+ handle.seek(start_offset)
641
+ self._block_start_offset = handle.tell()
642
+ try:
643
+ block_size, self._buffer = _load_bgzf_block(handle, self._text)
644
+ except StopIteration:
645
+ # EOF
646
+ block_size = 0
647
+ if self._text:
648
+ self._buffer = ""
649
+ else:
650
+ self._buffer = b""
651
+ self._within_block_offset = 0
652
+ self._block_raw_length = block_size
653
+ # Finally save the block in our cache,
654
+ self._buffers[self._block_start_offset] = self._buffer, block_size
655
+
656
+ def tell(self):
657
+ """Return a 64-bit unsigned BGZF virtual offset."""
658
+ if 0 < self._within_block_offset and self._within_block_offset == len(
659
+ self._buffer
660
+ ):
661
+ # Special case where we're right at the end of a (non empty) block.
662
+ # For non-maximal blocks could give two possible virtual offsets,
663
+ # but for a maximal block can't use 65536 as the within block
664
+ # offset. Therefore for consistency, use the next block and a
665
+ # within block offset of zero.
666
+ return (self._block_start_offset + self._block_raw_length) << 16
667
+ else:
668
+ # return make_virtual_offset(self._block_start_offset,
669
+ # self._within_block_offset)
670
+ # TODO - Include bounds checking as in make_virtual_offset?
671
+ return (self._block_start_offset << 16) | self._within_block_offset
672
+
673
+ def seek(self, virtual_offset):
674
+ """Seek to a 64-bit unsigned BGZF virtual offset."""
675
+ # Do this inline to avoid a function call,
676
+ # start_offset, within_block = split_virtual_offset(virtual_offset)
677
+ start_offset = virtual_offset >> 16
678
+ within_block = virtual_offset ^ (start_offset << 16)
679
+ if start_offset != self._block_start_offset:
680
+ # Don't need to load the block if already there
681
+ # (this avoids a function call since _load_block would do nothing)
682
+ self._load_block(start_offset)
683
+ if start_offset != self._block_start_offset:
684
+ raise ValueError("start_offset not loaded correctly")
685
+ if within_block > len(self._buffer):
686
+ if not (within_block == 0 and len(self._buffer) == 0):
687
+ raise ValueError(
688
+ "Within offset %i but block size only %i"
689
+ % (within_block, len(self._buffer))
690
+ )
691
+ self._within_block_offset = within_block
692
+ # assert virtual_offset == self.tell(), \
693
+ # "Did seek to %i (%i, %i), but tell says %i (%i, %i)" \
694
+ # % (virtual_offset, start_offset, within_block,
695
+ # self.tell(), self._block_start_offset,
696
+ # self._within_block_offset)
697
+ return virtual_offset
698
+
699
+ def read(self, size=-1):
700
+ """Read method for the BGZF module."""
701
+ if size < 0:
702
+ raise NotImplementedError("Don't be greedy, that could be massive!")
703
+
704
+ result = "" if self._text else b""
705
+ while size and self._block_raw_length:
706
+ if self._within_block_offset + size <= len(self._buffer):
707
+ # This may leave us right at the end of a block
708
+ # (lazy loading, don't load the next block unless we have too)
709
+ data = self._buffer[
710
+ self._within_block_offset : self._within_block_offset + size
711
+ ]
712
+ self._within_block_offset += size
713
+ if not data:
714
+ raise ValueError("Must be at least 1 byte")
715
+ result += data
716
+ break
717
+ else:
718
+ data = self._buffer[self._within_block_offset :]
719
+ size -= len(data)
720
+ self._load_block() # will reset offsets
721
+ result += data
722
+
723
+ return result
724
+
725
+ def readline(self):
726
+ """Read a single line for the BGZF file."""
727
+ result = "" if self._text else b""
728
+ while self._block_raw_length:
729
+ i = self._buffer.find(self._newline, self._within_block_offset)
730
+ # Three cases to consider,
731
+ if i == -1:
732
+ # No newline, need to read in more data
733
+ data = self._buffer[self._within_block_offset :]
734
+ self._load_block() # will reset offsets
735
+ result += data
736
+ elif i + 1 == len(self._buffer):
737
+ # Found new line, but right at end of block (SPECIAL)
738
+ data = self._buffer[self._within_block_offset :]
739
+ # Must now load the next block to ensure tell() works
740
+ self._load_block() # will reset offsets
741
+ if not data:
742
+ raise ValueError("Must be at least 1 byte")
743
+ result += data
744
+ break
745
+ else:
746
+ # Found new line, not at end of block (easy case, no IO)
747
+ data = self._buffer[self._within_block_offset : i + 1]
748
+ self._within_block_offset = i + 1
749
+ # assert data.endswith(self._newline)
750
+ result += data
751
+ break
752
+
753
+ return result
754
+
755
+ def __next__(self):
756
+ """Return the next line."""
757
+ line = self.readline()
758
+ if not line:
759
+ raise StopIteration
760
+ return line
761
+
762
+ def __iter__(self):
763
+ """Iterate over the lines in the BGZF file."""
764
+ return self
765
+
766
+ def close(self):
767
+ """Close BGZF file."""
768
+ self._handle.close()
769
+ self._buffer = None
770
+ self._block_start_offset = None
771
+ self._buffers = None
772
+
773
+ def seekable(self):
774
+ """Return True indicating the BGZF supports random access."""
775
+ return True
776
+
777
+ def isatty(self):
778
+ """Return True if connected to a TTY device."""
779
+ return False
780
+
781
+ def fileno(self):
782
+ """Return integer file descriptor."""
783
+ return self._handle.fileno()
784
+
785
+ def __enter__(self):
786
+ """Open a file operable with WITH statement."""
787
+ return self
788
+
789
+ def __exit__(self, type, value, traceback):
790
+ """Close a file with WITH statement."""
791
+ self.close()
792
+
793
+
794
+ class BgzfWriter:
795
+ """Define a BGZFWriter object."""
796
+
797
+ def __init__(self, filename=None, mode="w", fileobj=None, compresslevel=6):
798
+ """Initialize the class."""
799
+ if filename and fileobj:
800
+ raise ValueError("Supply either filename or fileobj, not both")
801
+ if fileobj:
802
+ # If an open file was passed, make sure it was opened in binary mode.
803
+ # This is a courtesy -- we can't detect mode for all file-like objects.
804
+ # Notably, `StringIO` does not have a `mode` attribute but plain files *do*.
805
+ if isinstance(fileobj, io.StringIO) or "b" not in getattr(
806
+ fileobj, "mode", "wb"
807
+ ):
808
+ raise ValueError("fileobj not opened in binary mode")
809
+ handle = fileobj
810
+ else:
811
+ if "w" not in mode.lower() and "a" not in mode.lower():
812
+ raise ValueError(f"Must use write or append mode, not {mode!r}")
813
+ if "a" in mode.lower():
814
+ handle = _open(filename, "ab")
815
+ else:
816
+ handle = _open(filename, "wb")
817
+ self._text = "b" not in mode.lower()
818
+ self._handle = handle
819
+ self._buffer = b""
820
+ self.compresslevel = compresslevel
821
+
822
+ def _write_block(self, block):
823
+ """Write provided data to file as a single BGZF compressed block (PRIVATE)."""
824
+ # print("Saving %i bytes" % len(block))
825
+ if len(block) > 65536:
826
+ raise ValueError(f"{len(block)} Block length > 65536")
827
+ # Giving a negative window bits means no gzip/zlib headers,
828
+ # -15 used in samtools
829
+ c = zlib.compressobj(
830
+ self.compresslevel, zlib.DEFLATED, -15, zlib.DEF_MEM_LEVEL, 0
831
+ )
832
+ compressed = c.compress(block) + c.flush()
833
+ del c
834
+ if len(compressed) > 65536:
835
+ raise RuntimeError(
836
+ "TODO - Didn't compress enough, try less data in this block"
837
+ )
838
+ crc = zlib.crc32(block)
839
+ # Should cope with a mix of Python platforms...
840
+ if crc < 0:
841
+ crc = struct.pack("<i", crc)
842
+ else:
843
+ crc = struct.pack("<I", crc)
844
+ bsize = struct.pack("<H", len(compressed) + 25) # includes -1
845
+ crc = struct.pack("<I", zlib.crc32(block) & 0xFFFFFFFF)
846
+ uncompressed_length = struct.pack("<I", len(block))
847
+ # Fixed 16 bytes,
848
+ # gzip magic bytes (4) mod time (4),
849
+ # gzip flag (1), os (1), extra length which is six (2),
850
+ # sub field which is BC (2), sub field length of two (2),
851
+ # Variable data,
852
+ # 2 bytes: block length as BC sub field (2)
853
+ # X bytes: the data
854
+ # 8 bytes: crc (4), uncompressed data length (4)
855
+ data = _bgzf_header + bsize + compressed + crc + uncompressed_length
856
+ self._handle.write(data)
857
+
858
+ def write(self, data):
859
+ """Write method for the class."""
860
+ # TODO - Check bytes vs unicode
861
+ if isinstance(data, str):
862
+ # When reading we can't cope with multi-byte characters
863
+ # being split between BGZF blocks, so we restrict to a
864
+ # single byte encoding - like ASCII or latin-1.
865
+ # On output we could probably allow any encoding, as we
866
+ # don't care about splitting unicode characters between blocks
867
+ data = data.encode("latin-1")
868
+ # block_size = 2**16 = 65536
869
+ data_len = len(data)
870
+ if len(self._buffer) + data_len < 65536:
871
+ # print("Cached %r" % data)
872
+ self._buffer += data
873
+ else:
874
+ # print("Got %r, writing out some data..." % data)
875
+ self._buffer += data
876
+ while len(self._buffer) >= 65536:
877
+ self._write_block(self._buffer[:65536])
878
+ self._buffer = self._buffer[65536:]
879
+
880
+ def flush(self):
881
+ """Flush data explicitally."""
882
+ while len(self._buffer) >= 65536:
883
+ self._write_block(self._buffer[:65535])
884
+ self._buffer = self._buffer[65535:]
885
+ self._write_block(self._buffer)
886
+ self._buffer = b""
887
+ self._handle.flush()
888
+
889
+ def close(self):
890
+ """Flush data, write 28 bytes BGZF EOF marker, and close BGZF file.
891
+
892
+ samtools will look for a magic EOF marker, just a 28 byte empty BGZF
893
+ block, and if it is missing warns the BAM file may be truncated. In
894
+ addition to samtools writing this block, so too does bgzip - so this
895
+ implementation does too.
896
+ """
897
+ if self._buffer:
898
+ self.flush()
899
+ self._handle.write(_bgzf_eof)
900
+ self._handle.flush()
901
+ self._handle.close()
902
+
903
+ def tell(self):
904
+ """Return a BGZF 64-bit virtual offset."""
905
+ return make_virtual_offset(self._handle.tell(), len(self._buffer))
906
+
907
+ def seekable(self):
908
+ """Return True indicating the BGZF supports random access."""
909
+ # Not seekable, but we do support tell...
910
+ return False
911
+
912
+ def isatty(self):
913
+ """Return True if connected to a TTY device."""
914
+ return False
915
+
916
+ def fileno(self):
917
+ """Return integer file descriptor."""
918
+ return self._handle.fileno()
919
+
920
+ def __enter__(self):
921
+ """Open a file operable with WITH statement."""
922
+ return self
923
+
924
+ def __exit__(self, type, value, traceback):
925
+ """Close a file with WITH statement."""
926
+ self.close()
927
+
928
+
929
+ if __name__ == "__main__":
930
+ if len(sys.argv) > 1:
931
+ print("Call this with no arguments and pipe uncompressed data in on stdin")
932
+ print("and it will produce BGZF compressed data on stdout. e.g.")
933
+ print("")
934
+ print("./bgzf.py < example.fastq > example.fastq.bgz")
935
+ print("")
936
+ print("The extension convention of *.bgz is to distinugish these from *.gz")
937
+ print("used for standard gzipped files without the block structure of BGZF.")
938
+ print("You can use the standard gunzip command to decompress BGZF files,")
939
+ print("if it complains about the extension try something like this:")
940
+ print("")
941
+ print("cat example.fastq.bgz | gunzip > example.fastq")
942
+ print("")
943
+ print("See also the tool bgzip that comes with samtools")
944
+ sys.exit(0)
945
+
946
+ # Ensure we have binary mode handles
947
+ # (leave stderr as default text mode)
948
+ stdin = sys.stdin.buffer
949
+ stdout = sys.stdout.buffer
950
+
951
+ sys.stderr.write("Producing BGZF output from stdin...\n")
952
+ w = BgzfWriter(fileobj=stdout)
953
+ while True:
954
+ data = stdin.read(65536)
955
+ w.write(data)
956
+ if not data:
957
+ break
958
+ # Doing close will write an empty BGZF block as EOF marker:
959
+ w.close()
960
+ sys.stderr.write("BGZF data produced\n")
.venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2.cpython-312-darwin.so ADDED
Binary file (52.3 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/Bio/cpairwise2module.c ADDED
@@ -0,0 +1,479 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2002 by Jeffrey Chang.
2
+ * Copyright 2016, 2019 by Markus Piotrowski.
3
+ * All rights reserved.
4
+ *
5
+ * This file is part of the Biopython distribution and governed by your
6
+ * choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
7
+ * Please see the LICENSE file that should have been included as part of this
8
+ * package.
9
+ *
10
+ * cpairwise2module.c
11
+ * Created 30 Sep 2001
12
+ *
13
+ * Optimized C routines that complement pairwise2.py.
14
+ */
15
+
16
+ #include "Python.h"
17
+
18
+
19
+ #define _PRECISION 1000
20
+ #define rint(x) (int)((x)*_PRECISION+0.5)
21
+
22
+ /* Functions in this module. */
23
+
24
+ static double calc_affine_penalty(int length, double open, double extend,
25
+ int penalize_extend_when_opening)
26
+ {
27
+ double penalty;
28
+
29
+ if(length <= 0)
30
+ return 0.0;
31
+ penalty = open + extend * length;
32
+ if(!penalize_extend_when_opening)
33
+ penalty -= extend;
34
+ return penalty;
35
+ }
36
+
37
+ static double _get_match_score(PyObject *py_sequenceA, PyObject *py_sequenceB,
38
+ PyObject *py_match_fn, int i, int j,
39
+ char *sequenceA, char *sequenceB,
40
+ int use_sequence_cstring,
41
+ double match, double mismatch,
42
+ int use_match_mismatch_scores)
43
+ {
44
+ PyObject *py_A=NULL, *py_B=NULL;
45
+ PyObject *py_arglist=NULL, *py_result=NULL;
46
+ double score = 0;
47
+
48
+ if(use_sequence_cstring && use_match_mismatch_scores) {
49
+ score = (sequenceA[i] == sequenceB[j]) ? match : mismatch;
50
+ return score;
51
+ }
52
+ /* Calculate the match score. */
53
+ if(!(py_A = PySequence_GetItem(py_sequenceA, i)))
54
+ goto _get_match_score_cleanup;
55
+ if(!(py_B = PySequence_GetItem(py_sequenceB, j)))
56
+ goto _get_match_score_cleanup;
57
+ if(!(py_arglist = Py_BuildValue("(OO)", py_A, py_B)))
58
+ goto _get_match_score_cleanup;
59
+
60
+ if(!(py_result = PyObject_CallObject(py_match_fn, py_arglist)))
61
+ goto _get_match_score_cleanup;
62
+ score = PyFloat_AsDouble(py_result);
63
+
64
+ _get_match_score_cleanup:
65
+ if(py_A) {
66
+ Py_DECREF(py_A);
67
+ }
68
+ if(py_B) {
69
+ Py_DECREF(py_B);
70
+ }
71
+ if(py_arglist) {
72
+ Py_DECREF(py_arglist);
73
+ }
74
+ if(py_result) {
75
+ Py_DECREF(py_result);
76
+ }
77
+ return score;
78
+ }
79
+
80
+ #if PY_MAJOR_VERSION >= 3
81
+ static PyObject* _create_bytes_object(PyObject* o)
82
+ {
83
+ PyObject* b;
84
+ if (PyBytes_Check(o)) {
85
+ return o;
86
+ }
87
+ if (!PyUnicode_Check(o)) {
88
+ return NULL;
89
+ }
90
+ b = PyUnicode_AsASCIIString(o);
91
+ if (!b) {
92
+ PyErr_Clear();
93
+ return NULL;
94
+ }
95
+ return b;
96
+ }
97
+ #endif
98
+
99
+ /* This function is a more-or-less straightforward port of the
100
+ * equivalent function in pairwise2. Please see there for algorithm
101
+ * documentation.
102
+ */
103
+ static PyObject *cpairwise2__make_score_matrix_fast(PyObject *self,
104
+ PyObject *args)
105
+ {
106
+ int i;
107
+ int row, col;
108
+ PyObject *py_sequenceA, *py_sequenceB, *py_match_fn;
109
+ #if PY_MAJOR_VERSION >= 3
110
+ PyObject *py_bytesA, *py_bytesB;
111
+ #endif
112
+ char *sequenceA=NULL, *sequenceB=NULL;
113
+ int use_sequence_cstring;
114
+ double open_A, extend_A, open_B, extend_B;
115
+ int penalize_extend_when_opening, penalize_end_gaps_A, penalize_end_gaps_B;
116
+ int align_globally, score_only;
117
+
118
+ PyObject *py_match=NULL, *py_mismatch=NULL;
119
+ double first_A_gap, first_B_gap;
120
+ double match, mismatch;
121
+ double score;
122
+ double best_score = 0;
123
+ double local_max_score = 0;
124
+ int use_match_mismatch_scores;
125
+ int lenA, lenB;
126
+ double *score_matrix = NULL;
127
+ unsigned char *trace_matrix = NULL;
128
+ PyObject *py_score_matrix=NULL, *py_trace_matrix=NULL;
129
+
130
+ double *col_cache_score = NULL;
131
+ PyObject *py_retval = NULL;
132
+
133
+ if(!PyArg_ParseTuple(args, "OOOddddi(ii)ii", &py_sequenceA, &py_sequenceB,
134
+ &py_match_fn, &open_A, &extend_A, &open_B, &extend_B,
135
+ &penalize_extend_when_opening,
136
+ &penalize_end_gaps_A, &penalize_end_gaps_B,
137
+ &align_globally, &score_only))
138
+ return NULL;
139
+ if(!PySequence_Check(py_sequenceA) || !PySequence_Check(py_sequenceB)) {
140
+ PyErr_SetString(PyExc_TypeError,
141
+ "py_sequenceA and py_sequenceB should be sequences.");
142
+ return NULL;
143
+ }
144
+
145
+ /* Optimize for the common case. Check to see if py_sequenceA and
146
+ py_sequenceB are strings. If they are, use the c string
147
+ representation. */
148
+ #if PY_MAJOR_VERSION < 3
149
+ use_sequence_cstring = 0;
150
+ if(PyString_Check(py_sequenceA) && PyString_Check(py_sequenceB)) {
151
+ sequenceA = PyString_AS_STRING(py_sequenceA);
152
+ sequenceB = PyString_AS_STRING(py_sequenceB);
153
+ use_sequence_cstring = 1;
154
+ }
155
+ #else
156
+ py_bytesA = _create_bytes_object(py_sequenceA);
157
+ py_bytesB = _create_bytes_object(py_sequenceB);
158
+ if (py_bytesA && py_bytesB) {
159
+ sequenceA = PyBytes_AS_STRING(py_bytesA);
160
+ sequenceB = PyBytes_AS_STRING(py_bytesB);
161
+ use_sequence_cstring = 1;
162
+ }
163
+ else {
164
+ Py_XDECREF(py_bytesA);
165
+ Py_XDECREF(py_bytesB);
166
+ use_sequence_cstring = 0;
167
+ }
168
+ #endif
169
+
170
+ if(!PyCallable_Check(py_match_fn)) {
171
+ PyErr_SetString(PyExc_TypeError, "py_match_fn must be callable.");
172
+ return NULL;
173
+ }
174
+ /* Optimize for the common case. Check to see if py_match_fn is
175
+ an identity_match. If so, pull out the match and mismatch
176
+ member variables and calculate the scores myself. */
177
+ match = mismatch = 0;
178
+ use_match_mismatch_scores = 0;
179
+ if(!(py_match = PyObject_GetAttrString(py_match_fn, "match")))
180
+ goto cleanup_after_py_match_fn;
181
+ match = PyFloat_AsDouble(py_match);
182
+ if(match==-1.0 && PyErr_Occurred())
183
+ goto cleanup_after_py_match_fn;
184
+ if(!(py_mismatch = PyObject_GetAttrString(py_match_fn, "mismatch")))
185
+ goto cleanup_after_py_match_fn;
186
+ mismatch = PyFloat_AsDouble(py_mismatch);
187
+ if(mismatch==-1.0 && PyErr_Occurred())
188
+ goto cleanup_after_py_match_fn;
189
+ use_match_mismatch_scores = 1;
190
+
191
+ cleanup_after_py_match_fn:
192
+ if(PyErr_Occurred())
193
+ PyErr_Clear();
194
+ if(py_match) {
195
+ Py_DECREF(py_match);
196
+ }
197
+ if(py_mismatch) {
198
+ Py_DECREF(py_mismatch);
199
+ }
200
+ /* Cache some commonly used gap penalties */
201
+ first_A_gap = calc_affine_penalty(1, open_A, extend_A,
202
+ penalize_extend_when_opening);
203
+ first_B_gap = calc_affine_penalty(1, open_B, extend_B,
204
+ penalize_extend_when_opening);
205
+
206
+ /* Allocate matrices for storing the results and initialize first row and col. */
207
+ lenA = PySequence_Length(py_sequenceA);
208
+ lenB = PySequence_Length(py_sequenceB);
209
+ score_matrix = malloc((lenA+1)*(lenB+1)*sizeof(*score_matrix));
210
+ if(!score_matrix) {
211
+ PyErr_SetString(PyExc_MemoryError, "Out of memory");
212
+ goto _cleanup_make_score_matrix_fast;
213
+ }
214
+ for(i=0; i<(lenB+1); i++)
215
+ score_matrix[i] = 0;
216
+ for(i=0; i<(lenA+1)*(lenB+1); i += (lenB+1))
217
+ score_matrix[i] = 0;
218
+ /* If we only want the score, we don't need the trace matrix. */
219
+ if (!score_only){
220
+ trace_matrix = malloc((lenA+1)*(lenB+1)*sizeof(*trace_matrix));
221
+ if(!trace_matrix) {
222
+ PyErr_SetString(PyExc_MemoryError, "Out of memory");
223
+ goto _cleanup_make_score_matrix_fast;
224
+ }
225
+ for(i=0; i<(lenB+1); i++)
226
+ trace_matrix[i] = 0;
227
+ for(i=0; i<(lenA+1)*(lenB+1); i += (lenB+1))
228
+ trace_matrix[i] = 0;
229
+ }
230
+ else
231
+ trace_matrix = malloc(1);
232
+
233
+ /* Initialize the first row and col of the score matrix. */
234
+ for(i=0; i<=lenA; i++) {
235
+ if(penalize_end_gaps_B)
236
+ score = calc_affine_penalty(i, open_B, extend_B,
237
+ penalize_extend_when_opening);
238
+ else
239
+ score = 0;
240
+ score_matrix[i*(lenB+1)] = score;
241
+ }
242
+ for(i=0; i<=lenB; i++) {
243
+ if(penalize_end_gaps_A)
244
+ score = calc_affine_penalty(i, open_A, extend_A,
245
+ penalize_extend_when_opening);
246
+ else
247
+ score = 0;
248
+ score_matrix[i] = score;
249
+ }
250
+
251
+ /* Now initialize the col cache. */
252
+ col_cache_score = malloc((lenB+1)*sizeof(*col_cache_score));
253
+ memset((void *)col_cache_score, 0, (lenB+1)*sizeof(*col_cache_score));
254
+ for(i=0; i<=lenB; i++) {
255
+ col_cache_score[i] = calc_affine_penalty(i, (2*open_B), extend_B,
256
+ penalize_extend_when_opening);
257
+ }
258
+
259
+ /* Fill in the score matrix. The row cache is calculated on the fly.*/
260
+ for(row=1; row<=lenA; row++) {
261
+ double row_cache_score = calc_affine_penalty(row, (2*open_A), extend_A,
262
+ penalize_extend_when_opening);
263
+ for(col=1; col<=lenB; col++) {
264
+ double match_score, nogap_score;
265
+ double row_open, row_extend, col_open, col_extend;
266
+ int best_score_rint, row_score_rint, col_score_rint;
267
+ unsigned char row_trace_score, col_trace_score, trace_score;
268
+
269
+ /* Calculate the best score. */
270
+ match_score = _get_match_score(py_sequenceA, py_sequenceB,
271
+ py_match_fn, row-1, col-1,
272
+ sequenceA, sequenceB,
273
+ use_sequence_cstring,
274
+ match, mismatch,
275
+ use_match_mismatch_scores);
276
+ if(match_score==-1.0 && PyErr_Occurred())
277
+ goto _cleanup_make_score_matrix_fast;
278
+ nogap_score = score_matrix[(row-1)*(lenB+1)+col-1] + match_score;
279
+
280
+ if (!penalize_end_gaps_A && row==lenA) {
281
+ row_open = score_matrix[(row)*(lenB+1)+col-1];
282
+ row_extend = row_cache_score;
283
+ }
284
+ else {
285
+ row_open = score_matrix[(row)*(lenB+1)+col-1] + first_A_gap;
286
+ row_extend = row_cache_score + extend_A;
287
+ }
288
+ row_cache_score = (row_open > row_extend) ? row_open : row_extend;
289
+
290
+ if (!penalize_end_gaps_B && col==lenB){
291
+ col_open = score_matrix[(row-1)*(lenB+1)+col];
292
+ col_extend = col_cache_score[col];
293
+ }
294
+ else {
295
+ col_open = score_matrix[(row-1)*(lenB+1)+col] + first_B_gap;
296
+ col_extend = col_cache_score[col] + extend_B;
297
+ }
298
+ col_cache_score[col] = (col_open > col_extend) ? col_open : col_extend;
299
+
300
+ best_score = (row_cache_score > col_cache_score[col]) ? row_cache_score : col_cache_score[col];
301
+ if(nogap_score > best_score)
302
+ best_score = nogap_score;
303
+
304
+ if (best_score > local_max_score)
305
+ local_max_score = best_score;
306
+
307
+ if(!align_globally && best_score < 0)
308
+ score_matrix[row*(lenB+1)+col] = 0;
309
+ else
310
+ score_matrix[row*(lenB+1)+col] = best_score;
311
+
312
+ if (!score_only) {
313
+ row_score_rint = rint(row_cache_score);
314
+ col_score_rint = rint(col_cache_score[col]);
315
+ row_trace_score = 0;
316
+ col_trace_score = 0;
317
+ if (rint(row_open) == row_score_rint)
318
+ row_trace_score = row_trace_score|1;
319
+ if (rint(row_extend) == row_score_rint)
320
+ row_trace_score = row_trace_score|8;
321
+ if (rint(col_open) == col_score_rint)
322
+ col_trace_score = col_trace_score|4;
323
+ if (rint(col_extend) == col_score_rint)
324
+ col_trace_score = col_trace_score|16;
325
+
326
+ trace_score = 0;
327
+ best_score_rint = rint(best_score);
328
+ if (rint(nogap_score) == best_score_rint)
329
+ trace_score = trace_score|2;
330
+ if (row_score_rint == best_score_rint)
331
+ trace_score += row_trace_score;
332
+ if (col_score_rint == best_score_rint)
333
+ trace_score += col_trace_score;
334
+ trace_matrix[row*(lenB+1)+col] = trace_score;
335
+ }
336
+ }
337
+ }
338
+
339
+ if (!align_globally)
340
+ best_score = local_max_score;
341
+
342
+ /* Save the score and traceback matrices into real python objects. */
343
+ if(!score_only) {
344
+ if(!(py_score_matrix = PyList_New(lenA+1)))
345
+ goto _cleanup_make_score_matrix_fast;
346
+ if(!(py_trace_matrix = PyList_New(lenA+1)))
347
+ goto _cleanup_make_score_matrix_fast;
348
+
349
+ for(row=0; row<=lenA; row++) {
350
+ PyObject *py_score_row, *py_trace_row;
351
+ if(!(py_score_row = PyList_New(lenB+1)))
352
+ goto _cleanup_make_score_matrix_fast;
353
+ PyList_SET_ITEM(py_score_matrix, row, py_score_row);
354
+ if(!(py_trace_row = PyList_New(lenB+1)))
355
+ goto _cleanup_make_score_matrix_fast;
356
+ PyList_SET_ITEM(py_trace_matrix, row, py_trace_row);
357
+
358
+ for(col=0; col<=lenB; col++) {
359
+ PyObject *py_score, *py_trace;
360
+ int offset = row*(lenB+1) + col;
361
+
362
+ /* Set py_score_matrix[row][col] to the score. */
363
+ if(!(py_score = PyFloat_FromDouble(score_matrix[offset])))
364
+ goto _cleanup_make_score_matrix_fast;
365
+ PyList_SET_ITEM(py_score_row, col, py_score);
366
+
367
+ /* Set py_trace_matrix[row][col] to a list of indexes. On
368
+ the edges of the matrix (row or column is 0), the
369
+ matrix should be [None]. */
370
+ if(!row || !col) {
371
+ if(!(py_trace = Py_BuildValue("B", 1)))
372
+ goto _cleanup_make_score_matrix_fast;
373
+ Py_INCREF(Py_None);
374
+ PyList_SET_ITEM(py_trace_row, col, Py_None);
375
+ }
376
+ else {
377
+ if(!(py_trace = Py_BuildValue("B", trace_matrix[offset])))
378
+ goto _cleanup_make_score_matrix_fast;
379
+ PyList_SET_ITEM(py_trace_row, col, py_trace);
380
+
381
+ }
382
+ }
383
+ }
384
+ }
385
+ else {
386
+ py_score_matrix = PyList_New(1);
387
+ py_trace_matrix = PyList_New(1);
388
+ }
389
+ py_retval = Py_BuildValue("(OOd)", py_score_matrix, py_trace_matrix, best_score);
390
+
391
+ _cleanup_make_score_matrix_fast:
392
+ if(score_matrix)
393
+ free(score_matrix);
394
+ if(trace_matrix)
395
+ free(trace_matrix);
396
+ if(col_cache_score)
397
+ free(col_cache_score);
398
+ if(py_score_matrix){
399
+ Py_DECREF(py_score_matrix);
400
+ }
401
+ if(py_trace_matrix){
402
+ Py_DECREF(py_trace_matrix);
403
+ }
404
+
405
+ #if PY_MAJOR_VERSION >= 3
406
+ if (py_bytesA != NULL && py_bytesA != py_sequenceA) Py_DECREF(py_bytesA);
407
+ if (py_bytesB != NULL && py_bytesB != py_sequenceB) Py_DECREF(py_bytesB);
408
+ #endif
409
+
410
+ return py_retval;
411
+ }
412
+
413
+ static PyObject *cpairwise2_rint(PyObject *self, PyObject *args,
414
+ PyObject *keywds)
415
+ {
416
+ double x;
417
+ int precision = _PRECISION;
418
+ int rint_x;
419
+
420
+ static char *kwlist[] = {"x", "precision", NULL};
421
+
422
+ if(!PyArg_ParseTupleAndKeywords(args, keywds, "d|l", kwlist,
423
+ &x, &precision))
424
+ return NULL;
425
+ rint_x = (int)(x * precision + 0.5);
426
+ #if PY_MAJOR_VERSION >= 3
427
+ return PyLong_FromLong((long)rint_x);
428
+ #else
429
+ return PyInt_FromLong((long)rint_x);
430
+ #endif
431
+ }
432
+
433
+ /* Module definition stuff */
434
+
435
+ static PyMethodDef cpairwise2Methods[] = {
436
+ {"_make_score_matrix_fast",
437
+ (PyCFunction)cpairwise2__make_score_matrix_fast, METH_VARARGS, ""},
438
+ {"rint", (PyCFunction)cpairwise2_rint, METH_VARARGS|METH_KEYWORDS, ""},
439
+ {NULL, NULL, 0, NULL}
440
+ };
441
+
442
+ static char cpairwise2__doc__[] =
443
+ "Optimized C routines that complement pairwise2.py. These are called from within pairwise2.py.\n\
444
+ \n\
445
+ ";
446
+
447
+ #if PY_MAJOR_VERSION >= 3
448
+
449
+ static struct PyModuleDef moduledef = {
450
+ PyModuleDef_HEAD_INIT,
451
+ "cpairwise2",
452
+ cpairwise2__doc__,
453
+ -1,
454
+ cpairwise2Methods,
455
+ NULL,
456
+ NULL,
457
+ NULL,
458
+ NULL
459
+ };
460
+
461
+ PyObject *
462
+ PyInit_cpairwise2(void)
463
+
464
+ #else
465
+
466
+ void
467
+ /* for Windows: _declspec(dllexport) initcpairwise2(void) */
468
+ initcpairwise2(void)
469
+ #endif
470
+
471
+ {
472
+ #if PY_MAJOR_VERSION >= 3
473
+ PyObject* module = PyModule_Create(&moduledef);
474
+ if (module==NULL) return NULL;
475
+ return module;
476
+ #else
477
+ (void) Py_InitModule3("cpairwise2", cpairwise2Methods, cpairwise2__doc__);
478
+ #endif
479
+ }
.venv_haddock/lib/python3.12/site-packages/Bio/pairwise2.py ADDED
@@ -0,0 +1,1441 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2002 by Jeffrey Chang.
2
+ # Copyright 2016, 2019, 2020 by Markus Piotrowski.
3
+ # All rights reserved.
4
+ #
5
+ # This file is part of the Biopython distribution and governed by your
6
+ # choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
7
+ # Please see the LICENSE file that should have been included as part of this
8
+ # package.
9
+
10
+ """Pairwise sequence alignment using a dynamic programming algorithm.
11
+
12
+ This provides functions to get global and local alignments between two
13
+ sequences. A global alignment finds the best concordance between all
14
+ characters in two sequences. A local alignment finds just the
15
+ subsequences that align the best. Local alignments must have a positive
16
+ score to be reported and they will not be extended for 'zero counting'
17
+ matches. This means a local alignment will always start and end with
18
+ a positive counting match.
19
+
20
+ When doing alignments, you can specify the match score and gap
21
+ penalties. The match score indicates the compatibility between an
22
+ alignment of two characters in the sequences. Highly compatible
23
+ characters should be given positive scores, and incompatible ones
24
+ should be given negative scores or 0. The gap penalties should be
25
+ negative.
26
+
27
+ The names of the alignment functions in this module follow the
28
+ convention
29
+ <alignment type>XX
30
+ where <alignment type> is either "global" or "local" and XX is a 2
31
+ character code indicating the parameters it takes. The first
32
+ character indicates the parameters for matches (and mismatches), and
33
+ the second indicates the parameters for gap penalties.
34
+
35
+ The match parameters are::
36
+
37
+ CODE DESCRIPTION & OPTIONAL KEYWORDS
38
+ x No parameters. Identical characters have score of 1, otherwise 0.
39
+ m A match score is the score of identical chars, otherwise mismatch
40
+ score. Keywords ``match``, ``mismatch``.
41
+ d A dictionary returns the score of any pair of characters.
42
+ Keyword ``match_dict``.
43
+ c A callback function returns scores. Keyword ``match_fn``.
44
+
45
+ The gap penalty parameters are::
46
+
47
+ CODE DESCRIPTION & OPTIONAL KEYWORDS
48
+ x No gap penalties.
49
+ s Same open and extend gap penalties for both sequences.
50
+ Keywords ``open``, ``extend``.
51
+ d The sequences have different open and extend gap penalties.
52
+ Keywords ``openA``, ``extendA``, ``openB``, ``extendB``.
53
+ c A callback function returns the gap penalties.
54
+ Keywords ``gap_A_fn``, ``gap_B_fn``.
55
+
56
+ All the different alignment functions are contained in an object
57
+ ``align``. For example:
58
+
59
+ >>> from Bio import pairwise2
60
+ >>> alignments = pairwise2.align.globalxx("ACCGT", "ACG")
61
+
62
+ For better readability, the required arguments can be used with optional keywords:
63
+
64
+ >>> alignments = pairwise2.align.globalxx(sequenceA="ACCGT", sequenceB="ACG")
65
+
66
+ The result is a list of the alignments between the two strings. Each alignment
67
+ is a named tuple consisting of the two aligned sequences, the score and the
68
+ start and end positions of the alignment:
69
+
70
+ >>> print(alignments)
71
+ [Alignment(seqA='ACCGT', seqB='A-CG-', score=3.0, start=0, end=5), ...
72
+
73
+ You can access each element of an alignment by index or name:
74
+
75
+ >>> alignments[0][2]
76
+ 3.0
77
+ >>> alignments[0].score
78
+ 3.0
79
+
80
+ For a nice printout of an alignment, use the ``format_alignment`` method of
81
+ the module:
82
+
83
+ >>> from Bio.pairwise2 import format_alignment
84
+ >>> print(format_alignment(*alignments[0]))
85
+ ACCGT
86
+ | ||
87
+ A-CG-
88
+ Score=3
89
+ <BLANKLINE>
90
+
91
+ All alignment functions have the following arguments:
92
+
93
+ - Two sequences: strings, Biopython sequence objects or lists.
94
+ Lists are useful for supplying sequences which contain residues that are
95
+ encoded by more than one letter.
96
+
97
+ - ``penalize_extend_when_opening``: boolean (default: False).
98
+ Whether to count an extension penalty when opening a gap. If false, a gap of
99
+ 1 is only penalized an "open" penalty, otherwise it is penalized
100
+ "open+extend".
101
+
102
+ - ``penalize_end_gaps``: boolean.
103
+ Whether to count the gaps at the ends of an alignment. By default, they are
104
+ counted for global alignments but not for local ones. Setting
105
+ ``penalize_end_gaps`` to (boolean, boolean) allows you to specify for the
106
+ two sequences separately whether gaps at the end of the alignment should be
107
+ counted.
108
+
109
+ - ``gap_char``: string (default: ``'-'``).
110
+ Which character to use as a gap character in the alignment returned. If your
111
+ input sequences are lists, you must change this to ``['-']``.
112
+
113
+ - ``force_generic``: boolean (default: False).
114
+ Always use the generic, non-cached, dynamic programming function (slow!).
115
+ For debugging.
116
+
117
+ - ``score_only``: boolean (default: False).
118
+ Only get the best score, don't recover any alignments. The return value of
119
+ the function is the score. Faster and uses less memory.
120
+
121
+ - ``one_alignment_only``: boolean (default: False).
122
+ Only recover one alignment.
123
+
124
+ The other parameters of the alignment function depend on the function called.
125
+ Some examples:
126
+
127
+ - Find the best global alignment between the two sequences. Identical
128
+ characters are given 1 point. No points are deducted for mismatches or gaps.
129
+
130
+ >>> for a in pairwise2.align.globalxx("ACCGT", "ACG"):
131
+ ... print(format_alignment(*a))
132
+ ACCGT
133
+ | ||
134
+ A-CG-
135
+ Score=3
136
+ <BLANKLINE>
137
+ ACCGT
138
+ || |
139
+ AC-G-
140
+ Score=3
141
+ <BLANKLINE>
142
+
143
+ - Same thing as before, but with a local alignment. Note that
144
+ ``format_alignment`` will only show the aligned parts of the sequences,
145
+ together with the starting positions.
146
+
147
+ >>> for a in pairwise2.align.localxx("ACCGT", "ACG"):
148
+ ... print(format_alignment(*a))
149
+ 1 ACCG
150
+ | ||
151
+ 1 A-CG
152
+ Score=3
153
+ <BLANKLINE>
154
+ 1 ACCG
155
+ || |
156
+ 1 AC-G
157
+ Score=3
158
+ <BLANKLINE>
159
+
160
+ To restore the 'historic' behaviour of ``format_alignemt``, i.e., showing
161
+ also the un-aligned parts of both sequences, use the new keyword parameter
162
+ ``full_sequences``:
163
+
164
+ >>> for a in pairwise2.align.localxx("ACCGT", "ACG"):
165
+ ... print(format_alignment(*a, full_sequences=True))
166
+ ACCGT
167
+ | ||
168
+ A-CG-
169
+ Score=3
170
+ <BLANKLINE>
171
+ ACCGT
172
+ || |
173
+ AC-G-
174
+ Score=3
175
+ <BLANKLINE>
176
+
177
+
178
+ - Do a global alignment. Identical characters are given 2 points, 1 point is
179
+ deducted for each non-identical character. Don't penalize gaps.
180
+
181
+ >>> for a in pairwise2.align.globalmx("ACCGT", "ACG", 2, -1):
182
+ ... print(format_alignment(*a))
183
+ ACCGT
184
+ | ||
185
+ A-CG-
186
+ Score=6
187
+ <BLANKLINE>
188
+ ACCGT
189
+ || |
190
+ AC-G-
191
+ Score=6
192
+ <BLANKLINE>
193
+
194
+ - Same as above, except now 0.5 points are deducted when opening a gap, and
195
+ 0.1 points are deducted when extending it.
196
+
197
+ >>> for a in pairwise2.align.globalms("ACCGT", "ACG", 2, -1, -.5, -.1):
198
+ ... print(format_alignment(*a))
199
+ ACCGT
200
+ | ||
201
+ A-CG-
202
+ Score=5
203
+ <BLANKLINE>
204
+ ACCGT
205
+ || |
206
+ AC-G-
207
+ Score=5
208
+ <BLANKLINE>
209
+
210
+ - Note that you can use keywords to increase the readability, e.g.:
211
+
212
+ >>> a = pairwise2.align.globalms("ACGT", "ACG", match=2, mismatch=-1, open=-.5,
213
+ ... extend=-.1)
214
+
215
+ - Depending on the penalties, a gap in one sequence may be followed by a gap in
216
+ the other sequence.If you don't like this behaviour, increase the gap-open
217
+ penalty:
218
+
219
+ >>> for a in pairwise2.align.globalms("A", "T", 5, -4, -1, -.1):
220
+ ... print(format_alignment(*a))
221
+ A-
222
+ <BLANKLINE>
223
+ -T
224
+ Score=-2
225
+ <BLANKLINE>
226
+ >>> for a in pairwise2.align.globalms("A", "T", 5, -4, -3, -.1):
227
+ ... print(format_alignment(*a))
228
+ A
229
+ .
230
+ T
231
+ Score=-4
232
+ <BLANKLINE>
233
+
234
+ - The alignment function can also use known matrices already included in
235
+ Biopython (in ``Bio.Align.substitution_matrices``):
236
+
237
+ >>> from Bio.Align import substitution_matrices
238
+ >>> matrix = substitution_matrices.load("BLOSUM62")
239
+ >>> for a in pairwise2.align.globaldx("KEVLA", "EVL", matrix):
240
+ ... print(format_alignment(*a))
241
+ KEVLA
242
+ |||
243
+ -EVL-
244
+ Score=13
245
+ <BLANKLINE>
246
+
247
+ - With the parameter ``c`` you can define your own match- and gap functions.
248
+ E.g. to define an affine logarithmic gap function and using it:
249
+
250
+ >>> from math import log
251
+ >>> def gap_function(x, y): # x is gap position in seq, y is gap length
252
+ ... if y == 0: # No gap
253
+ ... return 0
254
+ ... elif y == 1: # Gap open penalty
255
+ ... return -2
256
+ ... return - (2 + y/4.0 + log(y)/2.0)
257
+ ...
258
+ >>> alignment = pairwise2.align.globalmc("ACCCCCGT", "ACG", 5, -4,
259
+ ... gap_function, gap_function)
260
+
261
+ You can define different gap functions for each sequence.
262
+ Self-defined match functions must take the two residues to be compared and
263
+ return a score.
264
+
265
+ To see a description of the parameters for a function, please look at
266
+ the docstring for the function via the help function, e.g.
267
+ type ``help(pairwise2.align.localds)`` at the Python prompt.
268
+
269
+ """ # noqa: W291
270
+
271
+ import warnings
272
+ from collections import namedtuple
273
+
274
+ from Bio import BiopythonDeprecationWarning
275
+ from Bio import BiopythonWarning
276
+ from Bio.Align import substitution_matrices
277
+
278
+ warnings.warn(
279
+ "Bio.pairwise2 has been deprecated, and we intend to remove it in a "
280
+ "future release of Biopython. As an alternative, please consider using "
281
+ "Bio.Align.PairwiseAligner as a replacement, and contact the "
282
+ "Biopython developers if you still need the Bio.pairwise2 module.",
283
+ BiopythonDeprecationWarning,
284
+ )
285
+
286
+
287
+ MAX_ALIGNMENTS = 1000 # maximum alignments recovered in traceback
288
+
289
+ Alignment = namedtuple("Alignment", ("seqA, seqB, score, start, end"))
290
+
291
+
292
+ class align:
293
+ """Provide functions that do alignments.
294
+
295
+ Alignment functions are called as:
296
+
297
+ pairwise2.align.globalXX
298
+
299
+ or
300
+
301
+ pairwise2.align.localXX
302
+
303
+ Where XX is a 2 character code indicating the match/mismatch parameters
304
+ (first character, either x, m, d or c) and the gap penalty parameters
305
+ (second character, either x, s, d, or c).
306
+
307
+ For a detailed description read the main module's docstring (e.g.,
308
+ type ``help(pairwise2)``).
309
+ To see a description of the parameters for a function, please
310
+ look at the docstring for the function, e.g. type
311
+ ``help(pairwise2.align.localds)`` at the Python prompt.
312
+ """
313
+
314
+ class alignment_function:
315
+ """Callable class which impersonates an alignment function.
316
+
317
+ The constructor takes the name of the function. This class
318
+ will decode the name of the function to figure out how to
319
+ interpret the parameters.
320
+ """
321
+
322
+ # match code -> tuple of (parameters, docstring)
323
+ match2args = {
324
+ "x": ([], ""),
325
+ "m": (
326
+ ["match", "mismatch"],
327
+ "match is the score to given to identical characters.\n"
328
+ "mismatch is the score given to non-identical ones.",
329
+ ),
330
+ "d": (
331
+ ["match_dict"],
332
+ "match_dict is a dictionary where the keys are tuples\n"
333
+ "of pairs of characters and the values are the scores,\n"
334
+ "e.g. ('A', 'C') : 2.5.",
335
+ ),
336
+ "c": (
337
+ ["match_fn"],
338
+ "match_fn is a callback function that takes two "
339
+ "characters and returns the score between them.",
340
+ ),
341
+ }
342
+ # penalty code -> tuple of (parameters, docstring)
343
+ penalty2args = {
344
+ "x": ([], ""),
345
+ "s": (
346
+ ["open", "extend"],
347
+ "open and extend are the gap penalties when a gap is\n"
348
+ "opened and extended. They should be negative.",
349
+ ),
350
+ "d": (
351
+ ["openA", "extendA", "openB", "extendB"],
352
+ "openA and extendA are the gap penalties for sequenceA,\n"
353
+ "and openB and extendB for sequenceB. The penalties\n"
354
+ "should be negative.",
355
+ ),
356
+ "c": (
357
+ ["gap_A_fn", "gap_B_fn"],
358
+ "gap_A_fn and gap_B_fn are callback functions that takes\n"
359
+ "(1) the index where the gap is opened, and (2) the length\n"
360
+ "of the gap. They should return a gap penalty.",
361
+ ),
362
+ }
363
+
364
+ def __init__(self, name):
365
+ """Check to make sure the name of the function is reasonable."""
366
+ if name.startswith("global"):
367
+ if len(name) != 8:
368
+ raise AttributeError("function should be globalXX")
369
+ elif name.startswith("local"):
370
+ if len(name) != 7:
371
+ raise AttributeError("function should be localXX")
372
+ else:
373
+ raise AttributeError(name)
374
+ align_type, match_type, penalty_type = name[:-2], name[-2], name[-1]
375
+ try:
376
+ match_args, match_doc = self.match2args[match_type]
377
+ except KeyError:
378
+ raise AttributeError(f"unknown match type {match_type!r}")
379
+ try:
380
+ penalty_args, penalty_doc = self.penalty2args[penalty_type]
381
+ except KeyError:
382
+ raise AttributeError(f"unknown penalty type {penalty_type!r}")
383
+
384
+ # Now get the names of the parameters to this function.
385
+ param_names = ["sequenceA", "sequenceB"]
386
+ param_names.extend(match_args)
387
+ param_names.extend(penalty_args)
388
+ self.function_name = name
389
+ self.align_type = align_type
390
+ self.param_names = param_names
391
+
392
+ self.__name__ = self.function_name
393
+ # Set the doc string.
394
+ doc = f"{self.__name__}({', '.join(self.param_names)}) -> alignments\n"
395
+ doc += """\
396
+ \nThe following parameters can also be used with optional
397
+ keywords of the same name.\n\n
398
+ sequenceA and sequenceB must be of the same type, either
399
+ strings, lists or Biopython sequence objects.\n
400
+ """
401
+ if match_doc:
402
+ doc += f"\n{match_doc}\n"
403
+ if penalty_doc:
404
+ doc += f"\n{penalty_doc}\n"
405
+ doc += """\
406
+ \nalignments is a list of named tuples (seqA, seqB, score,
407
+ begin, end). seqA and seqB are strings showing the alignment
408
+ between the sequences. score is the score of the alignment.
409
+ begin and end are indexes of seqA and seqB that indicate
410
+ where the alignment occurs.
411
+ """
412
+ self.__doc__ = doc
413
+
414
+ def decode(self, *args, **keywds):
415
+ """Decode the arguments for the _align function.
416
+
417
+ keywds will get passed to it, so translate the arguments
418
+ to this function into forms appropriate for _align.
419
+ """
420
+ keywds = keywds.copy()
421
+
422
+ # Replace possible "keywords" with arguments:
423
+ args += (len(self.param_names) - len(args)) * (None,)
424
+ for key in keywds.copy():
425
+ if key in self.param_names:
426
+ _index = self.param_names.index(key)
427
+ args = args[:_index] + (keywds[key],) + args[_index:]
428
+ del keywds[key]
429
+ args = tuple(arg for arg in args if arg is not None)
430
+
431
+ if len(args) != len(self.param_names):
432
+ raise TypeError(
433
+ "%s takes exactly %d argument (%d given)"
434
+ % (self.function_name, len(self.param_names), len(args))
435
+ )
436
+
437
+ i = 0
438
+ while i < len(self.param_names):
439
+ if self.param_names[i] in [
440
+ "sequenceA",
441
+ "sequenceB",
442
+ "gap_A_fn",
443
+ "gap_B_fn",
444
+ "match_fn",
445
+ ]:
446
+ keywds[self.param_names[i]] = args[i]
447
+ i += 1
448
+ elif self.param_names[i] == "match":
449
+ assert self.param_names[i + 1] == "mismatch"
450
+ match, mismatch = args[i], args[i + 1]
451
+ keywds["match_fn"] = identity_match(match, mismatch)
452
+ i += 2
453
+ elif self.param_names[i] == "match_dict":
454
+ keywds["match_fn"] = dictionary_match(args[i])
455
+ i += 1
456
+ elif self.param_names[i] == "open":
457
+ assert self.param_names[i + 1] == "extend"
458
+ open, extend = args[i], args[i + 1]
459
+ pe = keywds.get("penalize_extend_when_opening", 0)
460
+ keywds["gap_A_fn"] = affine_penalty(open, extend, pe)
461
+ keywds["gap_B_fn"] = affine_penalty(open, extend, pe)
462
+ i += 2
463
+ elif self.param_names[i] == "openA":
464
+ assert self.param_names[i + 3] == "extendB"
465
+ openA, extendA, openB, extendB = args[i : i + 4]
466
+ pe = keywds.get("penalize_extend_when_opening", 0)
467
+ keywds["gap_A_fn"] = affine_penalty(openA, extendA, pe)
468
+ keywds["gap_B_fn"] = affine_penalty(openB, extendB, pe)
469
+ i += 4
470
+ else:
471
+ raise ValueError(f"unknown parameter {self.param_names[i]!r}")
472
+
473
+ # Here are the default parameters for _align. Assign
474
+ # these to keywds, unless already specified.
475
+ pe = keywds.get("penalize_extend_when_opening", 0)
476
+ default_params = [
477
+ ("match_fn", identity_match(1, 0)),
478
+ ("gap_A_fn", affine_penalty(0, 0, pe)),
479
+ ("gap_B_fn", affine_penalty(0, 0, pe)),
480
+ ("penalize_extend_when_opening", 0),
481
+ ("penalize_end_gaps", self.align_type == "global"),
482
+ ("align_globally", self.align_type == "global"),
483
+ ("gap_char", "-"),
484
+ ("force_generic", 0),
485
+ ("score_only", 0),
486
+ ("one_alignment_only", 0),
487
+ ]
488
+ for name, default in default_params:
489
+ keywds[name] = keywds.get(name, default)
490
+ value = keywds["penalize_end_gaps"]
491
+ try:
492
+ n = len(value)
493
+ except TypeError:
494
+ keywds["penalize_end_gaps"] = tuple([value] * 2)
495
+ else:
496
+ assert n == 2
497
+ return keywds
498
+
499
+ def __call__(self, *args, **keywds):
500
+ """Call the alignment instance already created."""
501
+ keywds = self.decode(*args, **keywds)
502
+ return _align(**keywds)
503
+
504
+ def __getattr__(self, attr):
505
+ """Call alignment_function() to check and decode the attributes."""
506
+ # The following 'magic' is needed to rewrite the class docstring
507
+ # dynamically:
508
+ wrapper = self.alignment_function(attr)
509
+ wrapper_type = type(wrapper)
510
+ wrapper_dict = wrapper_type.__dict__.copy()
511
+ wrapper_dict["__doc__"] = wrapper.__doc__
512
+ new_alignment_function = type("alignment_function", (object,), wrapper_dict)
513
+
514
+ return new_alignment_function(attr)
515
+
516
+
517
+ align = align()
518
+
519
+
520
+ def _align(
521
+ sequenceA,
522
+ sequenceB,
523
+ match_fn,
524
+ gap_A_fn,
525
+ gap_B_fn,
526
+ penalize_extend_when_opening,
527
+ penalize_end_gaps,
528
+ align_globally,
529
+ gap_char,
530
+ force_generic,
531
+ score_only,
532
+ one_alignment_only,
533
+ ):
534
+ """Return optimal alignments between two sequences (PRIVATE).
535
+
536
+ This method either returns a list of optimal alignments (with the same
537
+ score) or just the optimal score.
538
+ """
539
+ if not sequenceA or not sequenceB:
540
+ return []
541
+ try:
542
+ sequenceA + gap_char
543
+ sequenceB + gap_char
544
+ except TypeError:
545
+ raise TypeError(
546
+ "both sequences must be of the same type, either "
547
+ "string/sequence object or list. Gap character must "
548
+ "fit the sequence type (string or list)"
549
+ )
550
+
551
+ if not isinstance(sequenceA, list):
552
+ sequenceA = str(sequenceA)
553
+ if not isinstance(sequenceB, list):
554
+ sequenceB = str(sequenceB)
555
+ if not align_globally and (penalize_end_gaps[0] or penalize_end_gaps[1]):
556
+ warnings.warn(
557
+ '"penalize_end_gaps" should not be used in local '
558
+ "alignments. The resulting score may be wrong.",
559
+ BiopythonWarning,
560
+ )
561
+
562
+ if (
563
+ (not force_generic)
564
+ and isinstance(gap_A_fn, affine_penalty)
565
+ and isinstance(gap_B_fn, affine_penalty)
566
+ ):
567
+ open_A, extend_A = gap_A_fn.open, gap_A_fn.extend
568
+ open_B, extend_B = gap_B_fn.open, gap_B_fn.extend
569
+ matrices = _make_score_matrix_fast(
570
+ sequenceA,
571
+ sequenceB,
572
+ match_fn,
573
+ open_A,
574
+ extend_A,
575
+ open_B,
576
+ extend_B,
577
+ penalize_extend_when_opening,
578
+ penalize_end_gaps,
579
+ align_globally,
580
+ score_only,
581
+ )
582
+ else:
583
+ matrices = _make_score_matrix_generic(
584
+ sequenceA,
585
+ sequenceB,
586
+ match_fn,
587
+ gap_A_fn,
588
+ gap_B_fn,
589
+ penalize_end_gaps,
590
+ align_globally,
591
+ score_only,
592
+ )
593
+
594
+ score_matrix, trace_matrix, best_score = matrices
595
+
596
+ # print("SCORE %s" % print_matrix(score_matrix))
597
+ # print("TRACEBACK %s" % print_matrix(trace_matrix))
598
+
599
+ # If they only want the score, then return it.
600
+ if score_only:
601
+ return best_score
602
+
603
+ starts = _find_start(score_matrix, best_score, align_globally)
604
+
605
+ # Recover the alignments and return them.
606
+ alignments = _recover_alignments(
607
+ sequenceA,
608
+ sequenceB,
609
+ starts,
610
+ best_score,
611
+ score_matrix,
612
+ trace_matrix,
613
+ align_globally,
614
+ gap_char,
615
+ one_alignment_only,
616
+ gap_A_fn,
617
+ gap_B_fn,
618
+ )
619
+ if not alignments:
620
+ # This may happen, see recover_alignments for explanation
621
+ score_matrix, trace_matrix = _reverse_matrices(score_matrix, trace_matrix)
622
+ starts = [(z, (y, x)) for z, (x, y) in starts]
623
+ alignments = _recover_alignments(
624
+ sequenceB,
625
+ sequenceA,
626
+ starts,
627
+ best_score,
628
+ score_matrix,
629
+ trace_matrix,
630
+ align_globally,
631
+ gap_char,
632
+ one_alignment_only,
633
+ gap_B_fn,
634
+ gap_A_fn,
635
+ reverse=True,
636
+ )
637
+ return alignments
638
+
639
+
640
+ def _make_score_matrix_generic(
641
+ sequenceA,
642
+ sequenceB,
643
+ match_fn,
644
+ gap_A_fn,
645
+ gap_B_fn,
646
+ penalize_end_gaps,
647
+ align_globally,
648
+ score_only,
649
+ ):
650
+ """Generate a score and traceback matrix (PRIVATE).
651
+
652
+ This implementation according to Needleman-Wunsch allows the usage of
653
+ general gap functions and is rather slow. It is automatically called if
654
+ you define your own gap functions. You can force the usage of this method
655
+ with ``force_generic=True``.
656
+ """
657
+ local_max_score = 0
658
+ # Create the score and traceback matrices. These should be in the
659
+ # shape:
660
+ # sequenceA (down) x sequenceB (across)
661
+ lenA, lenB = len(sequenceA), len(sequenceB)
662
+ score_matrix, trace_matrix = [], []
663
+ for i in range(lenA + 1):
664
+ score_matrix.append([None] * (lenB + 1))
665
+ if not score_only:
666
+ trace_matrix.append([None] * (lenB + 1))
667
+
668
+ # Initialize first row and column with gap scores. This is like opening up
669
+ # i gaps at the beginning of sequence A or B.
670
+ for i in range(lenA + 1):
671
+ if penalize_end_gaps[1]: # [1]:gap in sequence B
672
+ score = gap_B_fn(0, i)
673
+ else:
674
+ score = 0.0
675
+ score_matrix[i][0] = score
676
+ for i in range(lenB + 1):
677
+ if penalize_end_gaps[0]: # [0]:gap in sequence A
678
+ score = gap_A_fn(0, i)
679
+ else:
680
+ score = 0.0
681
+ score_matrix[0][i] = score
682
+
683
+ # Fill in the score matrix. Each position in the matrix
684
+ # represents an alignment between a character from sequence A to
685
+ # one in sequence B. As I iterate through the matrix, find the
686
+ # alignment by choose the best of:
687
+ # 1) extending a previous alignment without gaps
688
+ # 2) adding a gap in sequenceA
689
+ # 3) adding a gap in sequenceB
690
+ for row in range(1, lenA + 1):
691
+ for col in range(1, lenB + 1):
692
+ # First, calculate the score that would occur by extending
693
+ # the alignment without gaps.
694
+ # fmt: off
695
+ nogap_score = (
696
+ score_matrix[row - 1][col - 1]
697
+ + match_fn(sequenceA[row - 1], sequenceB[col - 1])
698
+ )
699
+
700
+ # fmt: on
701
+ # Try to find a better score by opening gaps in sequenceA.
702
+ # Do this by checking alignments from each column in the row.
703
+ # Each column represents a different character to align from,
704
+ # and thus a different length gap.
705
+ # Although the gap function does not distinguish between opening
706
+ # and extending a gap, we distinguish them for the backtrace.
707
+ if not penalize_end_gaps[0] and row == lenA:
708
+ row_open = score_matrix[row][col - 1]
709
+ row_extend = max(score_matrix[row][x] for x in range(col))
710
+ else:
711
+ row_open = score_matrix[row][col - 1] + gap_A_fn(row, 1)
712
+ row_extend = max(
713
+ score_matrix[row][x] + gap_A_fn(row, col - x) for x in range(col)
714
+ )
715
+
716
+ # Try to find a better score by opening gaps in sequenceB.
717
+ if not penalize_end_gaps[1] and col == lenB:
718
+ col_open = score_matrix[row - 1][col]
719
+ col_extend = max(score_matrix[x][col] for x in range(row))
720
+ else:
721
+ col_open = score_matrix[row - 1][col] + gap_B_fn(col, 1)
722
+ col_extend = max(
723
+ score_matrix[x][col] + gap_B_fn(col, row - x) for x in range(row)
724
+ )
725
+
726
+ best_score = max(nogap_score, row_open, row_extend, col_open, col_extend)
727
+ local_max_score = max(local_max_score, best_score)
728
+ if not align_globally and best_score < 0:
729
+ score_matrix[row][col] = 0.0
730
+ else:
731
+ score_matrix[row][col] = best_score
732
+
733
+ # The backtrace is encoded binary. See _make_score_matrix_fast
734
+ # for details.
735
+ if not score_only:
736
+ trace_score = 0
737
+ if rint(nogap_score) == rint(best_score):
738
+ trace_score += 2
739
+ if rint(row_open) == rint(best_score):
740
+ trace_score += 1
741
+ if rint(row_extend) == rint(best_score):
742
+ trace_score += 8
743
+ if rint(col_open) == rint(best_score):
744
+ trace_score += 4
745
+ if rint(col_extend) == rint(best_score):
746
+ trace_score += 16
747
+ trace_matrix[row][col] = trace_score
748
+
749
+ if not align_globally:
750
+ best_score = local_max_score
751
+
752
+ return score_matrix, trace_matrix, best_score
753
+
754
+
755
+ def _make_score_matrix_fast(
756
+ sequenceA,
757
+ sequenceB,
758
+ match_fn,
759
+ open_A,
760
+ extend_A,
761
+ open_B,
762
+ extend_B,
763
+ penalize_extend_when_opening,
764
+ penalize_end_gaps,
765
+ align_globally,
766
+ score_only,
767
+ ):
768
+ """Generate a score and traceback matrix according to Gotoh (PRIVATE).
769
+
770
+ This is an implementation of the Needleman-Wunsch dynamic programming
771
+ algorithm as modified by Gotoh, implementing affine gap penalties.
772
+ In short, we have three matrices, holding scores for alignments ending
773
+ in (1) a match/mismatch, (2) a gap in sequence A, and (3) a gap in
774
+ sequence B, respectively. However, we can combine them in one matrix,
775
+ which holds the best scores, and store only those values from the
776
+ other matrices that are actually used for the next step of calculation.
777
+ The traceback matrix holds the positions for backtracing the alignment.
778
+ """
779
+ first_A_gap = calc_affine_penalty(1, open_A, extend_A, penalize_extend_when_opening)
780
+ first_B_gap = calc_affine_penalty(1, open_B, extend_B, penalize_extend_when_opening)
781
+ local_max_score = 0
782
+
783
+ # Create the score and traceback matrices. These should be in the
784
+ # shape:
785
+ # sequenceA (down) x sequenceB (across)
786
+ lenA, lenB = len(sequenceA), len(sequenceB)
787
+ score_matrix, trace_matrix = [], []
788
+ for i in range(lenA + 1):
789
+ score_matrix.append([None] * (lenB + 1))
790
+ if not score_only:
791
+ trace_matrix.append([None] * (lenB + 1))
792
+
793
+ # Initialize first row and column with gap scores. This is like opening up
794
+ # i gaps at the beginning of sequence A or B.
795
+ for i in range(lenA + 1):
796
+ if penalize_end_gaps[1]: # [1]:gap in sequence B
797
+ score = calc_affine_penalty(
798
+ i, open_B, extend_B, penalize_extend_when_opening
799
+ )
800
+ else:
801
+ score = 0
802
+ score_matrix[i][0] = score
803
+ for i in range(lenB + 1):
804
+ if penalize_end_gaps[0]: # [0]:gap in sequence A
805
+ score = calc_affine_penalty(
806
+ i, open_A, extend_A, penalize_extend_when_opening
807
+ )
808
+ else:
809
+ score = 0
810
+ score_matrix[0][i] = score
811
+
812
+ # Now initialize the col 'matrix'. Actually this is only a one dimensional
813
+ # list, since we only need the col scores from the last row.
814
+ col_score = [0] # Best score, if actual alignment ends with gap in seqB
815
+ for i in range(1, lenB + 1):
816
+ col_score.append(
817
+ calc_affine_penalty(i, 2 * open_B, extend_B, penalize_extend_when_opening)
818
+ )
819
+
820
+ # The row 'matrix' is calculated on the fly. Here we only need the actual
821
+ # score.
822
+ # Now, filling up the score and traceback matrices:
823
+ for row in range(1, lenA + 1):
824
+ row_score = calc_affine_penalty(
825
+ row, 2 * open_A, extend_A, penalize_extend_when_opening
826
+ )
827
+ for col in range(1, lenB + 1):
828
+ # Calculate the score that would occur by extending the
829
+ # alignment without gaps.
830
+ # fmt: off
831
+ nogap_score = (
832
+ score_matrix[row - 1][col - 1]
833
+ + match_fn(sequenceA[row - 1], sequenceB[col - 1])
834
+ )
835
+ # fmt: on
836
+ # Check the score that would occur if there were a gap in
837
+ # sequence A. This could come from opening a new gap or
838
+ # extending an existing one.
839
+ # A gap in sequence A can also be opened if it follows a gap in
840
+ # sequence B: A-
841
+ # -B
842
+ if not penalize_end_gaps[0] and row == lenA:
843
+ row_open = score_matrix[row][col - 1]
844
+ row_extend = row_score
845
+ else:
846
+ row_open = score_matrix[row][col - 1] + first_A_gap
847
+ row_extend = row_score + extend_A
848
+ row_score = max(row_open, row_extend)
849
+
850
+ # The same for sequence B:
851
+ if not penalize_end_gaps[1] and col == lenB:
852
+ col_open = score_matrix[row - 1][col]
853
+ col_extend = col_score[col]
854
+ else:
855
+ col_open = score_matrix[row - 1][col] + first_B_gap
856
+ col_extend = col_score[col] + extend_B
857
+ col_score[col] = max(col_open, col_extend)
858
+
859
+ best_score = max(nogap_score, col_score[col], row_score)
860
+ local_max_score = max(local_max_score, best_score)
861
+ if not align_globally and best_score < 0:
862
+ score_matrix[row][col] = 0
863
+ else:
864
+ score_matrix[row][col] = best_score
865
+
866
+ # Now the trace_matrix. The edges of the backtrace are encoded
867
+ # binary: 1 = open gap in seqA, 2 = match/mismatch of seqA and
868
+ # seqB, 4 = open gap in seqB, 8 = extend gap in seqA, and
869
+ # 16 = extend gap in seqB. This values can be summed up.
870
+ # Thus, the trace score 7 means that the best score can either
871
+ # come from opening a gap in seqA (=1), pairing two characters
872
+ # of seqA and seqB (+2=3) or opening a gap in seqB (+4=7).
873
+ # However, if we only want the score we don't care about the trace.
874
+ if not score_only:
875
+ row_score_rint = rint(row_score)
876
+ col_score_rint = rint(col_score[col])
877
+ row_trace_score = 0
878
+ col_trace_score = 0
879
+ if rint(row_open) == row_score_rint:
880
+ row_trace_score += 1 # Open gap in seqA
881
+ if rint(row_extend) == row_score_rint:
882
+ row_trace_score += 8 # Extend gap in seqA
883
+ if rint(col_open) == col_score_rint:
884
+ col_trace_score += 4 # Open gap in seqB
885
+ if rint(col_extend) == col_score_rint:
886
+ col_trace_score += 16 # Extend gap in seqB
887
+
888
+ trace_score = 0
889
+ best_score_rint = rint(best_score)
890
+ if rint(nogap_score) == best_score_rint:
891
+ trace_score += 2 # Align seqA with seqB
892
+ if row_score_rint == best_score_rint:
893
+ trace_score += row_trace_score
894
+ if col_score_rint == best_score_rint:
895
+ trace_score += col_trace_score
896
+ trace_matrix[row][col] = trace_score
897
+
898
+ if not align_globally:
899
+ best_score = local_max_score
900
+
901
+ return score_matrix, trace_matrix, best_score
902
+
903
+
904
+ def _recover_alignments(
905
+ sequenceA,
906
+ sequenceB,
907
+ starts,
908
+ best_score,
909
+ score_matrix,
910
+ trace_matrix,
911
+ align_globally,
912
+ gap_char,
913
+ one_alignment_only,
914
+ gap_A_fn,
915
+ gap_B_fn,
916
+ reverse=False,
917
+ ):
918
+ """Do the backtracing and return a list of alignments (PRIVATE).
919
+
920
+ Recover the alignments by following the traceback matrix. This
921
+ is a recursive procedure, but it's implemented here iteratively
922
+ with a stack.
923
+
924
+ sequenceA and sequenceB may be sequences, including strings,
925
+ lists, or list-like objects. In order to preserve the type of
926
+ the object, we need to use slices on the sequences instead of
927
+ indexes. For example, sequenceA[row] may return a type that's
928
+ not compatible with sequenceA, e.g. if sequenceA is a list and
929
+ sequenceA[row] is a string. Thus, avoid using indexes and use
930
+ slices, e.g. sequenceA[row:row+1]. Assume that client-defined
931
+ sequence classes preserve these semantics.
932
+ """
933
+ lenA, lenB = len(sequenceA), len(sequenceB)
934
+ ali_seqA, ali_seqB = sequenceA[0:0], sequenceB[0:0]
935
+ tracebacks = []
936
+ in_process = []
937
+
938
+ for start in starts:
939
+ score, (row, col) = start
940
+ begin = 0
941
+ if align_globally:
942
+ end = None
943
+ else:
944
+ # If this start is a zero-extension: don't start here!
945
+ if (score, (row - 1, col - 1)) in starts:
946
+ continue
947
+ # Local alignments should start with a positive score!
948
+ if score <= 0:
949
+ continue
950
+ # Local alignments should not end with a gap!:
951
+ trace = trace_matrix[row][col]
952
+ if (trace - trace % 2) % 4 == 2: # Trace contains 'nogap', fine!
953
+ trace_matrix[row][col] = 2
954
+ # If not, don't start here!
955
+ else:
956
+ continue
957
+ end = -max(lenA - row, lenB - col)
958
+ if not end:
959
+ end = None
960
+ col_distance = lenB - col
961
+ row_distance = lenA - row
962
+
963
+ # fmt: off
964
+ ali_seqA = (
965
+ (col_distance - row_distance) * gap_char
966
+ + sequenceA[lenA - 1 : row - 1 : -1]
967
+ )
968
+ ali_seqB = (
969
+ (row_distance - col_distance) * gap_char
970
+ + sequenceB[lenB - 1 : col - 1 : -1]
971
+ )
972
+ # fmt: on
973
+ in_process += [
974
+ (ali_seqA, ali_seqB, end, row, col, False, trace_matrix[row][col])
975
+ ]
976
+ while in_process and len(tracebacks) < MAX_ALIGNMENTS:
977
+ # Although we allow a gap in seqB to be followed by a gap in seqA,
978
+ # we don't want to allow it the other way round, since this would
979
+ # give redundant alignments of type: A- vs. -A
980
+ # -B B-
981
+ # Thus we need to keep track if a gap in seqA was opened (col_gap)
982
+ # and stop the backtrace (dead_end) if a gap in seqB follows.
983
+ #
984
+ # Attention: This may fail, if the gap-penalties for both strands are
985
+ # different. In this case the second alignment may be the only optimal
986
+ # alignment. Thus it can happen that no alignment is returned. For
987
+ # this case a workaround was implemented, which reverses the input and
988
+ # the matrices (this happens in _reverse_matrices) and repeats the
989
+ # backtrace. The variable 'reverse' keeps track of this.
990
+ dead_end = False
991
+ ali_seqA, ali_seqB, end, row, col, col_gap, trace = in_process.pop()
992
+
993
+ while (row > 0 or col > 0) and not dead_end:
994
+ cache = (ali_seqA[:], ali_seqB[:], end, row, col, col_gap)
995
+
996
+ # If trace is empty we have reached at least one border of the
997
+ # matrix or the end of a local alignment. Just add the rest of
998
+ # the sequence(s) and fill with gaps if necessary.
999
+ if not trace:
1000
+ if col and col_gap:
1001
+ dead_end = True
1002
+ else:
1003
+ ali_seqA, ali_seqB = _finish_backtrace(
1004
+ sequenceA, sequenceB, ali_seqA, ali_seqB, row, col, gap_char
1005
+ )
1006
+ break
1007
+ elif trace % 2 == 1: # = row open = open gap in seqA
1008
+ trace -= 1
1009
+ if col_gap:
1010
+ dead_end = True
1011
+ else:
1012
+ col -= 1
1013
+ ali_seqA += gap_char
1014
+ ali_seqB += sequenceB[col : col + 1]
1015
+ col_gap = False
1016
+ elif trace % 4 == 2: # = match/mismatch of seqA with seqB
1017
+ trace -= 2
1018
+ row -= 1
1019
+ col -= 1
1020
+ ali_seqA += sequenceA[row : row + 1]
1021
+ ali_seqB += sequenceB[col : col + 1]
1022
+ col_gap = False
1023
+ elif trace % 8 == 4: # = col open = open gap in seqB
1024
+ trace -= 4
1025
+ row -= 1
1026
+ ali_seqA += sequenceA[row : row + 1]
1027
+ ali_seqB += gap_char
1028
+ col_gap = True
1029
+ elif trace in (8, 24): # = row extend = extend gap in seqA
1030
+ trace -= 8
1031
+ if col_gap:
1032
+ dead_end = True
1033
+ else:
1034
+ col_gap = False
1035
+ # We need to find the starting point of the extended gap
1036
+ x = _find_gap_open(
1037
+ sequenceA,
1038
+ sequenceB,
1039
+ ali_seqA,
1040
+ ali_seqB,
1041
+ end,
1042
+ row,
1043
+ col,
1044
+ col_gap,
1045
+ gap_char,
1046
+ score_matrix,
1047
+ trace_matrix,
1048
+ in_process,
1049
+ gap_A_fn,
1050
+ col,
1051
+ row,
1052
+ "col",
1053
+ best_score,
1054
+ align_globally,
1055
+ )
1056
+ ali_seqA, ali_seqB, row, col, in_process, dead_end = x
1057
+ elif trace == 16: # = col extend = extend gap in seqB
1058
+ trace -= 16
1059
+ col_gap = True
1060
+ x = _find_gap_open(
1061
+ sequenceA,
1062
+ sequenceB,
1063
+ ali_seqA,
1064
+ ali_seqB,
1065
+ end,
1066
+ row,
1067
+ col,
1068
+ col_gap,
1069
+ gap_char,
1070
+ score_matrix,
1071
+ trace_matrix,
1072
+ in_process,
1073
+ gap_B_fn,
1074
+ row,
1075
+ col,
1076
+ "row",
1077
+ best_score,
1078
+ align_globally,
1079
+ )
1080
+ ali_seqA, ali_seqB, row, col, in_process, dead_end = x
1081
+
1082
+ if trace: # There is another path to follow...
1083
+ cache += (trace,)
1084
+ in_process.append(cache)
1085
+ trace = trace_matrix[row][col]
1086
+ if not align_globally:
1087
+ if score_matrix[row][col] == best_score:
1088
+ # We have gone through a 'zero-score' extension, discard it
1089
+ dead_end = True
1090
+ elif score_matrix[row][col] <= 0:
1091
+ # We have reached the end of the backtrace
1092
+ begin = max(row, col)
1093
+ trace = 0
1094
+ if not dead_end:
1095
+ if not reverse:
1096
+ tracebacks.append((ali_seqA[::-1], ali_seqB[::-1], score, begin, end))
1097
+ else:
1098
+ tracebacks.append((ali_seqB[::-1], ali_seqA[::-1], score, begin, end))
1099
+ if one_alignment_only:
1100
+ break
1101
+ return _clean_alignments(tracebacks)
1102
+
1103
+
1104
+ def _find_start(score_matrix, best_score, align_globally):
1105
+ """Return a list of starting points (score, (row, col)) (PRIVATE).
1106
+
1107
+ Indicating every possible place to start the tracebacks.
1108
+ """
1109
+ nrows, ncols = len(score_matrix), len(score_matrix[0])
1110
+ # In this implementation of the global algorithm, the start will always be
1111
+ # the bottom right corner of the matrix.
1112
+ if align_globally:
1113
+ starts = [(best_score, (nrows - 1, ncols - 1))]
1114
+ else:
1115
+ # For local alignments, there may be many different start points.
1116
+ starts = []
1117
+ tolerance = 0 # XXX do anything with this?
1118
+ # Now find all the positions within some tolerance of the best
1119
+ # score.
1120
+ for row in range(nrows):
1121
+ for col in range(ncols):
1122
+ score = score_matrix[row][col]
1123
+ if rint(abs(score - best_score)) <= rint(tolerance):
1124
+ starts.append((score, (row, col)))
1125
+ return starts
1126
+
1127
+
1128
+ def _reverse_matrices(score_matrix, trace_matrix):
1129
+ """Reverse score and trace matrices (PRIVATE)."""
1130
+ reverse_score_matrix = []
1131
+ reverse_trace_matrix = []
1132
+ # fmt: off
1133
+ reverse_trace = {
1134
+ 1: 4, 2: 2, 3: 6, 4: 1, 5: 5, 6: 3, 7: 7, 8: 16, 9: 20, 10: 18, 11: 22, 12: 17,
1135
+ 13: 21, 14: 19, 15: 23, 16: 8, 17: 12, 18: 10, 19: 14, 20: 9, 21: 13, 22: 11,
1136
+ 23: 15, 24: 24, 25: 28, 26: 26, 27: 30, 28: 25, 29: 29, 30: 27, 31: 31,
1137
+ None: None,
1138
+ }
1139
+ # fmt: on
1140
+ for col in range(len(score_matrix[0])):
1141
+ new_score_row = []
1142
+ new_trace_row = []
1143
+ for row in range(len(score_matrix)):
1144
+ new_score_row.append(score_matrix[row][col])
1145
+ new_trace_row.append(reverse_trace[trace_matrix[row][col]])
1146
+ reverse_score_matrix.append(new_score_row)
1147
+ reverse_trace_matrix.append(new_trace_row)
1148
+ return reverse_score_matrix, reverse_trace_matrix
1149
+
1150
+
1151
+ def _clean_alignments(alignments):
1152
+ """Take a list of alignments and return a cleaned version (PRIVATE).
1153
+
1154
+ Remove duplicates, make sure begin and end are set correctly, remove
1155
+ empty alignments.
1156
+ """
1157
+ unique_alignments = []
1158
+ for align in alignments:
1159
+ if align not in unique_alignments:
1160
+ unique_alignments.append(align)
1161
+ i = 0
1162
+ while i < len(unique_alignments):
1163
+ seqA, seqB, score, begin, end = unique_alignments[i]
1164
+ # Make sure end is set reasonably.
1165
+ if end is None: # global alignment
1166
+ end = len(seqA)
1167
+ elif end < 0:
1168
+ end = end + len(seqA)
1169
+ # If there's no alignment here, get rid of it.
1170
+ if begin >= end:
1171
+ del unique_alignments[i]
1172
+ continue
1173
+ unique_alignments[i] = Alignment(seqA, seqB, score, begin, end)
1174
+ i += 1
1175
+ return unique_alignments
1176
+
1177
+
1178
+ def _finish_backtrace(sequenceA, sequenceB, ali_seqA, ali_seqB, row, col, gap_char):
1179
+ """Add remaining sequences and fill with gaps if necessary (PRIVATE)."""
1180
+ if row:
1181
+ ali_seqA += sequenceA[row - 1 :: -1]
1182
+ if col:
1183
+ ali_seqB += sequenceB[col - 1 :: -1]
1184
+ if row > col:
1185
+ ali_seqB += gap_char * (len(ali_seqA) - len(ali_seqB))
1186
+ elif col > row:
1187
+ ali_seqA += gap_char * (len(ali_seqB) - len(ali_seqA))
1188
+ return ali_seqA, ali_seqB
1189
+
1190
+
1191
+ def _find_gap_open(
1192
+ sequenceA,
1193
+ sequenceB,
1194
+ ali_seqA,
1195
+ ali_seqB,
1196
+ end,
1197
+ row,
1198
+ col,
1199
+ col_gap,
1200
+ gap_char,
1201
+ score_matrix,
1202
+ trace_matrix,
1203
+ in_process,
1204
+ gap_fn,
1205
+ target,
1206
+ index,
1207
+ direction,
1208
+ best_score,
1209
+ align_globally,
1210
+ ):
1211
+ """Find the starting point(s) of the extended gap (PRIVATE)."""
1212
+ dead_end = False
1213
+ target_score = score_matrix[row][col]
1214
+ for n in range(target):
1215
+ if direction == "col":
1216
+ col -= 1
1217
+ ali_seqA += gap_char
1218
+ ali_seqB += sequenceB[col : col + 1]
1219
+ else:
1220
+ row -= 1
1221
+ ali_seqA += sequenceA[row : row + 1]
1222
+ ali_seqB += gap_char
1223
+ actual_score = score_matrix[row][col] + gap_fn(index, n + 1)
1224
+ if not align_globally and score_matrix[row][col] == best_score:
1225
+ # We have run through a 'zero-score' extension and discard it
1226
+ dead_end = True
1227
+ break
1228
+ if rint(actual_score) == rint(target_score) and n > 0:
1229
+ if not trace_matrix[row][col]:
1230
+ break
1231
+ else:
1232
+ in_process.append(
1233
+ (
1234
+ ali_seqA[:],
1235
+ ali_seqB[:],
1236
+ end,
1237
+ row,
1238
+ col,
1239
+ col_gap,
1240
+ trace_matrix[row][col],
1241
+ )
1242
+ )
1243
+ if not trace_matrix[row][col]:
1244
+ dead_end = True
1245
+ return ali_seqA, ali_seqB, row, col, in_process, dead_end
1246
+
1247
+
1248
+ _PRECISION = 1000
1249
+
1250
+
1251
+ def rint(x, precision=_PRECISION):
1252
+ """Print number with declared precision."""
1253
+ return int(x * precision + 0.5)
1254
+
1255
+
1256
+ class identity_match:
1257
+ """Create a match function for use in an alignment.
1258
+
1259
+ match and mismatch are the scores to give when two residues are equal
1260
+ or unequal. By default, match is 1 and mismatch is 0.
1261
+ """
1262
+
1263
+ def __init__(self, match=1, mismatch=0):
1264
+ """Initialize the class."""
1265
+ self.match = match
1266
+ self.mismatch = mismatch
1267
+
1268
+ def __call__(self, charA, charB):
1269
+ """Call a match function instance already created."""
1270
+ if charA == charB:
1271
+ return self.match
1272
+ return self.mismatch
1273
+
1274
+
1275
+ class dictionary_match:
1276
+ """Create a match function for use in an alignment.
1277
+
1278
+ Attributes:
1279
+ - score_dict - A dictionary where the keys are tuples (residue 1,
1280
+ residue 2) and the values are the match scores between those residues.
1281
+ - symmetric - A flag that indicates whether the scores are symmetric.
1282
+
1283
+ """
1284
+
1285
+ def __init__(self, score_dict, symmetric=1):
1286
+ """Initialize the class."""
1287
+ if isinstance(score_dict, substitution_matrices.Array):
1288
+ score_dict = dict(score_dict) # Access to dict is much faster
1289
+ self.score_dict = score_dict
1290
+ self.symmetric = symmetric
1291
+
1292
+ def __call__(self, charA, charB):
1293
+ """Call a dictionary match instance already created."""
1294
+ if self.symmetric and (charA, charB) not in self.score_dict:
1295
+ # If the score dictionary is symmetric, then look up the
1296
+ # score both ways.
1297
+ charB, charA = charA, charB
1298
+ return self.score_dict[(charA, charB)]
1299
+
1300
+
1301
+ class affine_penalty:
1302
+ """Create a gap function for use in an alignment."""
1303
+
1304
+ def __init__(self, open, extend, penalize_extend_when_opening=0):
1305
+ """Initialize the class."""
1306
+ if open > 0 or extend > 0:
1307
+ raise ValueError("Gap penalties should be non-positive.")
1308
+ if not penalize_extend_when_opening and (extend < open):
1309
+ raise ValueError(
1310
+ "Gap opening penalty should be higher than "
1311
+ "gap extension penalty (or equal)"
1312
+ )
1313
+ self.open, self.extend = open, extend
1314
+ self.penalize_extend_when_opening = penalize_extend_when_opening
1315
+
1316
+ def __call__(self, index, length):
1317
+ """Call a gap function instance already created."""
1318
+ return calc_affine_penalty(
1319
+ length, self.open, self.extend, self.penalize_extend_when_opening
1320
+ )
1321
+
1322
+
1323
+ def calc_affine_penalty(length, open, extend, penalize_extend_when_opening):
1324
+ """Calculate a penalty score for the gap function."""
1325
+ if length <= 0:
1326
+ return 0.0
1327
+ penalty = open + extend * length
1328
+ if not penalize_extend_when_opening:
1329
+ penalty -= extend
1330
+ return penalty
1331
+
1332
+
1333
+ def print_matrix(matrix):
1334
+ """Print out a matrix for debugging purposes."""
1335
+ # Transpose the matrix and get the length of the values in each column.
1336
+ matrixT = [[] for x in range(len(matrix[0]))]
1337
+ for i in range(len(matrix)):
1338
+ for j in range(len(matrix[i])):
1339
+ matrixT[j].append(len(str(matrix[i][j])))
1340
+ ndigits = [max(x) for x in matrixT]
1341
+ for i in range(len(matrix)):
1342
+ # Using string formatting trick to add leading spaces,
1343
+ print(
1344
+ " ".join("%*s " % (ndigits[j], matrix[i][j]) for j in range(len(matrix[i])))
1345
+ )
1346
+
1347
+
1348
+ def format_alignment(align1, align2, score, begin, end, full_sequences=False):
1349
+ """Format the alignment prettily into a string.
1350
+
1351
+ IMPORTANT: Gap symbol must be "-" (or ['-'] for lists)!
1352
+
1353
+ Since Biopython 1.71 identical matches are shown with a pipe
1354
+ character, mismatches as a dot, and gaps as a space.
1355
+
1356
+ Prior releases just used the pipe character to indicate the
1357
+ aligned region (matches, mismatches and gaps).
1358
+
1359
+ Also, in local alignments, if the alignment does not include
1360
+ the whole sequences, now only the aligned part is shown,
1361
+ together with the start positions of the aligned subsequences.
1362
+ The start positions are 1-based; so start position n is the
1363
+ n-th base/amino acid in the *un-aligned* sequence.
1364
+
1365
+ NOTE: This is different to the alignment's begin/end values,
1366
+ which give the Python indices (0-based) of the bases/amino acids
1367
+ in the *aligned* sequences.
1368
+
1369
+ If you want to restore the 'historic' behaviour, that means
1370
+ displaying the whole sequences (including the non-aligned parts),
1371
+ use ``full_sequences=True``. In this case, the non-aligned leading
1372
+ and trailing parts are also indicated by spaces in the match-line.
1373
+ """
1374
+ align_begin = begin
1375
+ align_end = end
1376
+ start1 = start2 = ""
1377
+ start_m = begin # Begin of match line (how many spaces to include)
1378
+ # For local alignments:
1379
+ if not full_sequences and (begin != 0 or end != len(align1)):
1380
+ # Calculate the actual start positions in the un-aligned sequences
1381
+ # This will only work if the gap symbol is '-' or ['-']!
1382
+ start1 = str(len(align1[:begin]) - align1[:begin].count("-") + 1) + " "
1383
+ start2 = str(len(align2[:begin]) - align2[:begin].count("-") + 1) + " "
1384
+ start_m = max(len(start1), len(start2))
1385
+ elif full_sequences:
1386
+ start_m = 0
1387
+ begin = 0
1388
+ end = len(align1)
1389
+
1390
+ if isinstance(align1, list):
1391
+ # List elements will be separated by spaces, since they can be
1392
+ # of different lengths
1393
+ align1 = [a + " " for a in align1]
1394
+ align2 = [a + " " for a in align2]
1395
+
1396
+ s1_line = ["{:>{width}}".format(start1, width=start_m)] # seq1 line
1397
+ m_line = [" " * start_m] # match line
1398
+ s2_line = ["{:>{width}}".format(start2, width=start_m)] # seq2 line
1399
+
1400
+ for n, (a, b) in enumerate(zip(align1[begin:end], align2[begin:end])):
1401
+ # Since list elements can be of different length, we center them,
1402
+ # using the maximum length of the two compared elements as width
1403
+ m_len = max(len(a), len(b))
1404
+ s1_line.append("{:^{width}}".format(a, width=m_len))
1405
+ s2_line.append("{:^{width}}".format(b, width=m_len))
1406
+ if full_sequences and (n < align_begin or n >= align_end):
1407
+ m_line.append("{:^{width}}".format(" ", width=m_len)) # space
1408
+ continue
1409
+ if a == b:
1410
+ m_line.append("{:^{width}}".format("|", width=m_len)) # match
1411
+ elif a.strip() == "-" or b.strip() == "-":
1412
+ m_line.append("{:^{width}}".format(" ", width=m_len)) # gap
1413
+ else:
1414
+ m_line.append("{:^{width}}".format(".", width=m_len)) # mismatch
1415
+
1416
+ s2_line.append(f"\n Score={score:g}\n")
1417
+ return "\n".join(["".join(s1_line), "".join(m_line), "".join(s2_line)])
1418
+
1419
+
1420
+ # Try and load C implementations of functions. If I can't,
1421
+ # then throw a warning and use the pure Python implementations.
1422
+ # The redefinition is deliberate, thus the no quality assurance
1423
+ # flag for when using flake8.
1424
+ # Before, we secure access to the pure Python functions (for testing purposes):
1425
+
1426
+ _python_make_score_matrix_fast = _make_score_matrix_fast
1427
+ _python_rint = rint
1428
+
1429
+ try:
1430
+ from .cpairwise2 import rint, _make_score_matrix_fast # noqa
1431
+ except ImportError:
1432
+ warnings.warn(
1433
+ "Import of C module failed. Falling back to pure Python "
1434
+ "implementation. This may be slooow...",
1435
+ BiopythonWarning,
1436
+ )
1437
+
1438
+ if __name__ == "__main__":
1439
+ from Bio._utils import run_doctest
1440
+
1441
+ run_doctest()
.venv_haddock/lib/python3.12/site-packages/Bio/py.typed ADDED
File without changes
.venv_haddock/lib/python3.12/site-packages/__pycache__/six.cpython-312.pyc ADDED
Binary file (41.4 kB). View file
 
.venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/METADATA ADDED
@@ -0,0 +1,205 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: haddock3
3
+ Version: 2026.3.0
4
+ Summary: HADDOCK3
5
+ Author-email: BonvinLab <bonvinlab.support@uu.nl>
6
+ License: Apache License 2.0
7
+ Project-URL: Homepage, https://github.com/haddocking/haddock3
8
+ Project-URL: Documentation, https://github.com/haddocking/haddock3#readme
9
+ Project-URL: Issue Tracker, https://github.com/haddocking/haddock3/issues
10
+ Project-URL: Discussion Forum, https://github.com/haddocking/haddock3/issues
11
+ Keywords: Structural Biology,Biochemistry,Docking,Protein docking,Proteins
12
+ Classifier: Development Status :: 5 - Production/Stable
13
+ Classifier: License :: OSI Approved :: Apache Software License
14
+ Classifier: Natural Language :: English
15
+ Classifier: Operating System :: POSIX
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Operating System :: MacOS
18
+ Classifier: Intended Audience :: Science/Research
19
+ Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
20
+ Classifier: Topic :: Scientific/Engineering :: Chemistry
21
+ Classifier: Topic :: Scientific/Engineering :: Physics
22
+ Classifier: Programming Language :: Python :: 3.9
23
+ Classifier: Programming Language :: Python :: 3.10
24
+ Classifier: Programming Language :: Python :: 3.11
25
+ Classifier: Programming Language :: Python :: 3.12
26
+ Classifier: Programming Language :: Python :: 3.13
27
+ Classifier: Programming Language :: Python :: 3.14
28
+ Requires-Python: <3.15,>=3.9
29
+ Description-Content-Type: text/markdown
30
+ License-File: LICENSE
31
+ Requires-Dist: pdb-tools>=2.5.0
32
+ Requires-Dist: biopython==1.*
33
+ Requires-Dist: jsonpickle>=2.1.0
34
+ Requires-Dist: numpy==2.*
35
+ Requires-Dist: pyyaml>=6.0
36
+ Requires-Dist: scipy>=1.10.0
37
+ Requires-Dist: toml>=0.10.2
38
+ Requires-Dist: pandas==2.*
39
+ Requires-Dist: prodigy-prot==2.3.0
40
+ Requires-Dist: prodigy-lig==1.1.4
41
+ Requires-Dist: plotly==6.5.2
42
+ Requires-Dist: freesasa>=2.2.1
43
+ Provides-Extra: dev
44
+ Requires-Dist: coverage==7.10.7; extra == "dev"
45
+ Requires-Dist: pytest==8.4.2; extra == "dev"
46
+ Requires-Dist: pytest-cov==7.0.0; extra == "dev"
47
+ Requires-Dist: hypothesis==6.141.1; extra == "dev"
48
+ Requires-Dist: pytest-mock==3.15.1; extra == "dev"
49
+ Requires-Dist: fastapi==0.128.8; extra == "dev"
50
+ Requires-Dist: httpx==0.28.1; extra == "dev"
51
+ Requires-Dist: kaleido==1.2.0; extra == "dev"
52
+ Requires-Dist: pytest-random-order==1.2.0; extra == "dev"
53
+ Provides-Extra: docs
54
+ Requires-Dist: sphinx>=7; extra == "docs"
55
+ Requires-Dist: sphinx-argparse>=0.4.0; extra == "docs"
56
+ Requires-Dist: sphinx_rtd_theme>=3.0.1; extra == "docs"
57
+ Requires-Dist: CommonMark>=0.9.1; extra == "docs"
58
+ Requires-Dist: mock>=5.1.0; extra == "docs"
59
+ Requires-Dist: myst-parser>=3.0.1; extra == "docs"
60
+ Provides-Extra: mpi
61
+ Requires-Dist: mpi4py>=4.0.2; extra == "mpi"
62
+ Provides-Extra: notebooks
63
+ Requires-Dist: py3Dmol>=2.5.2; extra == "notebooks"
64
+ Dynamic: license-file
65
+
66
+ # `haddock3`
67
+
68
+ ![haddock3-logo](https://raw.githubusercontent.com/haddocking/haddock3/refs/heads/main/docs/figs/HADDOCK3-logo.png)
69
+
70
+ [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.16914680.svg)](https://doi.org/10.5281/zenodo.16914680)
71
+ [![Research Software Directory](https://img.shields.io/badge/rsd-haddock3-00a3e3.svg)](https://research-software-directory.org/software/haddock3)
72
+ [![fair-software.eu](https://img.shields.io/badge/fair--software.eu-%E2%97%8F%20%20%E2%97%8F%20%20%E2%97%8F%20%20%E2%97%8F%20%20%E2%97%8F-green)](https://fair-software.eu)
73
+ [![OpenSSF Best Practices](https://www.bestpractices.dev/projects/8844/badge)](https://www.bestpractices.dev/projects/8844)
74
+
75
+ [![Downloads](https://static.pepy.tech/badge/haddock3)](https://pepy.tech/project/haddock3)
76
+ ![PyPI - Version](https://img.shields.io/pypi/v/haddock3)
77
+ ![PyPI - Python Version](https://img.shields.io/pypi/pyversions/haddock3)
78
+ [![SBGrid Badge](https://img.shields.io/badge/haddock3-blue?label=SBGrid&labelColor=%3D)](https://sbgrid.org/software/titles/haddock3)
79
+
80
+ [![ci](https://github.com/haddocking/haddock3/actions/workflows/ci.yml/badge.svg)](https://github.com/haddocking/haddock3/actions/workflows/ci.yml)
81
+ [![pages](https://github.com/haddocking/haddock3/actions/workflows/pages.yml/badge.svg)](https://github.com/haddocking/haddock3/actions/workflows/pages.yml)
82
+ [![CodeQL](https://github.com/haddocking/haddock3/actions/workflows/github-code-scanning/codeql/badge.svg)](https://github.com/haddocking/haddock3/actions/workflows/github-code-scanning/codeql)
83
+ [![Codacy Badge](https://app.codacy.com/project/badge/Grade/e11e7f45400f4e8589cdf5941f95233a)](https://app.codacy.com/gh/haddocking/haddock3/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)
84
+ [![Codacy Badge](https://app.codacy.com/project/badge/Coverage/e11e7f45400f4e8589cdf5941f95233a)](https://app.codacy.com/gh/haddocking/haddock3/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)
85
+
86
+ ## Introduction
87
+
88
+ HADDOCK, standing for **H**igh **A**mbiguity **D**riven protein-protein **DOCK**ing, is a widely used computational tool for the integrative modeling of biomolecular interactions. Developed by researchers at [Utrecht University](https://uu.nl) in the [BonvinLab](https://bonvinlab.org) for more than 20 years, it integrates various types of experimental data, biochemical, biophysical, bioinformatic prediction and knowledge to guide the docking process.
89
+
90
+ ## Installation
91
+
92
+ Simple installation of the [latest release](https://pypi.org/project/haddock3/) of HADDOCK3 (assuming you have a Python version 3.9 to 3.13 installed and the rights to install the software - if not refer to the instructions in [INSTALL.md](docs/INSTALL.md) for using either `venv` or `conda`) .
93
+
94
+ ```bash
95
+ pip install haddock3
96
+ ```
97
+
98
+ To install haddock3 with MPI support (required an OpenMPI installation - refer
99
+ to the instructions in [INSTALL.md](docs/INSTALL.md) use:
100
+
101
+ ```bash
102
+ pip install 'haddock3[mpi]'
103
+ ```
104
+
105
+ In case you rather install the latest unreleased version use instead:
106
+
107
+ ```bash
108
+ git clone https://github.com/haddocking/haddock3.git
109
+ cd haddock3
110
+ pip install .
111
+ ```
112
+
113
+ For detailed instructions and installation of third-party software, please check [INSTALL.md](docs/INSTALL.md)
114
+
115
+ You might also want to check the following utilities:
116
+
117
+ - [`haddock-restraints`](https://github.com/haddocking/haddock-restraints): Tool to generate restraints to be used in `haddock3`.
118
+ - [`haddock-runner`](https://github.com/haddocking/haddock-runner): Tool to run large scale `haddock3` simulations using multiple input molecules in different scenarios
119
+ - [`haddock-tools`](https://github.com/haddocking/haddock-tools): Set of useful utility scripts developed over the years by the BonvinLab group members
120
+
121
+ ## Usage
122
+
123
+ The most basic usage is:
124
+
125
+ ```bash
126
+ haddock3 <configuration-file.toml>
127
+ ```
128
+
129
+ For help on haddock3 usage:
130
+
131
+ ```bash
132
+ $ haddock3 -h
133
+ usage: haddock3 [-h] [--restart RESTART] [--extend-run EXTEND_RUN] [--setup] [--log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}] [-v] recipe
134
+
135
+ positional arguments:
136
+ recipe The input recipe file path
137
+
138
+ optional arguments:
139
+ -h, --help show this help message and exit
140
+ --restart RESTART Restart the run from a given step. Previous folders from the selected step onwards will be deleted.
141
+ --extend-run EXTEND_RUN
142
+ Start a run from a run directory previously prepared with the `haddock3-copy` CLI. Provide the run directory created with `haddock3-copy` CLI.
143
+ --setup Only setup the run, do not execute
144
+ --log-level {DEBUG,INFO,WARNING,ERROR,CRITICAL}
145
+ -v, --version show version
146
+ ```
147
+
148
+ Check the [EXAMPLES](https://github.com/haddocking/haddock3/blob/main/examples/README.md) page for more some usage examples and the [User manual](https://www.bonvinlab.org/haddock3-user-manual) for a more detailed explanation of the configuration file.
149
+
150
+ ## Support
151
+
152
+ If you encounter any code-related issues, [please open an issue](https://github.com/haddocking/haddock3/issues/new/choose).
153
+
154
+ If you have any other questions or need help, please contact us at [ask.bioexcel.eu](https://ask.bioexcel.eu/).
155
+
156
+ If you clone this repository and use `haddock3` for your research, please support us by signing up in [this form](https://forms.gle/LCUHiYHh1hE9rd8L6). This will allow us contact you when needed for `haddock3`-related issues, and also provide us a mean to demonstrate impact when reporting for grants - which grealty helps us to keep the project alive!
157
+
158
+ ## Cite us
159
+
160
+ If you used `haddock3` for your research, please cite us:
161
+
162
+ - **Research article**: M. Giulini, V. Reys, J.M.C. Teixeira, B. Jiménez-García, R.V. Honorato, A. Kravchenko, X. Xu, R. Versini, A. Engel, S. Verhoeven, A.M.J.J. Bonvin, [*HADDOCK3: A modular and versatile platform for integrative modelling of biomolecular complexes*](https://pubs.acs.org/doi/10.1021/acs.jcim.5c00969) Journal of Chemical Information and Modeling (2025). doi: 10.1021/acs.jcim.5c00969 [[BioRxiv]](https://www.biorxiv.org/content/10.1101/2025.04.30.651432v1)
163
+
164
+ - **Cite this repository**: M.C. Teixeira, J., Vargas Honorato, R., Giulini, M., Bonvin, A., SarahAlidoost, Reys, V., Jimenez, B., Schulte, D., van Noort, C., Verhoeven, S., Vreede, B., SSchott, & Tsai, R. (2024). haddocking/haddock3: v3.0.0-beta.5 (Version 3.0.0-beta.5) [Computer software]. [https://doi.org/10.5281/zenodo.10527751](https://doi.org/10.5281/zenodo.10527751)
165
+
166
+ ## Useful resources
167
+
168
+ - [User manual](https://www.bonvinlab.org/haddock3-user-manual): The online HADDOCK3 guide describing every aspects of the tool.
169
+ - [Best practice guide](https://www.bonvinlab.org/software/bpg/) (HADDOCK2.X series)
170
+ - [The HADDOCK2.4 web server: A leap forward in integrative modelling of biomolecular complexes. Nature Prot. 2024](https://www.nature.com/articles/s41596-024-01011-0)
171
+
172
+ ## Development
173
+
174
+ Please check [DEVELOPMENT](https://github.com/haddocking/haddock3/blob/main/DEVELOPMENT.md) for instructions on how to develop `haddock3`
175
+
176
+ ### Code Documentation
177
+
178
+ The code documentation is automatically built and hosted at [bonvinlab.org/haddock3](https://www.bonvinlab.org/haddock3/).
179
+
180
+ To build it locally it is necessary to have some extra packages installed. You can install them using the following command:
181
+
182
+ ```bash
183
+ pip install -e '.[docs]'
184
+ ```
185
+
186
+ Then, to build the documentation, run the following commands:
187
+
188
+ ```bash
189
+ sphinx-apidoc -f -e -o docs/ src/haddock -d 1
190
+ sphinx-build -b html docs haddock3-docs
191
+ ```
192
+
193
+ > Warning messages are expected, but the documentation should be built successfully.
194
+
195
+ The rendered documentation will be available at `haddock3-docs/index.html`. This will open a local webpage with the
196
+
197
+ ### Contributing
198
+
199
+ Check the [CONTRIBUTING](CONTRIBUTING.md) file for instructions on how to contribute with the project!
200
+
201
+ <!-- ---
202
+
203
+ Happy HADDOCking!
204
+
205
+ <img src="https://www.bonvinlab.org/images/bio-haddock.png" alt="haddock" width="50px"> -->
.venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/RECORD ADDED
@@ -0,0 +1,571 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ../../../bin/haddock-restraints,sha256=Yags-YNY67tJLwfMd2_pZq_sz-aP_6FuwvicD8S3DBw,234
2
+ ../../../bin/haddock3,sha256=HbfycSqG7JkHVfu1D9670SESUMQzg8OInaflb02qREE,217
3
+ ../../../bin/haddock3-analyse,sha256=qCpYoFSoGA9gdvuRbu46H91TjHtxUwIHcbCWafUuoHs,225
4
+ ../../../bin/haddock3-cfg,sha256=Nqqqvi-PZyVx2i0JH1g3rde6uYAT3W_g2I4WcZmFCPE,221
5
+ ../../../bin/haddock3-clean,sha256=U5jXBhPP7vqMp2rsFrXptxExOkcG63EL1FNDMakHNHQ,223
6
+ ../../../bin/haddock3-copy,sha256=rcvMAxwINQe-Qv24fUD3nee2jGdB9ZCXuqt07jL1gKw,220
7
+ ../../../bin/haddock3-dmn,sha256=exb1Aop7kqqAhrptONYsqtFPT3dqWc9LdoGotYJuwPY,221
8
+ ../../../bin/haddock3-mpitask,sha256=47Cg7mItK8Dj53_JQ1861-wSoCCT0WXfkkSjFX4AgcU,221
9
+ ../../../bin/haddock3-pp,sha256=B8Cm4L42TSeRiRzH9iIWmICVFUUPsEXtA-SBy20ar5Q,220
10
+ ../../../bin/haddock3-re,sha256=MJ4Vw8DptOivUx3wOQbhbODMA1SBIH14Wwy2OOHwCdc,220
11
+ ../../../bin/haddock3-restraints,sha256=CZ94yeu7W_hRwcUffa4LeYvrlSr36O3Z-R46m6P3ZWw,228
12
+ ../../../bin/haddock3-score,sha256=EOcjnW0I9aCephqoxTkow13ucouSYkD-fdvSPyy1Sg0,223
13
+ ../../../bin/haddock3-traceback,sha256=_9PDyQF__1wI3w1XWCC97TEOjZTCOA33NuEO301pBek,227
14
+ ../../../bin/haddock3-unpack,sha256=r1oU7rdrcK6b_aW08m2I_-yPJxmo7fKkIXhzbm5X1pY,224
15
+ haddock/__init__.py,sha256=fIVrlAmZV9hM6SOJ1WyB0Poh2vShgepyMsy3BiJpGiE,1325
16
+ haddock/__pycache__/__init__.cpython-312.pyc,,
17
+ haddock/bin/contact_fcc,sha256=DJQb0bttBNGHK0nRmTEdstqltzFIW129po9kIAEoxDY,73320
18
+ haddock/bin/contact_fcc.cpython-312-darwin.so,sha256=FOj9VPji2dkAtHCMOH7bnmEEHtdErF_QNZ4-E7QKKLo,89904
19
+ haddock/bin/fast-rmsdmatrix,sha256=zxAahCUM1PGyjV5uq5me5xy7JD4JIM3TxDIZHFq8tEs,52512
20
+ haddock/bin/fast_rmsdmatrix.cpython-312-darwin.so,sha256=KgN-7iQLhS0-PBPJxJjcldF2ocXYjzkzzjSCYJaZCdA,69048
21
+ haddock/bin/haddock-restraints,sha256=Das8qLkNpGtjcL1q9Ilo3T3Nud649qCFptDM5PTx6mk,2157456
22
+ haddock/clis/__init__.py,sha256=hQdjlVdnd-_1BJHBTojZc5dpJPM2HtJ8ueluHj1VnUk,211
23
+ haddock/clis/__pycache__/__init__.cpython-312.pyc,,
24
+ haddock/clis/__pycache__/cli.cpython-312.pyc,,
25
+ haddock/clis/__pycache__/cli_analyse.cpython-312.pyc,,
26
+ haddock/clis/__pycache__/cli_cfg.cpython-312.pyc,,
27
+ haddock/clis/__pycache__/cli_clean.cpython-312.pyc,,
28
+ haddock/clis/__pycache__/cli_cp.cpython-312.pyc,,
29
+ haddock/clis/__pycache__/cli_dmn.cpython-312.pyc,,
30
+ haddock/clis/__pycache__/cli_mpi.cpython-312.pyc,,
31
+ haddock/clis/__pycache__/cli_pp.cpython-312.pyc,,
32
+ haddock/clis/__pycache__/cli_re.cpython-312.pyc,,
33
+ haddock/clis/__pycache__/cli_restraints.cpython-312.pyc,,
34
+ haddock/clis/__pycache__/cli_score.cpython-312.pyc,,
35
+ haddock/clis/__pycache__/cli_traceback.cpython-312.pyc,,
36
+ haddock/clis/__pycache__/cli_unpack.cpython-312.pyc,,
37
+ haddock/clis/__pycache__/wrapper_haddock_restraints.cpython-312.pyc,,
38
+ haddock/clis/cli.py,sha256=HNfcDz4F2xQAaPn7ntg5JukG_HfyVayawErv4UhSe9s,6064
39
+ haddock/clis/cli_analyse.py,sha256=06uPRsRW72qDcR1uM2qM4GipA_tEKacJJeyaqUGZPLo,25845
40
+ haddock/clis/cli_cfg.py,sha256=97OY3h0d9APVUBEojBQQrmSMzlPWrzKsuChG4uHyHls,6514
41
+ haddock/clis/cli_clean.py,sha256=lf2s6PGQbzkLjUHhOp9_jtiLHnrj5oPW_tQaST4-Fu4,2976
42
+ haddock/clis/cli_cp.py,sha256=kT3thSQ55T-DE8AsvKWutCXIst_TAHb47dDUGEGH2jg,4687
43
+ haddock/clis/cli_dmn.py,sha256=r28ByoEwQMZUuFcr2mbj-mRvsKdSpOOsvueAUV3s7YM,8863
44
+ haddock/clis/cli_mpi.py,sha256=-xwqD3s0-jOtVKYhWw1eoxLgBpKJjbNp9n85Amdiw8U,3114
45
+ haddock/clis/cli_pp.py,sha256=I5vIswQgYr7hsdTxL_8z_krKEcV2YuvOnmmwEKQZpqo,4357
46
+ haddock/clis/cli_re.py,sha256=oi8J-fag-NcSDq6eLc8OUi1zXlYmDWJ4i2k_VlolyGQ,1663
47
+ haddock/clis/cli_restraints.py,sha256=g6cKYGz16mAwimhNfC4LW-SJmBVh7G3xVPHiuXQAgpU,4304
48
+ haddock/clis/cli_score.py,sha256=8hd7c4YK74tKr8K9EJWe6zb62yZpSSyufyc6kDMlfMM,8874
49
+ haddock/clis/cli_traceback.py,sha256=WLU9rvhTofaepCSE1V0n7hqkGIgf_GAg9Jl3GUeCgDk,12694
50
+ haddock/clis/cli_unpack.py,sha256=qVGHgJtIpZ9XQdJ_srWn0OxN5rnkJueVjayu40g_gG4,3540
51
+ haddock/clis/re/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
52
+ haddock/clis/re/__pycache__/__init__.cpython-312.pyc,,
53
+ haddock/clis/re/__pycache__/clustfcc.cpython-312.pyc,,
54
+ haddock/clis/re/__pycache__/clustrmsd.cpython-312.pyc,,
55
+ haddock/clis/re/__pycache__/score.cpython-312.pyc,,
56
+ haddock/clis/re/clustfcc.py,sha256=8R_57DdEgxvmjv1xokV3_nYCpk8zeuaLiqekX2h9f3o,6623
57
+ haddock/clis/re/clustrmsd.py,sha256=7Ktju36_SEvgL2aPi-aAEKJkTIWV-D2pf-tjZy7bagk,8825
58
+ haddock/clis/re/score.py,sha256=aIfH1a47wtgobNBf2xaW5JM6SdN1y1SDcim1NmI3DYc,4540
59
+ haddock/clis/restraints/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
60
+ haddock/clis/restraints/__pycache__/__init__.cpython-312.pyc,,
61
+ haddock/clis/restraints/__pycache__/active_passive_to_ambig.cpython-312.pyc,,
62
+ haddock/clis/restraints/__pycache__/calc_accessibility.cpython-312.pyc,,
63
+ haddock/clis/restraints/__pycache__/passive_from_active.cpython-312.pyc,,
64
+ haddock/clis/restraints/__pycache__/random_removal.cpython-312.pyc,,
65
+ haddock/clis/restraints/__pycache__/restrain_bodies.cpython-312.pyc,,
66
+ haddock/clis/restraints/__pycache__/restrain_ligand.cpython-312.pyc,,
67
+ haddock/clis/restraints/__pycache__/validate_tbl.cpython-312.pyc,,
68
+ haddock/clis/restraints/__pycache__/webservice.cpython-312.pyc,,
69
+ haddock/clis/restraints/__pycache__/z_surface_restraints.cpython-312.pyc,,
70
+ haddock/clis/restraints/active_passive_to_ambig.py,sha256=EjG0fM1W5UuWEYZQamisc0x3FikLSLz8vonbug1XueA,2283
71
+ haddock/clis/restraints/calc_accessibility.py,sha256=M9Z4zhNXM7PXEkZaW816KMwMNgE51_GlOaY4deL1Ef8,11269
72
+ haddock/clis/restraints/naccess.config,sha256=bk8sLKHwBo2StPKMAZD5MrB7CXHi0Ms19rHSgW4-DEo,4493
73
+ haddock/clis/restraints/passive_from_active.py,sha256=7xVfgod0kTh6OSYBmsMV3mG7IqPlsGNxE4WCankx-bI,2192
74
+ haddock/clis/restraints/random_removal.py,sha256=ZC5xbZ7HkeQeEzzDhiRW8lY44JP_f2tSAOTW0g4749Q,5274
75
+ haddock/clis/restraints/restrain_bodies.py,sha256=osq-RLusT08rkECU5xduq526nI45P_yb3c-KKQk5uNE,1705
76
+ haddock/clis/restraints/restrain_ligand.py,sha256=2wgTBiWKdQjUfcoS-kpKqDKtrETAGjUDUa2BRTSSd_E,7477
77
+ haddock/clis/restraints/validate_tbl.py,sha256=4Sag8zN6KHdCVvwcPud4Lzp-SqkKHx7_TgNV1m7fT9U,1694
78
+ haddock/clis/restraints/webservice.py,sha256=Gtakyjba8rsPwehm8PiQhdpzYMLgydVWSRLBmZjx8nE,9774
79
+ haddock/clis/restraints/z_surface_restraints.py,sha256=qKBYYx2NKn7j93pOyxujOf3cYtJAP03CWDQTM3-Vrvg,23114
80
+ haddock/clis/wrapper_haddock_restraints.py,sha256=qkK7jgaAUtD0oe1U5EArqSJb6XyIlDE189Xv5shyTBs,432
81
+ haddock/cns/bin/aarch64-linux.bin,sha256=cgiN1cg69k5XbNlpP7t6AbrZU0GS7-KSiQyK17u7uXQ,3947816
82
+ haddock/cns/bin/arm64-darwin.bin,sha256=5v6_dOzLdA-LxdSZVcyPwgICXV1kLhKedzjnKArZWog,4171768
83
+ haddock/cns/bin/x86_64-darwin.bin,sha256=UR0WNJL4h4vojnQDP7-PnzHJdRW78Wo4di8_zQwP8x0,4089832
84
+ haddock/cns/bin/x86_64-linux.bin,sha256=zmsMa5044JmR-xVDFALpLLOMcjVEstzKeo3Ci2ZkOSc,6363048
85
+ haddock/cns/toppar/boxtyp20.pdb,sha256=sROuDiaM-qLE2ktszjP9ZSWckF2Nb0S2_kKVh81SRwA,51077
86
+ haddock/cns/toppar/carbohydrate.param,sha256=vPGsd7ljzfe5vY6Ps0pLNQm_wisQIll5W7y6Im6C0QY,12136
87
+ haddock/cns/toppar/carbohydrate.top,sha256=Q4zyL0GJ--GaakL_TW-LLWIKF0nggMbFIZ0J2QUgj6w,87186
88
+ haddock/cns/toppar/cofactors.param,sha256=zsmdvfZS_M5SQpT2xOPaCt03mXqM4Y0UMg7xktnx18U,144746
89
+ haddock/cns/toppar/cofactors.pep,sha256=daEdpEyAJIa8b2VkCqSKcw8PaExcB6Qro80XNes_sHA,2
90
+ haddock/cns/toppar/cofactors.top,sha256=WxfXuY29EZVGfRlZqG6Zbzd5LvMzFfkr2UQSD-2AXek,85089
91
+ haddock/cns/toppar/dmso.pdb,sha256=in1vU16IwxIYK00FzxQjxeEHtQbTA9Kbq0LZ0KzhvEM,57626
92
+ haddock/cns/toppar/dna-rna-1.3.link,sha256=FugBWXkMYrc6m0wmptr01bKLCPC8KmS5jmt1BIj3ylU,2259
93
+ haddock/cns/toppar/dna-rna-CG-MARTINI-2-1p-break.top,sha256=SZ2x6DLH5wcyz3SoHBNtUATt2qiqLanYnfokzfNoRAM,499
94
+ haddock/cns/toppar/dna-rna-CG-MARTINI-2-1p.link,sha256=SF_9DDUQgVImO_whCjop8kImw4oxAmaipztiZ2NeB98,1267
95
+ haddock/cns/toppar/dna-rna-CG-MARTINI-2-1p.param,sha256=gPlvW0DGdmzfK7ORBvkLNnIzW2XCWlFL361MZmGjUBY,76501
96
+ haddock/cns/toppar/dna-rna-CG-MARTINI-2-1p.top,sha256=1sLHl25iT5QhtxwWLd-koiPEUcBaZbZAscMTYj-6hrU,8756
97
+ haddock/cns/toppar/dna-rna-allatom-hj-opls-1.3.param,sha256=5W5PHA9vJFvrzbDWrnCl8L2a8Ihp9PT3hNEZTykETN0,62721
98
+ haddock/cns/toppar/dna-rna-allatom-hj-opls-1.3.top,sha256=BKACbR5dmo3yB_or_zLM_7A6erILgdiwySdHJRpM2xA,38255
99
+ haddock/cns/toppar/dna-rna-pho-1.3.link,sha256=TAdg38H-8aR1WbtHDlGyyvXueRGjFYdS5La7TAkmyW8,2230
100
+ haddock/cns/toppar/dna_break.top,sha256=jNWk98MIiiuVAv-D7nbsCz4VRJbyxXA7mOefOYl0J78,553
101
+ haddock/cns/toppar/fragment_probes.param,sha256=WkjBh_7xOdtQnnC5iMT3FAdMC-hPAjzhx5sibl3Cw9Q,27601
102
+ haddock/cns/toppar/fragment_probes.top,sha256=dqwqOyLA3dKrnHjdMYCJLy2jML8VZhWJTv8eD1_vtOM,60109
103
+ haddock/cns/toppar/heme.pdb,sha256=dIRbmE_a1TxTvpx8nFxWuYVjr-Fa9ED7uiFobxsV7GA,6372
104
+ haddock/cns/toppar/heme.psf,sha256=AO7A04zsDO6c_77JNmAo2neBmbLznohXejdIVPh1gGU,7674
105
+ haddock/cns/toppar/hemeB.pdb,sha256=CUBqwwh0afEIPoqWh1HXzYQIFIZs7wc2YGg_97bbMr0,5746
106
+ haddock/cns/toppar/hemeB.psf,sha256=6GAfkNHU1qEmWtb0DPVD1f7OxrwkENe9Jf0m52eFzQI,14147
107
+ haddock/cns/toppar/hemes-allhdg.param,sha256=tWeMEsN27BGNm7SxIfNJRGLkU3Asc51LUJhScFPKKqU,11258
108
+ haddock/cns/toppar/hemes-allhdg.top,sha256=3NRn1rwAOnS9MeVrQ2_28C6yl3lraR7-gL2PpKPBqtU,19060
109
+ haddock/cns/toppar/hemes.pep,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
110
+ haddock/cns/toppar/initial_positions/trans_vector_0,sha256=SwBBT7HxN1lS4_7Lv-C6Nuln3RLzCP1y9Wow4DVnmXY,114
111
+ haddock/cns/toppar/initial_positions/trans_vector_1,sha256=rtjduBEEzPBSHQ0gB0_XhHLGeMIp1XVQRaGrddmKRaA,117
112
+ haddock/cns/toppar/initial_positions/trans_vector_10,sha256=32pz0VLs4s31FrvxB0K46WlN9u7U72tqx9K-3QvE7bo,1189
113
+ haddock/cns/toppar/initial_positions/trans_vector_11,sha256=KVJgv3lu5ma0DdKSlhM7b6pMtMxWgZ2V3xQ-4o_nTEI,1310
114
+ haddock/cns/toppar/initial_positions/trans_vector_12,sha256=iXXjxf7-hC2hr-f1-nuLKQAROiwpU1TlBfmkW0plu3E,1431
115
+ haddock/cns/toppar/initial_positions/trans_vector_13,sha256=Z6Z31uhsvOrIYuWf70D4qMClfW_A16avVM8FjNw5GPQ,1552
116
+ haddock/cns/toppar/initial_positions/trans_vector_14,sha256=MIw7czOW-HiA0o_z4kh5rWxc0dhszpqNccs5gA_M_O8,1674
117
+ haddock/cns/toppar/initial_positions/trans_vector_15,sha256=6Y6T1AQ1jLu7dspPUDSo7hGDpZ_xu3hyYnBUONh5TcQ,1795
118
+ haddock/cns/toppar/initial_positions/trans_vector_16,sha256=IFWYxzto9yFNw_ji4vHF5dtyVD8Wwz_zqtck7sxkHyU,1918
119
+ haddock/cns/toppar/initial_positions/trans_vector_17,sha256=EaxylLQsSGoQd5DAZl-T1qMJ7O6k_WcGFuNwc8bN-Jw,2038
120
+ haddock/cns/toppar/initial_positions/trans_vector_18,sha256=YhCaxXSpINoWUvjKJHtBysbj0SyqMyQc72dPS0I97KI,2160
121
+ haddock/cns/toppar/initial_positions/trans_vector_19,sha256=Mfz8J0K-qaQTQv_d6J_KdHGoQMQjABY4-qTWjD-f8DU,2281
122
+ haddock/cns/toppar/initial_positions/trans_vector_2,sha256=GPonFreK6rDPuXricSRuEpIzgBXSNRUNQmM-zxUXTcw,237
123
+ haddock/cns/toppar/initial_positions/trans_vector_20,sha256=ODBLpHkiI7B-BeYmeRyBL7182HaX3ymH0EUfPk2yv7U,2403
124
+ haddock/cns/toppar/initial_positions/trans_vector_21,sha256=LsnG3uIodEESa5dU0ce3NLSc-XdivibppxraS5cGfTY,2524
125
+ haddock/cns/toppar/initial_positions/trans_vector_22,sha256=6X2ZJrO2v74Z82f1z-DYO9ig-TCbOnE_ZL9drC0Yj38,2645
126
+ haddock/cns/toppar/initial_positions/trans_vector_23,sha256=JvaB2-s36qbj0jjjQYFUnx8Qq7U9AkGipCXE8hcc94Y,2766
127
+ haddock/cns/toppar/initial_positions/trans_vector_24,sha256=TZseOIIOUBV13vTHUawpqOsA-ZBpWRkEohVFg5NybQE,2887
128
+ haddock/cns/toppar/initial_positions/trans_vector_25,sha256=jbv61_C9SBrRieeezOJL6o4VdYyEPRVMInuH7i8r17c,3010
129
+ haddock/cns/toppar/initial_positions/trans_vector_26,sha256=SNR8glIMs4FxrlnluzQrunRriSWYBfJM80r5poFRd70,3133
130
+ haddock/cns/toppar/initial_positions/trans_vector_27,sha256=HOgRJTe02k1nUAFUTIRuRBmSlO9v6k-LyjTytazjfc8,3253
131
+ haddock/cns/toppar/initial_positions/trans_vector_28,sha256=cCXRYBF57mrBvk6nys0YEVwiZr5r8RI6xY0HtLWRyDE,3376
132
+ haddock/cns/toppar/initial_positions/trans_vector_29,sha256=8pk1hA6-6sltWoHAAQnT6BbRKmIKdY-L-ep0tiN0-Vc,3497
133
+ haddock/cns/toppar/initial_positions/trans_vector_3,sha256=pbeRX5_vbSFuAGRPkKF2z4ocjPUvt9GiXcEoJrxpgAw,354
134
+ haddock/cns/toppar/initial_positions/trans_vector_30,sha256=9z4s49cys49ZVZ2Clx2iGHCPqmTYdxzjLkUpinnPQvA,3618
135
+ haddock/cns/toppar/initial_positions/trans_vector_31,sha256=CNqWOwLO94DpfpfHBJCMQF2_PBt6rdMes4GTVuRgp4A,3740
136
+ haddock/cns/toppar/initial_positions/trans_vector_32,sha256=f3RkyjF9cbfpOGC_BLNOqRrGtLkzuLQ5uM9WVh_XmNs,3861
137
+ haddock/cns/toppar/initial_positions/trans_vector_33,sha256=vp_i7RtNAoCrp_3qZ3dGp6qylVgWJ6JHewSOe5ZRrdk,3981
138
+ haddock/cns/toppar/initial_positions/trans_vector_34,sha256=VuePwiByUCWn782UBW9-_R-B0iLEGd1ly93Qy0NCF9M,4103
139
+ haddock/cns/toppar/initial_positions/trans_vector_35,sha256=HY5NNYbKDTv5pReRTMha-dEhxVjPRHfArmorkXARzVI,4226
140
+ haddock/cns/toppar/initial_positions/trans_vector_36,sha256=qSUHqc4NXWNFOjunMYhBdne0nKDuUBKbt2ri2vkuGDE,4347
141
+ haddock/cns/toppar/initial_positions/trans_vector_37,sha256=cabhHC2gbUAV-ua4BdhhHQRT_VAflOlOJMJ7nfidmIQ,4469
142
+ haddock/cns/toppar/initial_positions/trans_vector_38,sha256=G-_8b9YYa5o6dXbgNrborVMKBdWwMDM9zqOiMQLHCJo,4590
143
+ haddock/cns/toppar/initial_positions/trans_vector_39,sha256=QfQuaGCg746MM7sWrOiUFhvkGCWK7CqdPGMSxENoCKI,4713
144
+ haddock/cns/toppar/initial_positions/trans_vector_4,sha256=KQX0wW1AeAvuf53HsNBzGXQkQ7bZDL1cFr-SUbAxhEc,473
145
+ haddock/cns/toppar/initial_positions/trans_vector_40,sha256=M0drggL_YM04LxUgN0-oPXFfKsGVhOvsLL-osiXhlQM,4834
146
+ haddock/cns/toppar/initial_positions/trans_vector_41,sha256=6MNh7CpvoxHY1-4bFlXa6x4b2GOygGbsovxBeU23x40,4958
147
+ haddock/cns/toppar/initial_positions/trans_vector_42,sha256=yPXV9K00LiWw6dh5oWsI1KFq2eFGpqdgc5TtNOYyFEA,5076
148
+ haddock/cns/toppar/initial_positions/trans_vector_43,sha256=44heeC_5LKC2QE4t5-jCHxwMnBAkog3p8mzr5PdNiLc,5197
149
+ haddock/cns/toppar/initial_positions/trans_vector_44,sha256=t8ruh9HCr-PPs_n3otR83TfK1aQDO3wS3dX0kZWGqtc,5319
150
+ haddock/cns/toppar/initial_positions/trans_vector_45,sha256=DQiDSGzGyUwjoDmZ5sQ9GgKJIwp6ORNc5a1iXqO9PSk,5441
151
+ haddock/cns/toppar/initial_positions/trans_vector_46,sha256=c4pDHAHFeDmCsJK6uQa98Z3L6zHGM4JjFUvdjMflk6w,5561
152
+ haddock/cns/toppar/initial_positions/trans_vector_47,sha256=c33i0zyY4PWNSR0VIUktvvQBbLW-dzOwD9hVKaRV2wA,5684
153
+ haddock/cns/toppar/initial_positions/trans_vector_48,sha256=rXq0tH2X6ti4XggzLXjuM1bgK1SHMGDE_hWSaRwpS8s,5805
154
+ haddock/cns/toppar/initial_positions/trans_vector_49,sha256=QYw2KQMINmghAok-OhixWHdC2shDiKeq9CDCYAu98eg,5927
155
+ haddock/cns/toppar/initial_positions/trans_vector_5,sha256=LYAdBIeAZphgR9FVnwA1rHaITSdLw66WHKolliA4zlI,592
156
+ haddock/cns/toppar/initial_positions/trans_vector_50,sha256=f9VzoGOVTr02Q6JJ_LeNZYb5oklx5ZddFpFmDNP_zA8,6049
157
+ haddock/cns/toppar/initial_positions/trans_vector_6,sha256=M2MYuXSCQ-Di1CFgcHDtv7LJ7HEW2_DeXHIu9RRsSgY,711
158
+ haddock/cns/toppar/initial_positions/trans_vector_7,sha256=rqZC9pS6I4jywcIB7-kHcvpPN2BEq-eLJVvFitNccZI,831
159
+ haddock/cns/toppar/initial_positions/trans_vector_8,sha256=-5Zxpbwwm2FF1dJXn57e8Wii0aRxCs8WzeWDzNXAI7E,950
160
+ haddock/cns/toppar/initial_positions/trans_vector_9,sha256=MkreysXN4ZqX-HIX0ghG-ju3n6wzy6Nfsl9dSS-D-10,1067
161
+ haddock/cns/toppar/ion.param,sha256=hv0AZDT9-1oNa8mQN1nRJ6Cqkt5gPw1X3u_QwnFVk-4,5179
162
+ haddock/cns/toppar/ion.top,sha256=tUWJkmafNh4q9tiDnrfGdAgMT-87RJ8GVQnzfVl7_fw,10961
163
+ haddock/cns/toppar/metalcenter.tbl,sha256=nE6urZxJZXq1kJcEHRGNwJg8V8kAXxXnN8AWx93uJQo,160
164
+ haddock/cns/toppar/par_axis.pro,sha256=QcvLoIrq12XuQNJlypyGNg0_CNp_Zh0Hhh7RORtsCz0,700
165
+ haddock/cns/toppar/par_axis_dani.pro,sha256=qewpcxTdFm74WZ1GbB98NKt5WRX0ZqcEAeAeFCKoyN8,652
166
+ haddock/cns/toppar/protein-CG-Martini-2-2.link,sha256=R-JGxuijAbjpq5L2ikjl2gnQ_vrx_RL5KZvb8za78FQ,56248
167
+ haddock/cns/toppar/protein-CG-Martini-2-2.param,sha256=QgHFxgd805NxI84pDhaatYkAbUmOGMTMVCVh4KcQXaM,1404087
168
+ haddock/cns/toppar/protein-CG-Martini-2-2.top,sha256=DnmVsFid_xacYmmh7uPnIbt9ImvaiSkyq3XtsHSMRGk,7823
169
+ haddock/cns/toppar/protein-CG-Martini.link,sha256=R-JGxuijAbjpq5L2ikjl2gnQ_vrx_RL5KZvb8za78FQ,56248
170
+ haddock/cns/toppar/protein-CG-Martini.param,sha256=1SZ1ajgJltklg5b0qqGmGcotiBYDZTNzQmSz8TiHKTc,1833141
171
+ haddock/cns/toppar/protein-CG-Martini.top,sha256=F87Xg0vU5_sCV26G7wf1U7dSzenBXzv8uVrRmgWJE74,7303
172
+ haddock/cns/toppar/protein-allhdg5-4-noCter.link,sha256=MSGO8LLiT1O6L4ODQQrD--9zvSwSRyU04aZLlamDokM,94690
173
+ haddock/cns/toppar/protein-allhdg5-4-noNter.link,sha256=nAQpiIU5pxmkkkx0GF32VYymGgvgO5lDj_KoFzV370I,94589
174
+ haddock/cns/toppar/protein-allhdg5-4-noter.link,sha256=1tiK4XQ1Lt2O5ipdM6w2hBQQzeDp7-J-lePhkdPNrLA,93387
175
+ haddock/cns/toppar/protein-allhdg5-4.link,sha256=YIVnKQ4LUEE88qi0PwgXyYPAa7Z54AlH1a07H4DEPPI,95891
176
+ haddock/cns/toppar/protein-allhdg5-4.param,sha256=8h30h3ieGkRro1_or2bDz1U2TaqMUjAaK6_T3tf9W2k,119314
177
+ haddock/cns/toppar/protein-allhdg5-4.top,sha256=1c37BXS6tGAJCIMJy2Ry2Hce-j7aBfRsDTPnzdxXFlE,106529
178
+ haddock/cns/toppar/scatter.lib,sha256=QbuDzDND0nXUHnPGE1j5xjMU4eG9gghXoafMgWjkn3M,27508
179
+ haddock/cns/toppar/shape.param,sha256=3Ns17S4SR6WqXLq6hU1-yb1SDVl4L1i4o5ejsAHLgYU,229
180
+ haddock/cns/toppar/shape.top,sha256=e4V32_I13vtNPGdJLihWgh-lWNzFSKKWN0JnscgdZNQ,352
181
+ haddock/cns/toppar/solvent-allhdg5-4.param,sha256=BaapuWG0qUlTQjUvYgB5QZjbErnRVHI-3HuJi4eDQ0w,1376
182
+ haddock/cns/toppar/solvent-allhdg5-4.top,sha256=SzVG8KirJ460WHS0YSaAuWqxRg7kivtHrr1ErEcju44,3983
183
+ haddock/cns/toppar/tensor.pdb,sha256=FxQeD9NNeaNAlDwldq0dgHm5_RFWcxu0SUBuHJWFs0A,3253
184
+ haddock/cns/toppar/tensor.psf,sha256=WcmWCaVK33MnfCneVRWkj3AKFzd3UFRVJJLlm-YycaM,3303
185
+ haddock/cns/toppar/tensor_dani.pdb,sha256=WWshNHksvNUOvAlgfMpQs-oETqph2kFmqaM6AIxeFLc,1750
186
+ haddock/cns/toppar/tensor_dani.psf,sha256=qq0Uef1h1q2dbJO0i1JdAX_cR-dBi3AlR2RLDbvfqtk,2135
187
+ haddock/cns/toppar/tensor_para.pdb,sha256=QUUM3dPUW3x0L5zJYAIsg_TwKsadzQPtRsFoKMVmH2o,3260
188
+ haddock/cns/toppar/tensor_para.psf,sha256=deVGT8ZwFqE4YjNhOLE5hHzlbRbWMdnVPfwe0XU2IT8,3430
189
+ haddock/cns/toppar/top_axis.pro,sha256=Z-Sikf-PDxIQG67l-SphHbUo-B7dJkR0HhmyjSDRL9Y,976
190
+ haddock/cns/toppar/top_axis_dani.pro,sha256=XgxnQVlXDm45_VHPM7wNEsjKjhIAuOKeUq1tbh5j2yc,533
191
+ haddock/core/__init__.py,sha256=LvOBCQzcgwxQPixN3ae2TjxXlDdjw0Ax2Rds4h1UFEE,39
192
+ haddock/core/__pycache__/__init__.cpython-312.pyc,,
193
+ haddock/core/__pycache__/cns_paths.cpython-312.pyc,,
194
+ haddock/core/__pycache__/defaults.cpython-312.pyc,,
195
+ haddock/core/__pycache__/exceptions.cpython-312.pyc,,
196
+ haddock/core/__pycache__/supported_molecules.cpython-312.pyc,,
197
+ haddock/core/__pycache__/typing.cpython-312.pyc,,
198
+ haddock/core/cns_paths.py,sha256=qJyE6Z-Uty5by6OiYXm60_tVv84j53t3vwHYCe7Cb7Y,2828
199
+ haddock/core/defaults.py,sha256=yKknPzxichto_jG3ZJ48wsSAcyrpZPmROdmzJMwKI7I,1413
200
+ haddock/core/exceptions.py,sha256=T86eYzR0biAFyIt2XKEtjoEjH5DiXZm8PT6e_fGlVIQ,1535
201
+ haddock/core/mandatory.yaml,sha256=wX-qX6eZN_r8hWOq7viqzrcXv4A9XpZDpIQelApHtqU,496
202
+ haddock/core/optional.yaml,sha256=cNkWKEPh6I6PspNb4x4IUUt-5YKCKVMYGq9ObO9pGQU,1590
203
+ haddock/core/supported_molecules.py,sha256=ilmim2ZnlWpoYPWvjgpXBAbo43wfM_quRkVe5Foh3hA,16077
204
+ haddock/core/typing.py,sha256=zVKozQwtcohx-Lfa8HM8y4fx_xi5ti1z2Zv99_e_BcE,4555
205
+ haddock/deps/contact_fcc.cpp,sha256=ITn5R6VQmurHZ2XEuNpC0aeu54YbDgXZekpOshvTOKs,2948
206
+ haddock/deps/fast-rmsdmatrix.c,sha256=IXXeREAcNmrWKcCHvLRG1_4IzA5noeY-1je4HbHCJbE,29676
207
+ haddock/fcc/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
208
+ haddock/fcc/__pycache__/__init__.cpython-312.pyc,,
209
+ haddock/fcc/__pycache__/calc_fcc_matrix.cpython-312.pyc,,
210
+ haddock/fcc/__pycache__/cluster_fcc.cpython-312.pyc,,
211
+ haddock/fcc/calc_fcc_matrix.py,sha256=L1I-q5PZLGRwtw365y3rXchX6bqtm-XfS9cOujVIT5k,2453
212
+ haddock/fcc/cluster_fcc.py,sha256=uRL_hM6ObhHSL_IMLhzIk8SyunZC5u5aWO-bIid1hpA,4628
213
+ haddock/gear/__init__.py,sha256=DISpBt2ms1ySWT0xuSistlspfN9pzeXEcX53-U222Ec,274
214
+ haddock/gear/__pycache__/__init__.cpython-312.pyc,,
215
+ haddock/gear/__pycache__/clean_steps.cpython-312.pyc,,
216
+ haddock/gear/__pycache__/config.cpython-312.pyc,,
217
+ haddock/gear/__pycache__/expandable_parameters.cpython-312.pyc,,
218
+ haddock/gear/__pycache__/extend_run.cpython-312.pyc,,
219
+ haddock/gear/__pycache__/greetings.cpython-312.pyc,,
220
+ haddock/gear/__pycache__/haddockmodel.cpython-312.pyc,,
221
+ haddock/gear/__pycache__/known_cns_errors.cpython-312.pyc,,
222
+ haddock/gear/__pycache__/parameters.cpython-312.pyc,,
223
+ haddock/gear/__pycache__/postprocessing.cpython-312.pyc,,
224
+ haddock/gear/__pycache__/prepare_run.cpython-312.pyc,,
225
+ haddock/gear/__pycache__/preprocessing.cpython-312.pyc,,
226
+ haddock/gear/__pycache__/restart_run.cpython-312.pyc,,
227
+ haddock/gear/__pycache__/validations.cpython-312.pyc,,
228
+ haddock/gear/__pycache__/yaml2cfg.cpython-312.pyc,,
229
+ haddock/gear/__pycache__/zerofill.cpython-312.pyc,,
230
+ haddock/gear/clean_steps.py,sha256=rOlXliZ93XrRwU-WfpUuu6-FT37AYoRxMOBej-Dd5jM,7379
231
+ haddock/gear/config.py,sha256=oH2Wnzf4HF7f5sU1noE3aDzBWn1vOZatevaScAHaUGY,9820
232
+ haddock/gear/expandable_parameters.py,sha256=AtHl24Fw7Qeqd22lJjwxIU96GV7zNZrQjm1PxMiM5aY,27121
233
+ haddock/gear/extend_run.py,sha256=RlrnlGdyYeo2Y4fWRUKB6AciIUE7K-Nv2WNucvlaDow,8139
234
+ haddock/gear/greetings.py,sha256=OWfnxg-_RN3gjBNMg_1Ec3ukX2eIZRlXrjyc_TsCIAk,3516
235
+ haddock/gear/haddockmodel.py,sha256=2xBtLlMkYsOd7CQ0Qq2RyKV7XowRcJlhURE_n14_XRA,5437
236
+ haddock/gear/known_cns_errors.py,sha256=CDtBJ1RSWBmRAJzuiCT5BrfCC5Ch2Hw_hOR3J130zr8,6910
237
+ haddock/gear/parameters.py,sha256=e7ZAOzOZzijlKWHTqeDgHP-QGu0HKCdlinc6Klk3M68,749
238
+ haddock/gear/postprocessing.py,sha256=xnNurZ8P5VYRb1TeZOYOwM2ZC8LQYJdqQP0qIeMJN1k,1439
239
+ haddock/gear/prepare_run.py,sha256=b9JXlHSrDBwucLbTezMYVOfA_TRx0YKDBTEajTjLpKc,47960
240
+ haddock/gear/preprocessing.py,sha256=IoJivA3VDBhfK_3nj2LrKHmZQUyDjKYdMtAW7_iO3ls,31188
241
+ haddock/gear/restart_run.py,sha256=QO6ROHqg24m36r1_NkEyPJ1eX57QZSo1M8d8xMaIWis,1803
242
+ haddock/gear/validations.py,sha256=79Hii60bB58g4NJziYPQWh3rm4u70gvj0u1Ff9KNBzI,4376
243
+ haddock/gear/yaml2cfg.py,sha256=DATeKFsLJv2Ly506O_J20wqmbLncbzDL6l21Yl4vw94,9133
244
+ haddock/gear/zerofill.py,sha256=TesdOODdbIKdekwXRaO4l2jdggo5P7lMYGwBGVgXhn8,3373
245
+ haddock/libs/__init__.py,sha256=v4-UCEx7R8hJRTKSBQzPvkyXnQb6q7hvkQCmPVA6AnU,47
246
+ haddock/libs/__pycache__/__init__.cpython-312.pyc,,
247
+ haddock/libs/__pycache__/libalign.cpython-312.pyc,,
248
+ haddock/libs/__pycache__/libcli.cpython-312.pyc,,
249
+ haddock/libs/__pycache__/libclust.cpython-312.pyc,,
250
+ haddock/libs/__pycache__/libcns.cpython-312.pyc,,
251
+ haddock/libs/__pycache__/libfcc.cpython-312.pyc,,
252
+ haddock/libs/__pycache__/libfunc.cpython-312.pyc,,
253
+ haddock/libs/__pycache__/libgrid.cpython-312.pyc,,
254
+ haddock/libs/__pycache__/libhpc.cpython-312.pyc,,
255
+ haddock/libs/__pycache__/libinteractive.cpython-312.pyc,,
256
+ haddock/libs/__pycache__/libio.cpython-312.pyc,,
257
+ haddock/libs/__pycache__/libligand.cpython-312.pyc,,
258
+ haddock/libs/__pycache__/liblog.cpython-312.pyc,,
259
+ haddock/libs/__pycache__/libmath.cpython-312.pyc,,
260
+ haddock/libs/__pycache__/libmpi.cpython-312.pyc,,
261
+ haddock/libs/__pycache__/libnotebooks.cpython-312.pyc,,
262
+ haddock/libs/__pycache__/libontology.cpython-312.pyc,,
263
+ haddock/libs/__pycache__/libparallel.cpython-312.pyc,,
264
+ haddock/libs/__pycache__/libpdb.cpython-312.pyc,,
265
+ haddock/libs/__pycache__/libplots.cpython-312.pyc,,
266
+ haddock/libs/__pycache__/libprodigy.cpython-312.pyc,,
267
+ haddock/libs/__pycache__/librestraints.cpython-312.pyc,,
268
+ haddock/libs/__pycache__/libstructure.cpython-312.pyc,,
269
+ haddock/libs/__pycache__/libsubprocess.cpython-312.pyc,,
270
+ haddock/libs/__pycache__/libtimer.cpython-312.pyc,,
271
+ haddock/libs/__pycache__/libutil.cpython-312.pyc,,
272
+ haddock/libs/__pycache__/libworkflow.cpython-312.pyc,,
273
+ haddock/libs/assets/__init__.py,sha256=OHnRgMfl3EKH39_jt29TsQgdlCh77a-S2ckhajnR5RE,361
274
+ haddock/libs/assets/__pycache__/__init__.cpython-312.pyc,,
275
+ haddock/libs/assets/index.css,sha256=zQhm56MPdkCiONjcDcbJGOJzxcsE62IwpoHpWMZ5LR0,10785
276
+ haddock/libs/assets/report.bundle.js,sha256=wJLAYIGv-zCto98hmwFLB3dtsl7xpNdkjB6Fqx-rxpo,1481453
277
+ haddock/libs/libalign.py,sha256=THxG3qZqWAQnJRkjTrHY77egeu1hQJ6iO66Fhc0nlY0,38721
278
+ haddock/libs/libcli.py,sha256=jYvqc8-m9BUevDitjw4ps97mO_2-OQ_okECJ1wwloYM,2716
279
+ haddock/libs/libclust.py,sha256=n7LG4n5bI0TCKJNP-6j2DwRBJOR2G-2JC7BnDeWOC4w,9655
280
+ haddock/libs/libcns.py,sha256=4voTSRCv7VjAyy1JC4mfnamB-pDWNBBOenoqWefRbDo,14193
281
+ haddock/libs/libfcc.py,sha256=zk8-uss90KFfBEsphXOVuz_jHn8pY9fcsholiL1od-s,6562
282
+ haddock/libs/libfunc.py,sha256=Y6afr2DT7Rx42FBHoRm4TIL3qRueKldKKyW-s7Z8JZA,2274
283
+ haddock/libs/libgrid.py,sha256=R0nC-f9A5hKK7kKgKw5c_mJ1IxFvvfr1JR-6SbvDyN4,29623
284
+ haddock/libs/libhpc.py,sha256=EQpn5for3hRLkp6OrIx00t18ZvkjplOh04g88Ay7yf0,12354
285
+ haddock/libs/libinteractive.py,sha256=WtO3vNf3pKpZ3rlzhflE9wb8zuztNTI3qTKoCGwfkmE,7329
286
+ haddock/libs/libio.py,sha256=R3wDEO7YGYZZEFBvG7OKm6THq4JsELoRDMT0tK2-47E,16530
287
+ haddock/libs/libligand.py,sha256=2CKBNWSXE0X49kRaigMu-GzdnZ2SAvsvco0wLhLrzkU,5462
288
+ haddock/libs/liblog.py,sha256=xp1Qinu8Ct8LVHPEAVb4ik_mj48kK096GnBoMq6G37I,2333
289
+ haddock/libs/libmath.py,sha256=PdPROXkAuA4Ujq7cfG-u8VsQjFTnO8nhM7gANqvVr5o,865
290
+ haddock/libs/libmpi.py,sha256=yl_peJ6JNQpU-gNzCcY03Q9RGfFbxBzM6MQH-DZtwD8,1803
291
+ haddock/libs/libnotebooks.py,sha256=wAO--cC-PGENU8-N-rqMnhdyV6RKuMj6jC42pllOF9w,9460
292
+ haddock/libs/libontology.py,sha256=iTUJlmFc2u8Qy8w1Uem4zE1TeZ9pB93yB0me1GnY97k,8332
293
+ haddock/libs/libparallel.py,sha256=2-EolmGZb5Av_MR5AROX5MaxfuMxL9TejWoqtym3zJo,6379
294
+ haddock/libs/libpdb.py,sha256=IjNy6HCQlMvNc57QMf9tqrXOJj30SxpDuuwtGcNkmRU,16280
295
+ haddock/libs/libplots.py,sha256=rMx85zZKQ5yWcMxG2ONwqxHbehG_ZCyb4Pl_rnWa3UI,49143
296
+ haddock/libs/libprodigy.py,sha256=ofVMTELREPyxwJzVuLGPzehk7eNTWkgY2CDD_pALx4k,5026
297
+ haddock/libs/librestraints.py,sha256=OBemuZSLFlfuubMox1lBQz0Ju8WkqWAmM-E29b-LuqU,28610
298
+ haddock/libs/libstructure.py,sha256=uRPaaJsZPbiB7jyWFJwBeLwbA6OfEZbHavhxlrjK7f8,1367
299
+ haddock/libs/libsubprocess.py,sha256=o8zQeOJ3BlhujxnL46irHd7uNYMQd0mGIQty-bGBnps,8033
300
+ haddock/libs/libtimer.py,sha256=8vFHFbBSRM5AkJ4b-I4Ph4NYBMYEeYIZ5ttTu3tD2n4,1607
301
+ haddock/libs/libutil.py,sha256=nso_xPfqlY0JUqUE2bF9DSCcpd-dq0ReWTk7y7xnNSI,14005
302
+ haddock/libs/libworkflow.py,sha256=HhNYok2Wx0yRzsnelwKrndvrcp4zaWomLZI0nY_gGzM,7364
303
+ haddock/modules/__init__.py,sha256=adGlrDRDtzl9ot3sz3jW3pfyTxGmIRYicn6S04uGaKM,17125
304
+ haddock/modules/__pycache__/__init__.cpython-312.pyc,,
305
+ haddock/modules/__pycache__/base_cns_module.cpython-312.pyc,,
306
+ haddock/modules/_template_cat/README.md,sha256=q1EPD15gNjWwQa6QCTnlRhTBaBHZjMOMiWslkBM6LHM,1694
307
+ haddock/modules/_template_cat/_template_mod/__init__.py,sha256=gbz7p-C7DbePqq3w0R9nuiD8ymnEs2N6nnxz_bEIPyQ,5548
308
+ haddock/modules/_template_cat/_template_mod/__pycache__/__init__.cpython-312.pyc,,
309
+ haddock/modules/_template_cat/_template_mod/defaults.yaml,sha256=EKZzFFd9tfO6_MNG9OGyM_6mLuVfeiuyffZcys2iTM4,1941
310
+ haddock/modules/analysis/__init__.py,sha256=OUxBnttEXAAjGXnJWHJ8k-Jir8HyLzeqyEhtS9e9YDo,1926
311
+ haddock/modules/analysis/__pycache__/__init__.cpython-312.pyc,,
312
+ haddock/modules/analysis/alascan/__init__.py,sha256=EDeh6qzv1lpijgH5c6DELOG3JhIe5xzf-q5v9ibJQmw,7862
313
+ haddock/modules/analysis/alascan/__pycache__/__init__.cpython-312.pyc,,
314
+ haddock/modules/analysis/alascan/__pycache__/scan.cpython-312.pyc,,
315
+ haddock/modules/analysis/alascan/defaults.yaml,sha256=C1EK-pA7YwPtWyfx4MChQ788P7WGSCFqO0zl1aHnK9Q,3753
316
+ haddock/modules/analysis/alascan/scan.py,sha256=sp2KdjR3Sumk3_9mg3Ov57GbFoptethENSwJWC-z38A,33797
317
+ haddock/modules/analysis/caprieval/__init__.py,sha256=trmXV9nFx-WdvcV8Rml6BnI1WbUk7ao0qR8LW5qWTpI,9880
318
+ haddock/modules/analysis/caprieval/__pycache__/__init__.cpython-312.pyc,,
319
+ haddock/modules/analysis/caprieval/__pycache__/capri.cpython-312.pyc,,
320
+ haddock/modules/analysis/caprieval/capri.py,sha256=t2aLsqYCrWZiNKKf9kN_wCMN3zBCACYg_xDW10oJgPc,39733
321
+ haddock/modules/analysis/caprieval/defaults.yaml,sha256=jRrJdXHmdQ78xgLJ46P_L2f63w9-TfYD9NN0a9Lck6k,6944
322
+ haddock/modules/analysis/clustfcc/__init__.py,sha256=ZEKa0_hWYrzrCmsw_L5hnlonAJbvG4gZTlTDv0qE5EU,7456
323
+ haddock/modules/analysis/clustfcc/__pycache__/__init__.cpython-312.pyc,,
324
+ haddock/modules/analysis/clustfcc/__pycache__/clustfcc.cpython-312.pyc,,
325
+ haddock/modules/analysis/clustfcc/clustfcc.py,sha256=U-CV-LcXxMbDGcAP0hCDP0GcFg8nDxjioL3KXM3siI8,6114
326
+ haddock/modules/analysis/clustfcc/defaults.yaml,sha256=zoQGTLJtvDZwJdzZfI-vZpz9hN0Qvhn3PZ8eHPjl8QA,2519
327
+ haddock/modules/analysis/clustrmsd/__init__.py,sha256=wB_zfn5Ray5SA6jlSruqeFc6NKwiEJA1isDy4QLsIgg,6350
328
+ haddock/modules/analysis/clustrmsd/__pycache__/__init__.cpython-312.pyc,,
329
+ haddock/modules/analysis/clustrmsd/__pycache__/clustrmsd.cpython-312.pyc,,
330
+ haddock/modules/analysis/clustrmsd/clustrmsd.py,sha256=1AbNzmz0LnYczZnKB30iXZILBvBY19J2NfFDp6MCS_E,12387
331
+ haddock/modules/analysis/clustrmsd/defaults.yaml,sha256=ko2SVYIfdXsZTeRXMtbr3W5HKNVrayR0fyWe7kW-B6k,2044
332
+ haddock/modules/analysis/contactmap/__init__.py,sha256=XV1qnG_ZC1ou8envXBvhpDKRP1DA2fY-1F0SuqURyAA,4424
333
+ haddock/modules/analysis/contactmap/__pycache__/__init__.cpython-312.pyc,,
334
+ haddock/modules/analysis/contactmap/__pycache__/contmap.cpython-312.pyc,,
335
+ haddock/modules/analysis/contactmap/contmap.py,sha256=Qv0-penTUsWCWvugHS7KwR8F81nu0egyfKyk4AHnpBs,74236
336
+ haddock/modules/analysis/contactmap/defaults.yaml,sha256=3gMMRx7TXBaae9A1jIF9Z-yiPbgnvmcKmYNJ8DcRC8o,3263
337
+ haddock/modules/analysis/filter/__init__.py,sha256=8dnxVQpOEJ6JlGL7TYKCRTg-_gxSsgkpkGvdypdRvek,3736
338
+ haddock/modules/analysis/filter/__pycache__/__init__.cpython-312.pyc,,
339
+ haddock/modules/analysis/filter/defaults.yaml,sha256=LaRHAWiGarOWQEvDjjB749G5TRk9LFGHORmC9S-WH0s,371
340
+ haddock/modules/analysis/ilrmsdmatrix/__init__.py,sha256=Tg9DEGYxh1VaYUeIvPg_RNF9QyGd3TYD1Wskgfv7awI,14168
341
+ haddock/modules/analysis/ilrmsdmatrix/__pycache__/__init__.cpython-312.pyc,,
342
+ haddock/modules/analysis/ilrmsdmatrix/__pycache__/ilrmsd.cpython-312.pyc,,
343
+ haddock/modules/analysis/ilrmsdmatrix/defaults.yaml,sha256=DmdQo293VbE1VUHIYdSbvuEFo8z222lt9Byk0g-i1SU,2474
344
+ haddock/modules/analysis/ilrmsdmatrix/ilrmsd.py,sha256=asoMkpLtMoi_ScFIo3J7aDQAZqzzFSY6w-SJCotd6dk,3809
345
+ haddock/modules/analysis/rmsdmatrix/__init__.py,sha256=C0vjkTQho3iW7FlLfmFz3kvAn3O_YKCm-mhJVsgRiWU,8373
346
+ haddock/modules/analysis/rmsdmatrix/__pycache__/__init__.cpython-312.pyc,,
347
+ haddock/modules/analysis/rmsdmatrix/__pycache__/rmsd.cpython-312.pyc,,
348
+ haddock/modules/analysis/rmsdmatrix/defaults.yaml,sha256=cS_Y7XKiolEaNDFOltU00xjBzYMx5CoGrVciDmr4V68,1639
349
+ haddock/modules/analysis/rmsdmatrix/rmsd.py,sha256=NEDc23-ITL7cbsRwObyETZgO25Iy_9nwMiT30sHfx1Y,3872
350
+ haddock/modules/analysis/seletop/__init__.py,sha256=crGU45EQGDbKE8lBgRc5Bz396eVSMD9vzEv_fGYgAWs,2162
351
+ haddock/modules/analysis/seletop/__pycache__/__init__.cpython-312.pyc,,
352
+ haddock/modules/analysis/seletop/defaults.yaml,sha256=HpnqYme7nFFeyjKB6wg7or4dlzZN-61biyj0HTyJbNI,412
353
+ haddock/modules/analysis/seletopclusts/__init__.py,sha256=vj8kudb81Y8wX832NWH43018l_DQxYCuXVKybHJRFEA,2908
354
+ haddock/modules/analysis/seletopclusts/__pycache__/__init__.cpython-312.pyc,,
355
+ haddock/modules/analysis/seletopclusts/__pycache__/seletopclusts.cpython-312.pyc,,
356
+ haddock/modules/analysis/seletopclusts/defaults.yaml,sha256=dWxN_rdic4WRUTLzdiG2FAxqOMnKKrczMAEtfWhMlbY,1414
357
+ haddock/modules/analysis/seletopclusts/seletopclusts.py,sha256=MOwuIyuJuRYc5ml58zOvi7H-Ko7T7ARe6whaqXs0EHc,7051
358
+ haddock/modules/base_cns_module.py,sha256=OyrDmj4ed2lJkgy1ArBwjpzTYpKfv8xp8WL89EMvkd4,6366
359
+ haddock/modules/defaults.yaml,sha256=xmAr6EZ03_u0Qy8P86R8eMJhaS86I4g1RY6u7kukKbw,6014
360
+ haddock/modules/extras/__init__.py,sha256=cDHmAvelnn80uqO6ouvds1ahgFBIgI0DqFv9Z0Jo8rY,175
361
+ haddock/modules/extras/__pycache__/__init__.cpython-312.pyc,,
362
+ haddock/modules/extras/exit/__init__.py,sha256=37VlCgPBIiLU8vtFDgioJMRamTtK4SzTdCpTkf2w1RQ,1703
363
+ haddock/modules/extras/exit/__pycache__/__init__.cpython-312.pyc,,
364
+ haddock/modules/extras/exit/defaults.yaml,sha256=9OTiEcCv4zBEYfle2uTwAdmMEKazk5a6TuShUv1SEE8,238
365
+ haddock/modules/refinement/__init__.py,sha256=cMG5Zt4JDKvNK207ct6FMJ0EgbmU0e_1L-V_ZXCsOZc,48
366
+ haddock/modules/refinement/__pycache__/__init__.cpython-312.pyc,,
367
+ haddock/modules/refinement/emref/__init__.py,sha256=bhWdqXv9M5MqTfihaGzz_q6WbCDby7T1RTE0XeofBWk,5143
368
+ haddock/modules/refinement/emref/__pycache__/__init__.cpython-312.pyc,,
369
+ haddock/modules/refinement/emref/cns/calc_free-ene.cns,sha256=oiXJjYSnG23nizBMv1D6YbeI-c4kDdQahRsuq0rn2w0,1116
370
+ haddock/modules/refinement/emref/cns/check_coordinates.cns,sha256=diLUZz3XxMMb1towOaeWlGRiSNh72dgB5oX6tV57tFg,3015
371
+ haddock/modules/refinement/emref/cns/contactairs.cns,sha256=LtMZm33ScEAnNE1J5HE-iQ95R8CtpTTCne4F23w7moc,1426
372
+ haddock/modules/refinement/emref/cns/def_solv_param.cns,sha256=hRyLXwbnm7zoCidi_Eeztq-NvBjSiWIJfxo9WXcRzPo,4071
373
+ haddock/modules/refinement/emref/cns/dna-rna_restraints.cns,sha256=gkljYrv7AqP3x9ujcjQYVSmhH6vknqW0GKmqyCBH-SY,19764
374
+ haddock/modules/refinement/emref/cns/emref.cns,sha256=HKePIsUY7IUdYEU3T0f5K-yelyDXakuZuhsmBcWktdo,13409
375
+ haddock/modules/refinement/emref/cns/flex_segment_back.cns,sha256=ZcURFVmlEIXHw96PSZ-GPmM_IyrCivG5A_8AKotuSQw,2320
376
+ haddock/modules/refinement/emref/cns/flexauto-neighbors.cns,sha256=TysMjn197bNZ1gPSty-f0341t5fHc-K-I4aEvfE2-DA,1934
377
+ haddock/modules/refinement/emref/cns/print_coorheader.cns,sha256=AdRuACCZ5TIWwBPuSVXVvQhD6728rIUxhwtN4yiLWmw,12246
378
+ haddock/modules/refinement/emref/cns/protein-ss-restraints-all.cns,sha256=Ng7k_RoSrORIj77EFUIPuQ5xLwqMkcTw8byDF6ets70,4239
379
+ haddock/modules/refinement/emref/cns/protein-ss-restraints-alpha-beta.cns,sha256=v02vtd4tzMDvoLr9tQgAkiKah2yJGBUJ0ufO8-8r2IE,6002
380
+ haddock/modules/refinement/emref/cns/protein-ss-restraints-alpha.cns,sha256=zp_fje9KlUkwrqN9C6RVoXtAo674GEj69AmAALuLz48,5163
381
+ haddock/modules/refinement/emref/cns/read_data.cns,sha256=5timDjMPd5_cTA8djQjuLxoIBBhOAwefdlFOj-BE6ms,2026
382
+ haddock/modules/refinement/emref/cns/read_noes.cns,sha256=nLADAFcVjbJ-WN8Zza5mgYZFkvZNldL9feUidQRVN1I,1817
383
+ haddock/modules/refinement/emref/cns/read_param.cns,sha256=Dm_oGn9aIJILPsFIa1RvAp21w5AeekXLxJLdh7u9BXY,2021
384
+ haddock/modules/refinement/emref/cns/restrain-ions.cns,sha256=gb6AqflQscIatvKUSXno6wO6G2-kbncNNwaId2b5J7U,5237
385
+ haddock/modules/refinement/emref/cns/scale_inter.cns,sha256=mKIJ7R65tB9DuqAMCOfADPW2vZY5aFnFvo-Xkxjxy_w,2349
386
+ haddock/modules/refinement/emref/cns/scale_inter_final.cns,sha256=WPncZ_1Rp757GyOZL9YFp0ONAfpIzV7WW6Lvrhy4LNQ,1836
387
+ haddock/modules/refinement/emref/cns/scale_intra_only.cns,sha256=BIA9k5ETYoSswYiZXTnVaE5g6N7k0TTIhhG-Amot3Q8,1489
388
+ haddock/modules/refinement/emref/cns/setflags.cns,sha256=BWCTCEU-7i6rDsArjZ_EWJd6pe-sj275phmD9EJs0Es,771
389
+ haddock/modules/refinement/emref/cns/symmultimer.cns,sha256=v-RvMEcmhxmwJgetDufqr2OHO9JTOaHIU1cm_vshTf8,32233
390
+ haddock/modules/refinement/emref/defaults.yaml,sha256=SjCKBbTRPrqWGc7v-dd19_jFzI7G2x0-zXH0dBL2sU8,162391
391
+ haddock/modules/refinement/flexref/__init__.py,sha256=dSHD9Rbwl9CZnWX2oen9HXX5FYhtC3pIAs2zBiOGflM,5835
392
+ haddock/modules/refinement/flexref/__pycache__/__init__.cpython-312.pyc,,
393
+ haddock/modules/refinement/flexref/cns/calc_free-ene.cns,sha256=oiXJjYSnG23nizBMv1D6YbeI-c4kDdQahRsuq0rn2w0,1116
394
+ haddock/modules/refinement/flexref/cns/check-homomers.cns,sha256=t0rPTSXU44EPwZ-Q6Av73QyEXjaYvjzAHXm7FGIQZms,1736
395
+ haddock/modules/refinement/flexref/cns/check_coordinates.cns,sha256=diLUZz3XxMMb1towOaeWlGRiSNh72dgB5oX6tV57tFg,3015
396
+ haddock/modules/refinement/flexref/cns/cm-restraints.cns,sha256=31ZR8M-kl5i4VoJcihgMCZTxjwvla3yfi7gWXYgUSJ4,5043
397
+ haddock/modules/refinement/flexref/cns/contactairs.cns,sha256=LtMZm33ScEAnNE1J5HE-iQ95R8CtpTTCne4F23w7moc,1426
398
+ haddock/modules/refinement/flexref/cns/covalions.cns,sha256=V5UzRQ7iWJPzu3eDxGAbHYX_9ao9eSIBycUo78Zsg5o,3912
399
+ haddock/modules/refinement/flexref/cns/def_solv_param.cns,sha256=hRyLXwbnm7zoCidi_Eeztq-NvBjSiWIJfxo9WXcRzPo,4071
400
+ haddock/modules/refinement/flexref/cns/dna-rna_restraints.cns,sha256=gkljYrv7AqP3x9ujcjQYVSmhH6vknqW0GKmqyCBH-SY,19764
401
+ haddock/modules/refinement/flexref/cns/flex_segment.cns,sha256=kMA5ImQM1njQQ3xTlT4VxqL2FZyIwUlFZ7zKJR0cycg,1243
402
+ haddock/modules/refinement/flexref/cns/flex_segment_back.cns,sha256=ZcURFVmlEIXHw96PSZ-GPmM_IyrCivG5A_8AKotuSQw,2320
403
+ haddock/modules/refinement/flexref/cns/flex_segment_side.cns,sha256=tOdJBjWTb-17NM0LCxKXLC9iNIareaEXHNAkrGfHq4c,2552
404
+ haddock/modules/refinement/flexref/cns/flexauto-neighbors.cns,sha256=TysMjn197bNZ1gPSty-f0341t5fHc-K-I4aEvfE2-DA,1934
405
+ haddock/modules/refinement/flexref/cns/flexref.cns,sha256=xscNwfyX-7gj5BA-4_qkx7rL-8pl8x1Xd7m4rMFNjN8,18672
406
+ haddock/modules/refinement/flexref/cns/numtrees.cns,sha256=vJ3TVqvRuGzRAnBK5r6FCFogOxIsbvbezyk1xzfO8mE,3281
407
+ haddock/modules/refinement/flexref/cns/print_coorheader.cns,sha256=AdRuACCZ5TIWwBPuSVXVvQhD6728rIUxhwtN4yiLWmw,12246
408
+ haddock/modules/refinement/flexref/cns/protein-ss-restraints-all.cns,sha256=Ng7k_RoSrORIj77EFUIPuQ5xLwqMkcTw8byDF6ets70,4239
409
+ haddock/modules/refinement/flexref/cns/protein-ss-restraints-alpha-beta.cns,sha256=v02vtd4tzMDvoLr9tQgAkiKah2yJGBUJ0ufO8-8r2IE,6002
410
+ haddock/modules/refinement/flexref/cns/protein-ss-restraints-alpha.cns,sha256=zp_fje9KlUkwrqN9C6RVoXtAo674GEj69AmAALuLz48,5163
411
+ haddock/modules/refinement/flexref/cns/random_rotations.cns,sha256=6XnCXDtAMmtkbvIolx8BctAKxz8lTMw79zRom_tJtVk,7800
412
+ haddock/modules/refinement/flexref/cns/read_data.cns,sha256=5timDjMPd5_cTA8djQjuLxoIBBhOAwefdlFOj-BE6ms,2026
413
+ haddock/modules/refinement/flexref/cns/read_noes.cns,sha256=nLADAFcVjbJ-WN8Zza5mgYZFkvZNldL9feUidQRVN1I,1817
414
+ haddock/modules/refinement/flexref/cns/read_param.cns,sha256=Dm_oGn9aIJILPsFIa1RvAp21w5AeekXLxJLdh7u9BXY,2021
415
+ haddock/modules/refinement/flexref/cns/restrain-ions.cns,sha256=gb6AqflQscIatvKUSXno6wO6G2-kbncNNwaId2b5J7U,5237
416
+ haddock/modules/refinement/flexref/cns/sa_ltad_cool1.cns,sha256=_WhHrttAUlWUHG4KSESfRIPkcvAxm7CpZm9COAhzW0A,3809
417
+ haddock/modules/refinement/flexref/cns/sa_ltad_cool2.cns,sha256=HPNvgZ7n0zHjPz84fzJIIeyzL_VelU8_9SoAVoPjIE0,3868
418
+ haddock/modules/refinement/flexref/cns/sa_ltad_cool3.cns,sha256=n35MVRjpa0lKSHtFc-KK9PbCXOr6tdS5GWrFCqr9hJ0,3867
419
+ haddock/modules/refinement/flexref/cns/sa_ltad_hightemp.cns,sha256=9kR5ji8ehi4eIafTgh8U8FnnNsuauU02dodZOlxEXGM,1818
420
+ haddock/modules/refinement/flexref/cns/scale_inter.cns,sha256=mKIJ7R65tB9DuqAMCOfADPW2vZY5aFnFvo-Xkxjxy_w,2349
421
+ haddock/modules/refinement/flexref/cns/scale_inter_final.cns,sha256=WPncZ_1Rp757GyOZL9YFp0ONAfpIzV7WW6Lvrhy4LNQ,1836
422
+ haddock/modules/refinement/flexref/cns/scale_inter_only.cns,sha256=MfJwiYsd8Vn8R-Qbaiq02maAI6E89yC-Fg07E3rS2D8,2071
423
+ haddock/modules/refinement/flexref/cns/scale_intra_only.cns,sha256=BIA9k5ETYoSswYiZXTnVaE5g6N7k0TTIhhG-Amot3Q8,1489
424
+ haddock/modules/refinement/flexref/cns/separate.cns,sha256=s_mqxZNmhRNe94BTIsf9XiI_hI_JAbgI17KKn3aqcp8,9324
425
+ haddock/modules/refinement/flexref/cns/setflags.cns,sha256=gllgQGuPPqtCHymIfuGIzvS8MglQzAcPzZRNFR6O9zI,850
426
+ haddock/modules/refinement/flexref/cns/symmultimer.cns,sha256=v-RvMEcmhxmwJgetDufqr2OHO9JTOaHIU1cm_vshTf8,32233
427
+ haddock/modules/refinement/flexref/cns/torsiontop.cns,sha256=5GivVQJOpUV6eFqYY_CMK_yEqDMQp4bLT7tHQQwFOs4,4595
428
+ haddock/modules/refinement/flexref/defaults.yaml,sha256=llNeXA7UC1Qj3seiQaRxoQViba9m8jLxIE6VUh6_NFc,183524
429
+ haddock/modules/refinement/mdref/__init__.py,sha256=y3mrMhmeT0ctA0ThZksvsOp1-9F2ix1u5Wh5YBtmg1g,5661
430
+ haddock/modules/refinement/mdref/__pycache__/__init__.cpython-312.pyc,,
431
+ haddock/modules/refinement/mdref/cns/calc_free-ene.cns,sha256=oiXJjYSnG23nizBMv1D6YbeI-c4kDdQahRsuq0rn2w0,1116
432
+ haddock/modules/refinement/mdref/cns/check_coordinates.cns,sha256=diLUZz3XxMMb1towOaeWlGRiSNh72dgB5oX6tV57tFg,3015
433
+ haddock/modules/refinement/mdref/cns/cm-restraints.cns,sha256=XqI2yLh8WagcEeY3VAObuUPrdgAeVvyGv4r-udFDfH0,5511
434
+ haddock/modules/refinement/mdref/cns/contactairs.cns,sha256=LtMZm33ScEAnNE1J5HE-iQ95R8CtpTTCne4F23w7moc,1426
435
+ haddock/modules/refinement/mdref/cns/def_solv_param.cns,sha256=hRyLXwbnm7zoCidi_Eeztq-NvBjSiWIJfxo9WXcRzPo,4071
436
+ haddock/modules/refinement/mdref/cns/dna-rna_restraints.cns,sha256=gkljYrv7AqP3x9ujcjQYVSmhH6vknqW0GKmqyCBH-SY,19764
437
+ haddock/modules/refinement/mdref/cns/flex_segment_back.cns,sha256=iysr0Gz16kj1IxvPDCA7VkW1rAmZv_qHoJIn1INCFGk,2263
438
+ haddock/modules/refinement/mdref/cns/flex_segment_side.cns,sha256=LLv1xUQO-n5z7fSHb9fs5ro-Bj8JsVLHzlbSTBxwr3c,1906
439
+ haddock/modules/refinement/mdref/cns/flexauto-neighbors.cns,sha256=TysMjn197bNZ1gPSty-f0341t5fHc-K-I4aEvfE2-DA,1934
440
+ haddock/modules/refinement/mdref/cns/generate_dmso.cns,sha256=-wuKZONhjDS-EjnsLQmcuLzf6mjWTqs_HUBzPw6r49Y,5433
441
+ haddock/modules/refinement/mdref/cns/generate_water.cns,sha256=GO6nyT7pXZtHKBE8mh9MT8q8dbntQxHEXMxeB_Eo3I0,5792
442
+ haddock/modules/refinement/mdref/cns/mdref.cns,sha256=ryxfLCB2SLWSdnt2DZgS2Fxil0sU4J2v9bT8leJubTY,16910
443
+ haddock/modules/refinement/mdref/cns/print_coorheader.cns,sha256=AdRuACCZ5TIWwBPuSVXVvQhD6728rIUxhwtN4yiLWmw,12246
444
+ haddock/modules/refinement/mdref/cns/protein-ss-restraints-all.cns,sha256=Ng7k_RoSrORIj77EFUIPuQ5xLwqMkcTw8byDF6ets70,4239
445
+ haddock/modules/refinement/mdref/cns/protein-ss-restraints-alpha-beta.cns,sha256=v02vtd4tzMDvoLr9tQgAkiKah2yJGBUJ0ufO8-8r2IE,6002
446
+ haddock/modules/refinement/mdref/cns/protein-ss-restraints-alpha.cns,sha256=zp_fje9KlUkwrqN9C6RVoXtAo674GEj69AmAALuLz48,5163
447
+ haddock/modules/refinement/mdref/cns/read_data.cns,sha256=5timDjMPd5_cTA8djQjuLxoIBBhOAwefdlFOj-BE6ms,2026
448
+ haddock/modules/refinement/mdref/cns/read_noes.cns,sha256=nLADAFcVjbJ-WN8Zza5mgYZFkvZNldL9feUidQRVN1I,1817
449
+ haddock/modules/refinement/mdref/cns/read_param.cns,sha256=Dm_oGn9aIJILPsFIa1RvAp21w5AeekXLxJLdh7u9BXY,2021
450
+ haddock/modules/refinement/mdref/cns/restrain-ions.cns,sha256=QktROUdVSPaRC4ckEWjAsy0lY9sUZ6Rp1-2iDGfl3y4,5213
451
+ haddock/modules/refinement/mdref/cns/scale_inter.cns,sha256=mKIJ7R65tB9DuqAMCOfADPW2vZY5aFnFvo-Xkxjxy_w,2349
452
+ haddock/modules/refinement/mdref/cns/scale_inter_final.cns,sha256=WPncZ_1Rp757GyOZL9YFp0ONAfpIzV7WW6Lvrhy4LNQ,1836
453
+ haddock/modules/refinement/mdref/cns/scale_intra_only.cns,sha256=BIA9k5ETYoSswYiZXTnVaE5g6N7k0TTIhhG-Amot3Q8,1489
454
+ haddock/modules/refinement/mdref/cns/setflags.cns,sha256=BWCTCEU-7i6rDsArjZ_EWJd6pe-sj275phmD9EJs0Es,771
455
+ haddock/modules/refinement/mdref/cns/symmultimer.cns,sha256=v-RvMEcmhxmwJgetDufqr2OHO9JTOaHIU1cm_vshTf8,32233
456
+ haddock/modules/refinement/mdref/defaults.yaml,sha256=rfrSOsbTcZszZesA-Y_KEzPIBCanm89SBcosDhZB68Y,166304
457
+ haddock/modules/refinement/openmm/__init__.py,sha256=XGNlzJZmG5aG2YMasSen-5FwxNu-P7dHq5beV5yUmTs,6152
458
+ haddock/modules/refinement/openmm/__pycache__/__init__.cpython-312.pyc,,
459
+ haddock/modules/refinement/openmm/__pycache__/openmm.cpython-312.pyc,,
460
+ haddock/modules/refinement/openmm/defaults.yaml,sha256=_MVC_1YAGiy3O8UzBb4lEyRrDiAOu-Iwv1aa14KEyO4,9080
461
+ haddock/modules/refinement/openmm/openmm.py,sha256=ojd8N6fQ0Uqjfr4jy2svBSRmXqR-aLfirDDTRZgRD1A,37361
462
+ haddock/modules/sampling/__init__.py,sha256=IzSJ1tIiCpDEi6ItmP_kq_kpYG3--qR27oTGO--3njI,37
463
+ haddock/modules/sampling/__pycache__/__init__.cpython-312.pyc,,
464
+ haddock/modules/sampling/lightdock/__init__.py,sha256=YsnXGhgkqwuaQ0r0pt0QMN4uZtDVfvuFLEmiXxMgpfA,5819
465
+ haddock/modules/sampling/lightdock/__pycache__/__init__.cpython-312.pyc,,
466
+ haddock/modules/sampling/lightdock/defaults.yaml,sha256=cbXG0qE_WUaKvwOU3rxtDhcIbjmCBXbm9BFMHLVV3B0,2671
467
+ haddock/modules/sampling/rigidbody/__init__.py,sha256=bjKEyHC_vmH9DpEnwnF7GlFxDipEGLO0tohR4irqW74,10714
468
+ haddock/modules/sampling/rigidbody/__pycache__/__init__.cpython-312.pyc,,
469
+ haddock/modules/sampling/rigidbody/cns/bestener.cns,sha256=EW2EJ1eMhKx6BgLc2K1DURHIkajYcQYuXy4Td09XnXw,3055
470
+ haddock/modules/sampling/rigidbody/cns/bsa.cns,sha256=BGhJFQpEHo_tpsWu1qqk4H4-TGyr27m2r49F5ajWUsc,2493
471
+ haddock/modules/sampling/rigidbody/cns/charge-beads-interactions.cns,sha256=YZO2HosC75DLThsSaCBcejZHyit5pjiioT6XkcE8d9k,1755
472
+ haddock/modules/sampling/rigidbody/cns/check-homomers.cns,sha256=t0rPTSXU44EPwZ-Q6Av73QyEXjaYvjzAHXm7FGIQZms,1736
473
+ haddock/modules/sampling/rigidbody/cns/check_coordinates.cns,sha256=diLUZz3XxMMb1towOaeWlGRiSNh72dgB5oX6tV57tFg,3015
474
+ haddock/modules/sampling/rigidbody/cns/cm-restraints.cns,sha256=31ZR8M-kl5i4VoJcihgMCZTxjwvla3yfi7gWXYgUSJ4,5043
475
+ haddock/modules/sampling/rigidbody/cns/def_solv_param.cns,sha256=hRyLXwbnm7zoCidi_Eeztq-NvBjSiWIJfxo9WXcRzPo,4071
476
+ haddock/modules/sampling/rigidbody/cns/get_random_rotation.cns,sha256=5zHg-lEkWBE_8Zrrv9RqBzo60avmXPmO_yC6TScaOq8,3875
477
+ haddock/modules/sampling/rigidbody/cns/print_coorheader.cns,sha256=AdRuACCZ5TIWwBPuSVXVvQhD6728rIUxhwtN4yiLWmw,12246
478
+ haddock/modules/sampling/rigidbody/cns/random_rotations.cns,sha256=6XnCXDtAMmtkbvIolx8BctAKxz8lTMw79zRom_tJtVk,7800
479
+ haddock/modules/sampling/rigidbody/cns/randomairs.cns,sha256=Bv5TjtwCQMwwDLRHoNc8bQNH-KxCwkPyzQGQRPnTIaw,8970
480
+ haddock/modules/sampling/rigidbody/cns/read_noes.cns,sha256=nLADAFcVjbJ-WN8Zza5mgYZFkvZNldL9feUidQRVN1I,1817
481
+ haddock/modules/sampling/rigidbody/cns/read_param.cns,sha256=Dm_oGn9aIJILPsFIa1RvAp21w5AeekXLxJLdh7u9BXY,2021
482
+ haddock/modules/sampling/rigidbody/cns/rigidbody.cns,sha256=VuZv32U8XiI3KPz5SZCVW2t8ncmn2tHR-UrTFkxjUSo,18700
483
+ haddock/modules/sampling/rigidbody/cns/rotation180.cns,sha256=J0UXXhjj67-hKInI54n8y3Qlt8GeOT1k5VaTPLp6M-s,2749
484
+ haddock/modules/sampling/rigidbody/cns/scale_inter_final.cns,sha256=WPncZ_1Rp757GyOZL9YFp0ONAfpIzV7WW6Lvrhy4LNQ,1836
485
+ haddock/modules/sampling/rigidbody/cns/scale_inter_mini.cns,sha256=QwfEU3fBxBqTOeB5BDUbRfa9FrGvifnraUVFLRIvfCw,1711
486
+ haddock/modules/sampling/rigidbody/cns/scale_inter_only.cns,sha256=MfJwiYsd8Vn8R-Qbaiq02maAI6E89yC-Fg07E3rS2D8,2071
487
+ haddock/modules/sampling/rigidbody/cns/scale_intra_only.cns,sha256=BIA9k5ETYoSswYiZXTnVaE5g6N7k0TTIhhG-Amot3Q8,1489
488
+ haddock/modules/sampling/rigidbody/cns/separate.cns,sha256=s_mqxZNmhRNe94BTIsf9XiI_hI_JAbgI17KKn3aqcp8,9324
489
+ haddock/modules/sampling/rigidbody/cns/surf-restraints.cns,sha256=Xsh9rKXeB4bEELsGQ_06xYCLGAGYD1kjh1h8MmXRPNU,2722
490
+ haddock/modules/sampling/rigidbody/cns/symmultimer.cns,sha256=v-RvMEcmhxmwJgetDufqr2OHO9JTOaHIU1cm_vshTf8,32233
491
+ haddock/modules/sampling/rigidbody/defaults.yaml,sha256=PClF41pu2WYClCm0mNXMEGwC2XdP6i_c31Msk-1BQ9o,156404
492
+ haddock/modules/scoring/__init__.py,sha256=uZKaVaMaDApf0Yng0biAeXWhV4AYYngjl5abZRbPdfA,12816
493
+ haddock/modules/scoring/__pycache__/__init__.cpython-312.pyc,,
494
+ haddock/modules/scoring/emscoring/__init__.py,sha256=C6A1vSY-udbKWiws11aVKPxA0elBb54yt7jDOC61vTs,3627
495
+ haddock/modules/scoring/emscoring/__pycache__/__init__.cpython-312.pyc,,
496
+ haddock/modules/scoring/emscoring/cns/calc_free-ene.cns,sha256=ImZyyS30ThEOJ9y_B1QLOs7AJALMJ5yH699RmGN4XZE,962
497
+ haddock/modules/scoring/emscoring/cns/check_coordinates.cns,sha256=diLUZz3XxMMb1towOaeWlGRiSNh72dgB5oX6tV57tFg,3015
498
+ haddock/modules/scoring/emscoring/cns/def_solv_param.cns,sha256=hRyLXwbnm7zoCidi_Eeztq-NvBjSiWIJfxo9WXcRzPo,4071
499
+ haddock/modules/scoring/emscoring/cns/emscoring.cns,sha256=8pHOygMxS8NAoRVlruXegYIupQ9FmAtSMKASOHXgWfQ,6388
500
+ haddock/modules/scoring/emscoring/cns/print_coorheader.cns,sha256=unXp0Ufe6_RvB10xqlZjPADQI2TYafGux8ujPAHdD6c,17115
501
+ haddock/modules/scoring/emscoring/cns/read_param.cns,sha256=Dm_oGn9aIJILPsFIa1RvAp21w5AeekXLxJLdh7u9BXY,2021
502
+ haddock/modules/scoring/emscoring/cns/restrain-ions.cns,sha256=gb6AqflQscIatvKUSXno6wO6G2-kbncNNwaId2b5J7U,5237
503
+ haddock/modules/scoring/emscoring/cns/scale_inter_final.cns,sha256=tV57zFF1vHt0texcYIsNqw5xyVRR8ft6ahIPuaGnx2k,1801
504
+ haddock/modules/scoring/emscoring/cns/scale_intra_only.cns,sha256=BIA9k5ETYoSswYiZXTnVaE5g6N7k0TTIhhG-Amot3Q8,1489
505
+ haddock/modules/scoring/emscoring/defaults.yaml,sha256=9YAkIq5rLwdloKpcFP3aMv4e9qS3VMCRViL7WUXiJXw,10496
506
+ haddock/modules/scoring/mdscoring/__init__.py,sha256=C3HQP2U0BXJHvO_UbQiuV0oGAgCLkzwLsJdOUOPzZ80,3612
507
+ haddock/modules/scoring/mdscoring/__pycache__/__init__.cpython-312.pyc,,
508
+ haddock/modules/scoring/mdscoring/cns/calc_free-ene.cns,sha256=oiXJjYSnG23nizBMv1D6YbeI-c4kDdQahRsuq0rn2w0,1116
509
+ haddock/modules/scoring/mdscoring/cns/check_coordinates.cns,sha256=diLUZz3XxMMb1towOaeWlGRiSNh72dgB5oX6tV57tFg,3015
510
+ haddock/modules/scoring/mdscoring/cns/contactairs.cns,sha256=LtMZm33ScEAnNE1J5HE-iQ95R8CtpTTCne4F23w7moc,1426
511
+ haddock/modules/scoring/mdscoring/cns/def_solv_param.cns,sha256=hRyLXwbnm7zoCidi_Eeztq-NvBjSiWIJfxo9WXcRzPo,4071
512
+ haddock/modules/scoring/mdscoring/cns/dna-rna_restraints.cns,sha256=gkljYrv7AqP3x9ujcjQYVSmhH6vknqW0GKmqyCBH-SY,19764
513
+ haddock/modules/scoring/mdscoring/cns/flex_segment_back.cns,sha256=xOirchd_aVDHcOrViWbUwJyA3otme_U5tvdWUQXj-PI,1031
514
+ haddock/modules/scoring/mdscoring/cns/flex_segment_side.cns,sha256=40dJPmGgkOUzw8cNZ-iGdgKA40Thj-TjAffGD28Fhxs,1101
515
+ haddock/modules/scoring/mdscoring/cns/flexauto-neighbors.cns,sha256=lk3g471rwmcySIEIhQVrYWzN0jd1rWQxBiybwBuoxp8,2141
516
+ haddock/modules/scoring/mdscoring/cns/generate_dmso.cns,sha256=-wuKZONhjDS-EjnsLQmcuLzf6mjWTqs_HUBzPw6r49Y,5433
517
+ haddock/modules/scoring/mdscoring/cns/generate_water.cns,sha256=GO6nyT7pXZtHKBE8mh9MT8q8dbntQxHEXMxeB_Eo3I0,5792
518
+ haddock/modules/scoring/mdscoring/cns/mdscoring.cns,sha256=llZxBUqZHBULj75RdxiGlxDJabfuAPEI3kn-cXeEwdw,12973
519
+ haddock/modules/scoring/mdscoring/cns/print_coorheader.cns,sha256=unXp0Ufe6_RvB10xqlZjPADQI2TYafGux8ujPAHdD6c,17115
520
+ haddock/modules/scoring/mdscoring/cns/protein-ss-restraints-all.cns,sha256=Ng7k_RoSrORIj77EFUIPuQ5xLwqMkcTw8byDF6ets70,4239
521
+ haddock/modules/scoring/mdscoring/cns/protein-ss-restraints-alpha-beta.cns,sha256=v02vtd4tzMDvoLr9tQgAkiKah2yJGBUJ0ufO8-8r2IE,6002
522
+ haddock/modules/scoring/mdscoring/cns/protein-ss-restraints-alpha.cns,sha256=zp_fje9KlUkwrqN9C6RVoXtAo674GEj69AmAALuLz48,5163
523
+ haddock/modules/scoring/mdscoring/cns/read_param.cns,sha256=Dm_oGn9aIJILPsFIa1RvAp21w5AeekXLxJLdh7u9BXY,2021
524
+ haddock/modules/scoring/mdscoring/cns/restrain-ions.cns,sha256=gb6AqflQscIatvKUSXno6wO6G2-kbncNNwaId2b5J7U,5237
525
+ haddock/modules/scoring/mdscoring/cns/scale_inter_final.cns,sha256=tV57zFF1vHt0texcYIsNqw5xyVRR8ft6ahIPuaGnx2k,1801
526
+ haddock/modules/scoring/mdscoring/cns/scale_intra_only.cns,sha256=BIA9k5ETYoSswYiZXTnVaE5g6N7k0TTIhhG-Amot3Q8,1489
527
+ haddock/modules/scoring/mdscoring/cns/setflags.cns,sha256=BWCTCEU-7i6rDsArjZ_EWJd6pe-sj275phmD9EJs0Es,771
528
+ haddock/modules/scoring/mdscoring/defaults.yaml,sha256=roDENFSMB2X38YHsAZQIgSCO22GNNzFcy9TWCXIL-mg,15687
529
+ haddock/modules/scoring/prodigyligand/__init__.py,sha256=C_hWOypd2yMxT5Iawfbu0DxtADDmPI50laVJV_QgSAQ,3030
530
+ haddock/modules/scoring/prodigyligand/__pycache__/__init__.cpython-312.pyc,,
531
+ haddock/modules/scoring/prodigyligand/__pycache__/prodigylig.cpython-312.pyc,,
532
+ haddock/modules/scoring/prodigyligand/defaults.yaml,sha256=9OcxMUB6J3a3dq03A3u59oTDGE1ZlE8AodRzYeq0KEg,2285
533
+ haddock/modules/scoring/prodigyligand/prodigylig.py,sha256=XVFFJ9G4M8iXOc76aOIiwdYsQscVD6ViG1fBFJFJfrc,2805
534
+ haddock/modules/scoring/prodigyprotein/__init__.py,sha256=XvGR90BHRp55RkswI_QJmZgRYwEcDzHHay89Tg1lv_4,3103
535
+ haddock/modules/scoring/prodigyprotein/__pycache__/__init__.cpython-312.pyc,,
536
+ haddock/modules/scoring/prodigyprotein/__pycache__/prodigy.cpython-312.pyc,,
537
+ haddock/modules/scoring/prodigyprotein/defaults.yaml,sha256=VKzgmWkYJYTYfBTfvyVVVv0cCDUUQzk2RPlsYWuVbbc,2287
538
+ haddock/modules/scoring/prodigyprotein/prodigy.py,sha256=xnnOwKNpa0GeeykptAmm2l5D_WMuu_O-bO6mnEEcdPc,2506
539
+ haddock/modules/scoring/sasascore/__init__.py,sha256=E35Jf30jzFjB2B0Q25U_aTkRBCCSYnbP_i4bMq9_FNk,4283
540
+ haddock/modules/scoring/sasascore/__pycache__/__init__.cpython-312.pyc,,
541
+ haddock/modules/scoring/sasascore/__pycache__/sasascore.cpython-312.pyc,,
542
+ haddock/modules/scoring/sasascore/defaults.yaml,sha256=QPYj269Cz4wzl3QavYeAEacII8xE5Dfxst2O9X2zpOo,1457
543
+ haddock/modules/scoring/sasascore/sasascore.py,sha256=nULoqFPCs7EGMGITTqmAtfgA7UnvoWOHz07QsXZ2nic,5478
544
+ haddock/modules/topology/__init__.py,sha256=T1QD23IIPMdLplN1AE8fH6ayk5x1ClewgCI9jtgkycs,45
545
+ haddock/modules/topology/__pycache__/__init__.cpython-312.pyc,,
546
+ haddock/modules/topology/topoaa/__init__.py,sha256=AK5LuSH-iYkpEqYvnYf9aDgQ9ikXrX4Iq3uLIuykVmM,15344
547
+ haddock/modules/topology/topoaa/__pycache__/__init__.cpython-312.pyc,,
548
+ haddock/modules/topology/topoaa/cns/auto-his.cns,sha256=sdzqMBcvQHMB1tMtbkQ_ZKOmWopZtVvm0pNqOKKIJdY,4999
549
+ haddock/modules/topology/topoaa/cns/bondglycans.cns,sha256=HeUkl-Nn188E6FBkSgtlBXDrvKro99IXTUp5TNJZvCU,22854
550
+ haddock/modules/topology/topoaa/cns/build-missing.cns,sha256=Z1il-I46XEAqkpfue8buc_R7rgRCyUUlKqqLILxeLK4,8912
551
+ haddock/modules/topology/topoaa/cns/check_coordinates.cns,sha256=diLUZz3XxMMb1towOaeWlGRiSNh72dgB5oX6tV57tFg,3015
552
+ haddock/modules/topology/topoaa/cns/coval-ace-cys.cns,sha256=ZOZmDA0wDRulagAhy2EQzEGV0OlPPULJAy-omC9-z6M,2015
553
+ haddock/modules/topology/topoaa/cns/covalheme.cns,sha256=PtPpIoTBFFUYeg5-mQ4s08V57SevYFE8jg4FFiTYB_M,3768
554
+ haddock/modules/topology/topoaa/cns/dna_break.cns,sha256=YBfMhmQVIFg_bZR7IFp6KyCF0ubhBoQ3JSXW-87shFE,2738
555
+ haddock/modules/topology/topoaa/cns/generate-topology.cns,sha256=MXOt00CBq_I2z8P_50waJCcjcWaVQUYXxEWs8I9MeAU,23545
556
+ haddock/modules/topology/topoaa/cns/patch-bb-cg.cns,sha256=OVxefdcaYAcogj7dLcnWDmS6LHT38ri2wAIeMi7M5z8,8026
557
+ haddock/modules/topology/topoaa/cns/patch-types-cg.cns,sha256=T2hHsV-mTrX0BVQMLDmHubg-XVw-PHuuW2Kq4MNUNWY,2963
558
+ haddock/modules/topology/topoaa/cns/prot_break.cns,sha256=DZyq8yDD3yfnL0gfWGCYv6hEMNcJ9tcrZV34V-2Mbdc,4843
559
+ haddock/modules/topology/topoaa/defaults.yaml,sha256=GrnJC1BWbynRHEkWKojY_v4wrGS1VELd6PObqSUVZNU,8404
560
+ haddock/prodrg/prodrg.param,sha256=5SPxuZsoiKP8DM6R7yaQXg4c8XcdJmS-JjIZ7nuU74I,81989
561
+ haddock/prodrg/prodrg_aarch64-linux,sha256=RgYnIbN2U8t7TOK-6jJ3OeLKNU3KeIaGy_mly12hzoU,1919656
562
+ haddock/prodrg/prodrg_arm64-darwin,sha256=UxDP5bmf2skSx2E49sq3Es0ScKP0_j8_ZJJ42Wa5h_0,737144
563
+ haddock/prodrg/prodrg_x86_64-linux,sha256=d3oqH1qyjD1aS8sKRCzZpKu1_hgBGWacSOlvoLIK6V0,1904548
564
+ haddock3-2026.3.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
565
+ haddock3-2026.3.0.dist-info/METADATA,sha256=QkWpLD2srYCZRXSuvqOXwwx9XWegsFyoXW6bN-cuRb0,10659
566
+ haddock3-2026.3.0.dist-info/RECORD,,
567
+ haddock3-2026.3.0.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
568
+ haddock3-2026.3.0.dist-info/WHEEL,sha256=VjsRi47qtukBUrbjxzUfbq_AtWwISMuQJEz01zs7bcg,109
569
+ haddock3-2026.3.0.dist-info/entry_points.txt,sha256=aT3o4F0PoYHex4eotd2i65SKvHu9co9u6kkrVTG8ViY,696
570
+ haddock3-2026.3.0.dist-info/licenses/LICENSE,sha256=xx0jnfkXJvxRnG63LTGOxlggYnIysveWIZ6H3PNdCrQ,11357
571
+ haddock3-2026.3.0.dist-info/top_level.txt,sha256=26Fn1sNxrDBEuot8BU3pVoHZ-U-diSijnSp_gcVwNUs,8
.venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/REQUESTED ADDED
File without changes
.venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp312-cp312-macosx_11_0_arm64
5
+
.venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/entry_points.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [console_scripts]
2
+ haddock-restraints = haddock.clis.wrapper_haddock_restraints:main
3
+ haddock3 = haddock.clis.cli:maincli
4
+ haddock3-analyse = haddock.clis.cli_analyse:maincli
5
+ haddock3-cfg = haddock.clis.cli_cfg:maincli
6
+ haddock3-clean = haddock.clis.cli_clean:maincli
7
+ haddock3-copy = haddock.clis.cli_cp:maincli
8
+ haddock3-dmn = haddock.clis.cli_dmn:maincli
9
+ haddock3-mpitask = haddock.clis.cli_mpi:maincli
10
+ haddock3-pp = haddock.clis.cli_pp:maincli
11
+ haddock3-re = haddock.clis.cli_re:maincli
12
+ haddock3-restraints = haddock.clis.cli_restraints:maincli
13
+ haddock3-score = haddock.clis.cli_score:maincli
14
+ haddock3-traceback = haddock.clis.cli_traceback:maincli
15
+ haddock3-unpack = haddock.clis.cli_unpack:maincli
.venv_haddock/lib/python3.12/site-packages/haddock3-2026.3.0.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ haddock
.venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/METADATA ADDED
@@ -0,0 +1,232 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: jsonpickle
3
+ Version: 4.1.1
4
+ Summary: jsonpickle encodes/decodes any Python object to/from JSON
5
+ Author: Theelx
6
+ Author-email: David Aguilar <davvid+jsonpickle@gmail.com>
7
+ License: BSD-3-Clause
8
+ Project-URL: Documentation, https://jsonpickle.readthedocs.io/
9
+ Project-URL: Homepage, https://jsonpickle.readthedocs.io/
10
+ Project-URL: Source, https://github.com/jsonpickle/jsonpickle
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3 :: Only
15
+ Requires-Python: >=3.8
16
+ Description-Content-Type: text/x-rst
17
+ License-File: LICENSE
18
+ Provides-Extra: cov
19
+ Requires-Dist: pytest-cov; extra == "cov"
20
+ Provides-Extra: dev
21
+ Requires-Dist: black; extra == "dev"
22
+ Requires-Dist: pyupgrade; extra == "dev"
23
+ Provides-Extra: testing
24
+ Requires-Dist: pytest!=8.1.*,>=6.0; extra == "testing"
25
+ Requires-Dist: pytest-benchmark; extra == "testing"
26
+ Requires-Dist: pytest-benchmark[histogram]; extra == "testing"
27
+ Requires-Dist: pytest-checkdocs>=1.2.3; extra == "testing"
28
+ Requires-Dist: pytest-enabler>=1.0.1; extra == "testing"
29
+ Requires-Dist: pytest-ruff>=0.2.1; extra == "testing"
30
+ Requires-Dist: bson; extra == "testing"
31
+ Requires-Dist: ecdsa; extra == "testing"
32
+ Requires-Dist: feedparser; extra == "testing"
33
+ Requires-Dist: gmpy2; extra == "testing"
34
+ Requires-Dist: numpy; extra == "testing"
35
+ Requires-Dist: pandas; extra == "testing"
36
+ Requires-Dist: pymongo; extra == "testing"
37
+ Requires-Dist: PyYAML; extra == "testing"
38
+ Requires-Dist: scikit-learn; extra == "testing"
39
+ Requires-Dist: scipy>=1.9.3; python_version > "3.10" and extra == "testing"
40
+ Requires-Dist: scipy; python_version <= "3.10" and extra == "testing"
41
+ Requires-Dist: simplejson; extra == "testing"
42
+ Requires-Dist: sqlalchemy; extra == "testing"
43
+ Requires-Dist: ujson; extra == "testing"
44
+ Requires-Dist: atheris~=2.3.0; python_version < "3.12" and extra == "testing"
45
+ Provides-Extra: docs
46
+ Requires-Dist: furo; extra == "docs"
47
+ Requires-Dist: rst.linker>=1.9; extra == "docs"
48
+ Requires-Dist: sphinx>=3.5; extra == "docs"
49
+ Provides-Extra: packaging
50
+ Requires-Dist: build; extra == "packaging"
51
+ Requires-Dist: setuptools>=61.2; extra == "packaging"
52
+ Requires-Dist: setuptools_scm[toml]>=6.0; extra == "packaging"
53
+ Requires-Dist: twine; extra == "packaging"
54
+ Dynamic: license-file
55
+
56
+ .. image:: https://img.shields.io/pypi/v/jsonpickle.svg
57
+ :target: `PyPI link`_
58
+
59
+ .. image:: https://img.shields.io/pypi/pyversions/jsonpickle.svg
60
+ :target: `PyPI link`_
61
+
62
+ .. _PyPI link: https://pypi.org/project/jsonpickle
63
+
64
+ .. image:: https://readthedocs.org/projects/jsonpickle/badge/?version=latest
65
+ :target: https://jsonpickle.readthedocs.io/en/latest/?badge=latest
66
+
67
+ .. image:: https://github.com/jsonpickle/jsonpickle/actions/workflows/test.yml/badge.svg
68
+ :target: https://github.com/jsonpickle/jsonpickle/actions
69
+ :alt: Github Actions
70
+
71
+ .. image:: https://img.shields.io/badge/License-BSD%203--Clause-blue.svg
72
+ :target: https://github.com/jsonpickle/jsonpickle/blob/main/LICENSE
73
+ :alt: BSD
74
+
75
+
76
+ jsonpickle
77
+ ==========
78
+
79
+ jsonpickle is a library for the two-way conversion of complex Python objects
80
+ and `JSON <http://json.org/>`_. jsonpickle builds upon existing JSON
81
+ encoders, such as simplejson, json, and ujson.
82
+
83
+ .. warning::
84
+
85
+ jsonpickle can execute arbitrary Python code.
86
+
87
+ Please see the Security section for more details.
88
+
89
+
90
+ For complete documentation, please visit the
91
+ `jsonpickle documentation <http://jsonpickle.readthedocs.io/>`_.
92
+
93
+ Bug reports and merge requests are encouraged at the
94
+ `jsonpickle repository on github <https://github.com/jsonpickle/jsonpickle>`_.
95
+
96
+ Usage
97
+ =====
98
+ The following is a very simple example of how one can use jsonpickle in their scripts/projects. Note the usage of jsonpickle.encode and decode, and how the data is written/encoded to a file and then read/decoded from the file.
99
+
100
+ .. code-block:: python
101
+
102
+ import jsonpickle
103
+ from dataclasses import dataclass
104
+
105
+ @dataclass
106
+ class Example:
107
+ data: str
108
+
109
+
110
+ ex = Example("value1")
111
+ encoded_instance = jsonpickle.encode(ex)
112
+ assert encoded_instance == '{"py/object": "__main__.Example", "data": "value1"}'
113
+
114
+ with open("example.json", "w+") as f:
115
+ f.write(encoded_instance)
116
+
117
+ with open("example.json", "r+") as f:
118
+ written_instance = f.read()
119
+ decoded_instance = jsonpickle.decode(written_instance)
120
+ assert decoded_instance == ex
121
+
122
+ For more examples, see the `examples directory on GitHub <https://github.com/jsonpickle/jsonpickle/tree/main/examples>`_ for example scripts. These can be run on your local machine to see how jsonpickle works and behaves, and how to use it. Contributions from users regarding how they use jsonpickle are welcome!
123
+
124
+
125
+ Why jsonpickle?
126
+ ===============
127
+
128
+ Data serialized with python's pickle (or cPickle or dill) is not easily readable outside of python. Using the json format, jsonpickle allows simple data types to be stored in a human-readable format, and more complex data types such as numpy arrays and pandas dataframes, to be machine-readable on any platform that supports json. E.g., unlike pickled data, jsonpickled data stored in an Amazon S3 bucket is indexible by Amazon's Athena.
129
+
130
+ Security
131
+ ========
132
+
133
+ jsonpickle should be treated the same as the
134
+ `Python stdlib pickle module <https://docs.python.org/3/library/pickle.html>`_
135
+ from a security perspective.
136
+
137
+ .. warning::
138
+
139
+ The jsonpickle module **is not secure**. Only unpickle data you trust.
140
+
141
+ It is possible to construct malicious pickle data which will **execute
142
+ arbitrary code during unpickling**. Never unpickle data that could have come
143
+ from an untrusted source, or that could have been tampered with.
144
+
145
+ Consider signing data with an HMAC if you need to ensure that it has not
146
+ been tampered with.
147
+
148
+ Safer deserialization approaches, such as reading JSON directly,
149
+ may be more appropriate if you are processing untrusted data.
150
+
151
+
152
+ Install
153
+ =======
154
+
155
+ Install from pip for the latest stable release:
156
+
157
+ ::
158
+
159
+ pip install jsonpickle
160
+
161
+ Install from github for the latest changes:
162
+
163
+ ::
164
+
165
+ pip install git+https://github.com/jsonpickle/jsonpickle.git
166
+
167
+
168
+ Numpy/Pandas Support
169
+ ====================
170
+
171
+ jsonpickle includes built-in numpy and pandas extensions. If you would
172
+ like to encode sklearn models, numpy arrays, pandas DataFrames, and other
173
+ numpy/pandas-based data, then you must enable the numpy and/or pandas
174
+ extensions by registering their handlers::
175
+
176
+ >>> import jsonpickle.ext.numpy as jsonpickle_numpy
177
+ >>> import jsonpickle.ext.pandas as jsonpickle_pandas
178
+ >>> jsonpickle_numpy.register_handlers()
179
+ >>> jsonpickle_pandas.register_handlers()
180
+
181
+
182
+ Development
183
+ ===========
184
+
185
+ Use `make` to run the unit tests::
186
+
187
+ make test
188
+
189
+ `pytest` is used to run unit tests internally.
190
+
191
+ A `tox` target is provided to run tests using all installed and supported Python versions::
192
+
193
+ make tox
194
+
195
+ `jsonpickle` itself has no dependencies beyond the Python stdlib.
196
+ `tox` is required for testing when using the `tox` test runner only.
197
+
198
+ The testing requirements are specified in `setup.cfg`.
199
+ It is recommended to create a virtualenv and run tests from within the
200
+ virtualenv.::
201
+
202
+ python3 -mvenv env3
203
+ source env3/bin/activate
204
+ pip install --editable '.[dev]'
205
+ make test
206
+
207
+ You can also use a tool such as `vx <https://github.com/davvid/vx/>`_
208
+ to activate the virtualenv without polluting your shell environment::
209
+
210
+ python3 -mvenv env3
211
+ vx env3 pip install --editable '.[dev]'
212
+ vx env3 make test
213
+
214
+ If you can't use a venv, you can install the testing packages as follows::
215
+
216
+ pip install .[testing]
217
+
218
+ `jsonpickle` supports multiple Python versions, so using a combination of
219
+ multiple virtualenvs and `tox` is useful in order to catch compatibility
220
+ issues when developing.
221
+
222
+ GPG Signing
223
+ ===========
224
+
225
+ Unfortunately, while versions of jsonpickle before 3.0.1 should still be signed,
226
+ GPG signing support was removed from PyPi
227
+ (https://blog.pypi.org/posts/2023-05-23-removing-pgp/) back in May 2023.
228
+
229
+ License
230
+ =======
231
+
232
+ Licensed under the BSD License. See the LICENSE file for more details.
.venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/RECORD ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ jsonpickle-4.1.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ jsonpickle-4.1.1.dist-info/METADATA,sha256=uj-M-_gfWF9DXSpxrv070t1RNM4HgGjGc-Hw3wZUmc8,8148
3
+ jsonpickle-4.1.1.dist-info/RECORD,,
4
+ jsonpickle-4.1.1.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
5
+ jsonpickle-4.1.1.dist-info/licenses/LICENSE,sha256=2k10Dnv-Hpd3uu2jz2U09Wjssquye4Dn4sL58oZNg50,1547
6
+ jsonpickle-4.1.1.dist-info/top_level.txt,sha256=cdRDYlLc4XOT2KzzPurieMn-XW_3YxFzopwdeDqPFVs,11
7
+ jsonpickle/__init__.py,sha256=Lfn7ceNeACvvkRQS48F_740_g5Xy7aTffuDvOyJ7z-M,3043
8
+ jsonpickle/__pycache__/__init__.cpython-312.pyc,,
9
+ jsonpickle/__pycache__/backend.cpython-312.pyc,,
10
+ jsonpickle/__pycache__/compat.cpython-312.pyc,,
11
+ jsonpickle/__pycache__/errors.cpython-312.pyc,,
12
+ jsonpickle/__pycache__/handlers.cpython-312.pyc,,
13
+ jsonpickle/__pycache__/pickler.cpython-312.pyc,,
14
+ jsonpickle/__pycache__/tags.cpython-312.pyc,,
15
+ jsonpickle/__pycache__/tags_pd.cpython-312.pyc,,
16
+ jsonpickle/__pycache__/unpickler.cpython-312.pyc,,
17
+ jsonpickle/__pycache__/util.cpython-312.pyc,,
18
+ jsonpickle/__pycache__/version.cpython-312.pyc,,
19
+ jsonpickle/backend.py,sha256=0BImUq61LMYih-8510hNPQvtCgfNjIHGOTKuApzkyWg,9993
20
+ jsonpickle/compat.py,sha256=jCIhbLad7wMstxeEOykPh-lRvM3fIkwITmHi0Rbi5PM,378
21
+ jsonpickle/errors.py,sha256=lzadGFLtErTPH0CzAwxS2gbd61lqoOJE4f2_TSDa3WU,132
22
+ jsonpickle/ext/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
23
+ jsonpickle/ext/__pycache__/__init__.cpython-312.pyc,,
24
+ jsonpickle/ext/__pycache__/gmpy.cpython-312.pyc,,
25
+ jsonpickle/ext/__pycache__/numpy.cpython-312.pyc,,
26
+ jsonpickle/ext/__pycache__/pandas.cpython-312.pyc,,
27
+ jsonpickle/ext/__pycache__/yaml.cpython-312.pyc,,
28
+ jsonpickle/ext/gmpy.py,sha256=BSpYNyawYVeGdNQoMNQcS67H-UhxoSVAOYXkwPH2YFc,558
29
+ jsonpickle/ext/numpy.py,sha256=QTF9XhtuEzXJHVgswjA5TygGX34-hzj1WeZDrQtTxdc,14324
30
+ jsonpickle/ext/pandas.py,sha256=uScdvatBroJYZia6Xerm8t2i5eGZpCphOpZtILNnpvs,15138
31
+ jsonpickle/ext/yaml.py,sha256=jM5FPGefQ9UfLBcEYbm72ecUgRlkpp6a5GuQLRUQjks,429
32
+ jsonpickle/handlers.py,sha256=zbWgmCXnO9M7FUYz6hzjqivcj0XxibEnyzK96i2u218,8275
33
+ jsonpickle/pickler.py,sha256=Jpp1y9suO7qm1HdRkScTwGdHTtA_DLkRtXf_Id8vnkY,32227
34
+ jsonpickle/tags.py,sha256=-c43S7GOsPVG6ABR_vitWFjAEHVCD9g-oNFy090FlRY,987
35
+ jsonpickle/tags_pd.py,sha256=F6wFOUfSjp34e91wE8p25-37Pn4hH7z7dOC9DEYAQhI,8312
36
+ jsonpickle/unpickler.py,sha256=jKB6xhlm4dLMuj0qzyZA_9gGXRdKPmzxDTcaED6LY5o,33361
37
+ jsonpickle/util.py,sha256=3OFTrYRTEAqxXVjr2o15dtc9hcgnnZrMQtBXvZhFr7A,15933
38
+ jsonpickle/version.py,sha256=hPwJiFI0c_zey19VKn513p9gJ65s5mMdYi1p0EowrFM,342
.venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/WHEEL ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (80.9.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
.venv_haddock/lib/python3.12/site-packages/jsonpickle-4.1.1.dist-info/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ jsonpickle
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/METADATA ADDED
@@ -0,0 +1,349 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.4
2
+ Name: narwhals
3
+ Version: 2.19.0
4
+ Summary: Extremely lightweight compatibility layer between dataframe libraries
5
+ Project-URL: Homepage, https://github.com/narwhals-dev/narwhals
6
+ Project-URL: Documentation, https://narwhals-dev.github.io/narwhals/
7
+ Project-URL: Repository, https://github.com/narwhals-dev/narwhals
8
+ Project-URL: Bug Tracker, https://github.com/narwhals-dev/narwhals/issues
9
+ Author-email: Marco Gorelli <hello_narwhals@proton.me>
10
+ License: MIT License
11
+
12
+ Copyright (c) 2024 to present, Marco Gorelli
13
+
14
+ Permission is hereby granted, free of charge, to any person obtaining a copy
15
+ of this software and associated documentation files (the "Software"), to deal
16
+ in the Software without restriction, including without limitation the rights
17
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
18
+ copies of the Software, and to permit persons to whom the Software is
19
+ furnished to do so, subject to the following conditions:
20
+
21
+ The above copyright notice and this permission notice shall be included in all
22
+ copies or substantial portions of the Software.
23
+
24
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30
+ SOFTWARE.
31
+ License-File: LICENSE.md
32
+ Keywords: cudf,dask,dataframes,interoperability,modin,pandas,polars,pyarrow
33
+ Classifier: Development Status :: 5 - Production/Stable
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Programming Language :: Python :: 3
37
+ Classifier: Programming Language :: Python :: 3.9
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3.13
42
+ Classifier: Programming Language :: Python :: 3.14
43
+ Classifier: Programming Language :: Python :: Free Threading :: 2 - Beta
44
+ Classifier: Typing :: Typed
45
+ Requires-Python: >=3.9
46
+ Provides-Extra: cudf
47
+ Requires-Dist: cudf-cu12>=24.10.0; extra == 'cudf'
48
+ Provides-Extra: dask
49
+ Requires-Dist: dask[dataframe]>=2024.8; extra == 'dask'
50
+ Provides-Extra: duckdb
51
+ Requires-Dist: duckdb>=1.1; extra == 'duckdb'
52
+ Provides-Extra: ibis
53
+ Requires-Dist: ibis-framework>=6.0.0; extra == 'ibis'
54
+ Requires-Dist: packaging; extra == 'ibis'
55
+ Requires-Dist: pyarrow-hotfix; extra == 'ibis'
56
+ Requires-Dist: rich; extra == 'ibis'
57
+ Provides-Extra: modin
58
+ Requires-Dist: modin; extra == 'modin'
59
+ Provides-Extra: pandas
60
+ Requires-Dist: pandas>=1.1.3; extra == 'pandas'
61
+ Provides-Extra: polars
62
+ Requires-Dist: polars>=0.20.4; extra == 'polars'
63
+ Provides-Extra: pyarrow
64
+ Requires-Dist: pyarrow>=13.0.0; extra == 'pyarrow'
65
+ Provides-Extra: pyspark
66
+ Requires-Dist: pyspark>=3.5.0; extra == 'pyspark'
67
+ Provides-Extra: pyspark-connect
68
+ Requires-Dist: pyspark[connect]>=3.5.0; extra == 'pyspark-connect'
69
+ Provides-Extra: sql
70
+ Requires-Dist: duckdb>=1.1; extra == 'sql'
71
+ Requires-Dist: sqlparse; extra == 'sql'
72
+ Provides-Extra: sqlframe
73
+ Requires-Dist: sqlframe!=3.39.3,>=3.22.0; extra == 'sqlframe'
74
+ Description-Content-Type: text/markdown
75
+
76
+ # Narwhals
77
+
78
+ <h1 align="center">
79
+ <img
80
+ width="400"
81
+ alt="narwhals_small"
82
+ src="https://github.com/user-attachments/assets/968545af-ea0f-48bb-8377-144e93f7abf8">
83
+ </h1>
84
+
85
+ [![PyPI version](https://badge.fury.io/py/narwhals.svg)](https://badge.fury.io/py/narwhals)
86
+ [![Downloads](https://static.pepy.tech/badge/narwhals/month)](https://pepy.tech/project/narwhals)
87
+ [![Trusted publishing](https://img.shields.io/badge/Trusted_publishing-Provides_attestations-bright_green)](https://peps.python.org/pep-0740/)
88
+ [![PYPI - Types](https://img.shields.io/pypi/types/narwhals)](https://pypi.org/project/narwhals)
89
+
90
+ Extremely lightweight and extensible compatibility layer between dataframe libraries!
91
+
92
+ - **Full API support**: cuDF, Modin, pandas, Polars, PyArrow.
93
+ - **Lazy-only support**: Daft, Dask, DuckDB, Ibis, PySpark, SQLFrame.
94
+
95
+ Seamlessly support all, without depending on any!
96
+
97
+ - ✅ **Just use** [a subset of **the Polars API**](https://narwhals-dev.github.io/narwhals/api-reference/), no need to learn anything new
98
+ - ✅ **Zero dependencies**, Narwhals only uses what
99
+ the user passes in so your library can stay lightweight
100
+ - ✅ Separate **lazy** and eager APIs, use **expressions**
101
+ - ✅ Support pandas' complicated type system and index, without
102
+ either getting in the way
103
+ - ✅ **100% branch coverage**, tested against pandas and Polars nightly builds
104
+ - ✅ **Negligible overhead**, see [overhead](https://narwhals-dev.github.io/narwhals/overhead/)
105
+ - ✅ Let your IDE help you thanks to **full static typing**, see [typing](https://narwhals-dev.github.io/narwhals/api-reference/typing/)
106
+ - ✅ **Perfect backwards compatibility policy**,
107
+ see [stable api](https://narwhals-dev.github.io/narwhals/backcompat/) for how to opt-in
108
+
109
+ Get started!
110
+
111
+ - [Read the documentation](https://narwhals-dev.github.io/narwhals/)
112
+ - [Chat with us on Discord!](https://discord.gg/V3PqtB4VA4)
113
+ - [Join our community call](https://calendar.google.com/calendar/embed?src=27ff6dc5f598c1d94c1f6e627a1aaae680e2fac88f848bda1f2c7946ae74d5ab%40group.calendar.google.com)
114
+ - [Read the contributing guide](https://github.com/narwhals-dev/narwhals/blob/main/CONTRIBUTING.md)
115
+
116
+ <details>
117
+ <summary>Table of contents</summary>
118
+
119
+ - [Narwhals](#narwhals)
120
+ - [Installation](#installation)
121
+ - [Usage](#usage)
122
+ - [Example](#example)
123
+ - [Scope](#scope)
124
+ - [Roadmap](#roadmap)
125
+ - [Used by](#used-by)
126
+ - [Sponsors and institutional partners](#sponsors-and-institutional-partners)
127
+ - [Support](#support)
128
+ - [Appears on](#appears-on)
129
+ - [Why "Narwhals"?](#why-narwhals)
130
+
131
+ </details>
132
+
133
+ ## Installation
134
+
135
+ - pip (recommended, as it's the most up-to-date)
136
+ ```
137
+ pip install narwhals
138
+ ```
139
+ - conda-forge (also fine, but the latest version may take longer to appear)
140
+ ```
141
+ conda install -c conda-forge narwhals
142
+ ```
143
+
144
+ ## Usage
145
+
146
+ There are three steps to writing dataframe-agnostic code using Narwhals:
147
+
148
+ 1. use `narwhals.from_native` to wrap a pandas/Polars/Modin/cuDF/PyArrow
149
+ DataFrame/LazyFrame in a Narwhals class
150
+ 2. use the [subset of the Polars API supported by Narwhals](https://narwhals-dev.github.io/narwhals/api-reference/)
151
+ 3. use `narwhals.to_native` to return an object to the user in its original
152
+ dataframe flavour. For example:
153
+
154
+ - if you started with pandas, you'll get pandas back
155
+ - if you started with Polars, you'll get Polars back
156
+ - if you started with Modin, you'll get Modin back (and compute will be distributed)
157
+ - if you started with cuDF, you'll get cuDF back (and compute will happen on GPU)
158
+ - if you started with PyArrow, you'll get PyArrow back
159
+
160
+ <h1 align="left">
161
+ <img
162
+ width="600"
163
+ alt="narwhals_gif"
164
+ src="https://github.com/user-attachments/assets/88292d3c-6359-4155-973d-d0f8e3fbf5ac">
165
+
166
+ </h1>
167
+
168
+ ## Example
169
+
170
+ Narwhals allows you to define dataframe-agnostic functions. For example:
171
+
172
+ ```python
173
+ import narwhals as nw
174
+ from narwhals.typing import IntoFrameT
175
+
176
+
177
+ def agnostic_function(
178
+ df_native: IntoFrameT,
179
+ date_column: str,
180
+ price_column: str,
181
+ ) -> IntoFrameT:
182
+ return (
183
+ nw.from_native(df_native)
184
+ .group_by(nw.col(date_column).dt.truncate("1mo"))
185
+ .agg(nw.col(price_column).mean())
186
+ .sort(date_column)
187
+ .to_native()
188
+ )
189
+ ```
190
+
191
+ You can then pass `pandas.DataFrame`, `polars.DataFrame`, `polars.LazyFrame`, `duckdb.DuckDBPyRelation`,
192
+ `pyspark.sql.DataFrame`, `pyarrow.Table`, and more, to `agnostic_function`. In each case, no additional
193
+ dependencies will be required, and computation will stay native to the input library:
194
+
195
+ ```python
196
+ import pandas as pd
197
+ import polars as pl
198
+ from datetime import datetime
199
+
200
+ data = {
201
+ "date": [datetime(2020, 1, 1), datetime(2020, 1, 8), datetime(2020, 2, 3)],
202
+ "price": [1, 4, 3],
203
+ }
204
+ print("pandas result:")
205
+ print(agnostic_function(pd.DataFrame(data), "date", "price"))
206
+ print()
207
+ print("Polars result:")
208
+ print(agnostic_function(pl.DataFrame(data), "date", "price"))
209
+ ```
210
+
211
+ ```terminal
212
+ pandas result:
213
+ date price
214
+ 0 2020-01-01 2.5
215
+ 1 2020-02-01 3.0
216
+
217
+ Polars result:
218
+ shape: (2, 2)
219
+ ┌─────────────────────┬───────┐
220
+ │ date ┆ price │
221
+ │ --- ┆ --- │
222
+ │ datetime[μs] ┆ f64 │
223
+ ╞═════════════════════╪═══════╡
224
+ │ 2020-01-01 00:00:00 ┆ 2.5 │
225
+ │ 2020-02-01 00:00:00 ┆ 3.0 │
226
+ └─────────────────────┴───────┘
227
+ ```
228
+
229
+ See the [tutorial](https://narwhals-dev.github.io/narwhals/basics/dataframe/) for several examples!
230
+
231
+ ## Scope
232
+
233
+ - Do you maintain a dataframe-consuming library?
234
+ - Do you have a specific Polars function in mind that you would like Narwhals to have in order to make your work easier?
235
+
236
+ If you said yes to both, we'd love to hear from you!
237
+
238
+ ## Roadmap
239
+
240
+ See [roadmap discussion on GitHub](https://github.com/narwhals-dev/narwhals/discussions/1370)
241
+ for an up-to-date plan of future work.
242
+
243
+ ## Used by
244
+
245
+ Join the party!
246
+
247
+ - [altair](https://github.com/vega/altair/)
248
+ - [bokeh](https://github.com/bokeh/bokeh)
249
+ - [darts](https://github.com/unit8co/darts)
250
+ - [fairlearn](https://github.com/fairlearn/fairlearn)
251
+ - [formulaic](https://github.com/matthewwardrop/formulaic)
252
+ - [gt-extras](https://github.com/posit-dev/gt-extras)
253
+ - [hierarchicalforecast](https://github.com/Nixtla/hierarchicalforecast)
254
+ - [marimo](https://github.com/marimo-team/marimo)
255
+ - [metalearners](https://github.com/Quantco/metalearners)
256
+ - [mosaic](https://github.com/uwdata/mosaic)
257
+ - [panel-graphic-walker](https://github.com/panel-extensions/panel-graphic-walker)
258
+ - [plotly](https://plotly.com)
259
+ - [pointblank](https://github.com/posit-dev/pointblank)
260
+ - [pymarginaleffects](https://github.com/vincentarelbundock/pymarginaleffects)
261
+ - [pyreadstat](https://github.com/Roche/pyreadstat)
262
+ - [py-shiny](https://github.com/posit-dev/py-shiny)
263
+ - [rio](https://github.com/rio-labs/rio)
264
+ - [scikit-lego](https://github.com/koaning/scikit-lego)
265
+ - [scikit-playtime](https://github.com/koaning/scikit-playtime)
266
+ - [tabmat](https://github.com/Quantco/tabmat)
267
+ - [tea-tasting](https://github.com/e10v/tea-tasting)
268
+ - [timebasedcv](https://github.com/FBruzzesi/timebasedcv)
269
+ - [tubular](https://github.com/lvgig/tubular)
270
+ - [Validoopsie](https://github.com/akmalsoliev/Validoopsie)
271
+ - [vegafusion](https://github.com/vega/vegafusion)
272
+ - [wimsey](https://github.com/benrutter/wimsey)
273
+
274
+ Feel free to add your project to the list if it's missing, and/or
275
+ [chat with us on Discord](https://discord.gg/V3PqtB4VA4) if you'd like any support.
276
+
277
+ ## Sponsors and institutional partners
278
+
279
+ Narwhals is 100% independent, community-driven, and community-owned.
280
+ We are extremely grateful to the following organisations for having
281
+ provided some funding / development time:
282
+
283
+ - [Quansight Labs](https://labs.quansight.org)
284
+ - [Quansight Futures](https://www.qi.ventures)
285
+ - [OpenTeams](https://www.openteams.com)
286
+ - [POSSEE initiative](https://possee.org)
287
+ - [BYU-Idaho](https://www.byui.edu)
288
+
289
+ If you contribute to Narwhals on your organization's time, please let us know. We'd be happy to add your employer
290
+ to this list!
291
+
292
+ ## Support
293
+
294
+ If you'd like to say "thank you", please give us a ⭐ star ⭐.
295
+
296
+ Please contact [hello_narwhals@proton.me](hello_narwhals@proton.me) if you would like to:
297
+
298
+ - Receive professional support (e.g., if you're using or would like to use Narwhals at your company).
299
+ - Have any Narwhals fixes / features prioritised.
300
+ - Commission any Narwhals plugins for new backends.
301
+
302
+ ## Appears on
303
+
304
+ Narwhals has been featured in several talks, podcasts, and blog posts:
305
+
306
+ - [Inspiring Computing Podcast](https://www.inspiringcomputing.com/2107763/episodes/16702460-the-rise-of-narwhals-in-open-source)
307
+ The Rise of Narwhals in Open-Source
308
+
309
+ - [PyCon DE & PyData 2025](https://youtu.be/DJk782DWcss)
310
+ How Narwhals is silently bringing pandas, Polars, DuckDB, PyArrow, and more together
311
+
312
+ - [The Python Exchange March 2025](https://youtu.be/TvFWFlK-2po)
313
+ What Can Narwhals Do for You?
314
+
315
+ - [PyData London 2025](https://youtu.be/r2PxJlO7_QA)
316
+ How Narwhals brings Polars, DuckDB, PyArrow, & pandas together
317
+
318
+ - [Talk Python to me Podcast](https://youtu.be/FSH7BZ0tuE0)
319
+ Ahoy, Narwhals are bridging the data science APIs
320
+
321
+ - [Python Bytes Podcast](https://www.youtube.com/live/N7w_ESVW40I?si=y-wN1uCsAuJOKlOT&t=382)
322
+ Episode 402, topic #2
323
+
324
+ - [Super Data Science: ML & AI Podcast](https://www.youtube.com/watch?v=TeG4U8R0U8U)
325
+ Narwhals: For Pandas-to-Polars DataFrame Compatibility
326
+
327
+ - [Sample Space Podcast | probabl](https://youtu.be/8hYdq4sWbbQ?si=WG0QP1CZ6gkFf18b)
328
+ How Narwhals has many end users ... that never use it directly. - Marco Gorelli
329
+
330
+ - [The Real Python Podcast](https://www.youtube.com/watch?v=w5DFZbFYzCM)
331
+ Narwhals: Expanding DataFrame Compatibility Between Libraries
332
+
333
+ - [Pycon Lithuania 2024](https://www.youtube.com/watch?v=-mdx7Cn6_6E)
334
+ Marco Gorelli - DataFrame interoperatiblity - what's been achieved, and what comes next?
335
+
336
+ - [Pycon Italy 2024](https://www.youtube.com/watch?v=3IqUli9XsmQ)
337
+ How you can write a dataframe-agnostic library - Marco Gorelli
338
+
339
+ - [Polars Blog Post](https://pola.rs/posts/lightweight_plotting/)
340
+ Polars has a new lightweight plotting backend
341
+
342
+ - [Quansight Labs blog post (w/ Scikit-Lego)](https://labs.quansight.org/blog/scikit-lego-narwhals)
343
+ How Narwhals and scikit-lego came together to achieve dataframe-agnosticism
344
+
345
+ ## Why "Narwhals"?
346
+
347
+ [Coz they are so awesome](https://youtu.be/ykwqXuMPsoc?si=A-i8LdR38teYsos4).
348
+
349
+ Thanks to [Olha Urdeichuk](https://www.fiverr.com/olhaurdeichuk) for the illustration!
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/RECORD ADDED
@@ -0,0 +1,330 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ narwhals-2.19.0.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ narwhals-2.19.0.dist-info/METADATA,sha256=LFbVqYTtwz5TWaaKr9cLNbc7v5F42KlooRzWyo3T48Q,14081
3
+ narwhals-2.19.0.dist-info/RECORD,,
4
+ narwhals-2.19.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
5
+ narwhals-2.19.0.dist-info/licenses/LICENSE.md,sha256=gRRF8wFHuPDJ1ETJAl_VKPlTLFS3uD9uI2hHPckc_fA,1082
6
+ narwhals/__init__.py,sha256=2K-Vi5Dtx6Sc6-EwIlMGKYg50WiP8AXB2GWB-v_AUa4,3339
7
+ narwhals/__pycache__/__init__.cpython-312.pyc,,
8
+ narwhals/__pycache__/_constants.cpython-312.pyc,,
9
+ narwhals/__pycache__/_duration.cpython-312.pyc,,
10
+ narwhals/__pycache__/_enum.cpython-312.pyc,,
11
+ narwhals/__pycache__/_exceptions.cpython-312.pyc,,
12
+ narwhals/__pycache__/_expression_parsing.cpython-312.pyc,,
13
+ narwhals/__pycache__/_namespace.cpython-312.pyc,,
14
+ narwhals/__pycache__/_native.cpython-312.pyc,,
15
+ narwhals/__pycache__/_translate.cpython-312.pyc,,
16
+ narwhals/__pycache__/_typing.cpython-312.pyc,,
17
+ narwhals/__pycache__/_typing_compat.cpython-312.pyc,,
18
+ narwhals/__pycache__/_utils.cpython-312.pyc,,
19
+ narwhals/__pycache__/compliant.cpython-312.pyc,,
20
+ narwhals/__pycache__/dataframe.cpython-312.pyc,,
21
+ narwhals/__pycache__/dependencies.cpython-312.pyc,,
22
+ narwhals/__pycache__/dtypes.cpython-312.pyc,,
23
+ narwhals/__pycache__/exceptions.cpython-312.pyc,,
24
+ narwhals/__pycache__/expr.cpython-312.pyc,,
25
+ narwhals/__pycache__/expr_cat.cpython-312.pyc,,
26
+ narwhals/__pycache__/expr_dt.cpython-312.pyc,,
27
+ narwhals/__pycache__/expr_list.cpython-312.pyc,,
28
+ narwhals/__pycache__/expr_name.cpython-312.pyc,,
29
+ narwhals/__pycache__/expr_str.cpython-312.pyc,,
30
+ narwhals/__pycache__/expr_struct.cpython-312.pyc,,
31
+ narwhals/__pycache__/functions.cpython-312.pyc,,
32
+ narwhals/__pycache__/group_by.cpython-312.pyc,,
33
+ narwhals/__pycache__/plugins.cpython-312.pyc,,
34
+ narwhals/__pycache__/schema.cpython-312.pyc,,
35
+ narwhals/__pycache__/selectors.cpython-312.pyc,,
36
+ narwhals/__pycache__/series.cpython-312.pyc,,
37
+ narwhals/__pycache__/series_cat.cpython-312.pyc,,
38
+ narwhals/__pycache__/series_dt.cpython-312.pyc,,
39
+ narwhals/__pycache__/series_list.cpython-312.pyc,,
40
+ narwhals/__pycache__/series_str.cpython-312.pyc,,
41
+ narwhals/__pycache__/series_struct.cpython-312.pyc,,
42
+ narwhals/__pycache__/sql.cpython-312.pyc,,
43
+ narwhals/__pycache__/this.cpython-312.pyc,,
44
+ narwhals/__pycache__/translate.cpython-312.pyc,,
45
+ narwhals/__pycache__/typing.cpython-312.pyc,,
46
+ narwhals/__pycache__/utils.cpython-312.pyc,,
47
+ narwhals/_arrow/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
48
+ narwhals/_arrow/__pycache__/__init__.cpython-312.pyc,,
49
+ narwhals/_arrow/__pycache__/dataframe.cpython-312.pyc,,
50
+ narwhals/_arrow/__pycache__/expr.cpython-312.pyc,,
51
+ narwhals/_arrow/__pycache__/group_by.cpython-312.pyc,,
52
+ narwhals/_arrow/__pycache__/namespace.cpython-312.pyc,,
53
+ narwhals/_arrow/__pycache__/selectors.cpython-312.pyc,,
54
+ narwhals/_arrow/__pycache__/series.cpython-312.pyc,,
55
+ narwhals/_arrow/__pycache__/series_cat.cpython-312.pyc,,
56
+ narwhals/_arrow/__pycache__/series_dt.cpython-312.pyc,,
57
+ narwhals/_arrow/__pycache__/series_list.cpython-312.pyc,,
58
+ narwhals/_arrow/__pycache__/series_str.cpython-312.pyc,,
59
+ narwhals/_arrow/__pycache__/series_struct.cpython-312.pyc,,
60
+ narwhals/_arrow/__pycache__/typing.cpython-312.pyc,,
61
+ narwhals/_arrow/__pycache__/utils.cpython-312.pyc,,
62
+ narwhals/_arrow/dataframe.py,sha256=SIlHQrE80jg19Vq33Y2pCwNzhWDJj-0k-VD3zkzBYCw,31067
63
+ narwhals/_arrow/expr.py,sha256=T0F5hG0k4jeITT__B6UIHVGvkgGK1uXpZTyu8ZuzPyg,9433
64
+ narwhals/_arrow/group_by.py,sha256=3kNOSdauoXDWtMMAhOQfrQtbmhC1bzSN7Sl56QfwQE4,9174
65
+ narwhals/_arrow/namespace.py,sha256=gpxdqsMjeKUTw93dabbCPRlmZJ_w8LvwEG5VQYK7xYo,11272
66
+ narwhals/_arrow/selectors.py,sha256=kShb4WWC9UKQO_MTrYoLNKyo2KLdofjFRh1KBRtXCKQ,882
67
+ narwhals/_arrow/series.py,sha256=ZdmyaElQif1QOUKvMdeyGpswgzndXMDkz-Toq_8yL2c,45518
68
+ narwhals/_arrow/series_cat.py,sha256=j2DFbFEoaW2vSnLnCycspYNtbNYeWvVSeLELYb_3zF0,686
69
+ narwhals/_arrow/series_dt.py,sha256=xTQt39PKTVPkeVwh87soCld_ll6-v_OQJTdUKJBBjS4,9026
70
+ narwhals/_arrow/series_list.py,sha256=EDwxUa5bm5jrYci8SIK9sXa8gMv8k7GnCUndixg55gs,1461
71
+ narwhals/_arrow/series_str.py,sha256=n87Jqa7q-O-GonBiwWy3V7itGrDYB168Jk9Z-yj7_ns,5179
72
+ narwhals/_arrow/series_struct.py,sha256=MorW6vTLKxqpR96NhB5RxkkBWOxrCTyvJ76Ilnwb7LY,504
73
+ narwhals/_arrow/typing.py,sha256=W3Vz_kc5zw94VeYzrC9xNPYpJBZ3DOSyfpuWPUVEW1M,2359
74
+ narwhals/_arrow/utils.py,sha256=9ntQC59VAxpuZDsd2C6NNc510dNWle1VxEMKoLSEOjs,21010
75
+ narwhals/_compliant/__init__.py,sha256=Xzk2TdU1KItMCg-r_cs599PPF8x9BMjgSMiOalW9Vjs,2319
76
+ narwhals/_compliant/__pycache__/__init__.cpython-312.pyc,,
77
+ narwhals/_compliant/__pycache__/any_namespace.cpython-312.pyc,,
78
+ narwhals/_compliant/__pycache__/column.cpython-312.pyc,,
79
+ narwhals/_compliant/__pycache__/dataframe.cpython-312.pyc,,
80
+ narwhals/_compliant/__pycache__/expr.cpython-312.pyc,,
81
+ narwhals/_compliant/__pycache__/group_by.cpython-312.pyc,,
82
+ narwhals/_compliant/__pycache__/namespace.cpython-312.pyc,,
83
+ narwhals/_compliant/__pycache__/selectors.cpython-312.pyc,,
84
+ narwhals/_compliant/__pycache__/series.cpython-312.pyc,,
85
+ narwhals/_compliant/__pycache__/typing.cpython-312.pyc,,
86
+ narwhals/_compliant/__pycache__/window.cpython-312.pyc,,
87
+ narwhals/_compliant/any_namespace.py,sha256=1Zbv6m0x21qbHJqG5YbhlmPDBKWS0XcGdqbm6s5Rwgk,4411
88
+ narwhals/_compliant/column.py,sha256=d5watE0NL3f9tsIMqpELlI5OYIeKSMYKqZg1JAEZBEQ,5273
89
+ narwhals/_compliant/dataframe.py,sha256=FlbZXtq3xuN1YlAXH7mUUZnEljeAv00gs6xyVoO3Pss,16819
90
+ narwhals/_compliant/expr.py,sha256=YayC8nTW1BKfTEpK6k5P_K1IuGbcsRh3r9kTYO1yaxM,42125
91
+ narwhals/_compliant/group_by.py,sha256=0eKCV-jxXe506ZVGRDQnoL0LsBeMMUHgqkalHkO8VQo,7050
92
+ narwhals/_compliant/namespace.py,sha256=ai7Tj7tGeWPBYNd7Bbkxvz-Y7zVKcqQW-y1j-RX3PPk,11348
93
+ narwhals/_compliant/selectors.py,sha256=und99_KqUg9zrdhBlfxQVl_6R-VPv6NsL3vv6Bcwhuk,11902
94
+ narwhals/_compliant/series.py,sha256=g4kTQv140Hykaon14-VZazPgdjMmVPCezqmQiHbt-RY,13790
95
+ narwhals/_compliant/typing.py,sha256=xQ6omwtoRfLCiGXlgh-o7FuR_zHwmxL_QEvp6S0EZ1U,7498
96
+ narwhals/_compliant/window.py,sha256=_ji4goVKkT4YPTyZa_I0N2yGmwBfB1_LDG0WSXGbmlo,505
97
+ narwhals/_constants.py,sha256=kE1KWsIky4ryabH-Z117ZtGW24ccTcreWOZJjpacO6I,1094
98
+ narwhals/_dask/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
99
+ narwhals/_dask/__pycache__/__init__.cpython-312.pyc,,
100
+ narwhals/_dask/__pycache__/dataframe.cpython-312.pyc,,
101
+ narwhals/_dask/__pycache__/expr.cpython-312.pyc,,
102
+ narwhals/_dask/__pycache__/expr_dt.cpython-312.pyc,,
103
+ narwhals/_dask/__pycache__/expr_str.cpython-312.pyc,,
104
+ narwhals/_dask/__pycache__/group_by.cpython-312.pyc,,
105
+ narwhals/_dask/__pycache__/namespace.cpython-312.pyc,,
106
+ narwhals/_dask/__pycache__/selectors.cpython-312.pyc,,
107
+ narwhals/_dask/__pycache__/utils.cpython-312.pyc,,
108
+ narwhals/_dask/dataframe.py,sha256=tCT7sjZQ-5s3ykXJI-U-dIvQjIWukvf2MoroHEx_g6A,19856
109
+ narwhals/_dask/expr.py,sha256=VSd6j1ucRuFXkkiEg6hsVs7LLxo-wN3b9bFSrhFNa78,26735
110
+ narwhals/_dask/expr_dt.py,sha256=gtLt-UgD0Kw_Vev32rOZUdmP_XQfvU9XrKjtgmkQYps,6276
111
+ narwhals/_dask/expr_str.py,sha256=XE6bKZd-PTfMsZOJ49mWzl1miiQQoKQlTG2U_i97gic,3885
112
+ narwhals/_dask/group_by.py,sha256=nwgSODQljSjJ10snNGvOvKN3ctBXNertD6pciA5H0cs,5083
113
+ narwhals/_dask/namespace.py,sha256=lfE8aXPwpb7ejdIhkxE5kFZy4GasGGrYEqraRaxpTBE,13416
114
+ narwhals/_dask/selectors.py,sha256=W8tLFVUbafUb5EKi5rg09-cP9JA4T3MwiIjKCYk1YH0,927
115
+ narwhals/_dask/utils.py,sha256=pAUYw9k1krePgRzGWxWVBj4OyMaT6AALaRILOR6ehxo,5445
116
+ narwhals/_duckdb/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
117
+ narwhals/_duckdb/__pycache__/__init__.cpython-312.pyc,,
118
+ narwhals/_duckdb/__pycache__/dataframe.cpython-312.pyc,,
119
+ narwhals/_duckdb/__pycache__/expr.cpython-312.pyc,,
120
+ narwhals/_duckdb/__pycache__/expr_dt.cpython-312.pyc,,
121
+ narwhals/_duckdb/__pycache__/expr_list.cpython-312.pyc,,
122
+ narwhals/_duckdb/__pycache__/expr_str.cpython-312.pyc,,
123
+ narwhals/_duckdb/__pycache__/expr_struct.cpython-312.pyc,,
124
+ narwhals/_duckdb/__pycache__/group_by.cpython-312.pyc,,
125
+ narwhals/_duckdb/__pycache__/namespace.cpython-312.pyc,,
126
+ narwhals/_duckdb/__pycache__/selectors.cpython-312.pyc,,
127
+ narwhals/_duckdb/__pycache__/series.cpython-312.pyc,,
128
+ narwhals/_duckdb/__pycache__/typing.cpython-312.pyc,,
129
+ narwhals/_duckdb/__pycache__/utils.cpython-312.pyc,,
130
+ narwhals/_duckdb/dataframe.py,sha256=SjQP-dj-XAd_lRCLqDmH-hHWT74yypUwvy9bNFEI4Bw,20462
131
+ narwhals/_duckdb/expr.py,sha256=k35p2V98KcjhMchjvdvkowap7Sw8WBrbVAFXPcej4wc,12486
132
+ narwhals/_duckdb/expr_dt.py,sha256=RDqYnsM0pDPEh59hq0BHrl6YNLFBR7w8gLIdxVWdzvY,5157
133
+ narwhals/_duckdb/expr_list.py,sha256=OgnTsvii5lJDZ2vBJQIXBGT0hMqK2HfGOX_Dvrli2es,2734
134
+ narwhals/_duckdb/expr_str.py,sha256=ksmAAAnRr9fE5dzLI8ZkcIkxCdv-o1lbE3k9zlVsv7k,1870
135
+ narwhals/_duckdb/expr_struct.py,sha256=eN06QA1JS6wjAt7_AZzW3xoztHM_hoadlFUl_hwsEiE,576
136
+ narwhals/_duckdb/group_by.py,sha256=e07h9TN45G6HUveqhalRDKp9PngacCRLa-o3WlkoW5o,1276
137
+ narwhals/_duckdb/namespace.py,sha256=g-4cU0j3CVwe4ljTc4brdYRoNSJM18b6g3vnvCY4EKQ,6400
138
+ narwhals/_duckdb/selectors.py,sha256=yA16Z-MlJUJBjOu0XI9qVO4Zx7L_T5FN2DQqNAYhu-o,1033
139
+ narwhals/_duckdb/series.py,sha256=xBpuPUnSSIQ1vYEKjHQFZN7ix1ZyMwSchliDPpkf3Wk,1397
140
+ narwhals/_duckdb/typing.py,sha256=gO_Odyinkn4QZY_TU4uuzda6mbeo38glOOUUripcWgg,454
141
+ narwhals/_duckdb/utils.py,sha256=yqg4XsFY_URuzEMBxew2a8aDdgHD2FMXfBBXqA-Bbz4,15810
142
+ narwhals/_duration.py,sha256=WGzj3FVcC2KogqRhNeim3YDIwUn8HkXQHAljtvHrjwQ,3139
143
+ narwhals/_enum.py,sha256=6mWLGvqHP8JhLRhBjGof4Ungx-SDasqu-G0M2pX0Oew,1142
144
+ narwhals/_exceptions.py,sha256=uVgFKgx_6ub9MHJ_qJ7xC5zie-uRVtbJo0j3FDoXAqk,1894
145
+ narwhals/_expression_parsing.py,sha256=M-GhKye9mecJLjI9lF3jiDVSQWijZ0j2nH6-DkPSYKc,33387
146
+ narwhals/_ibis/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
147
+ narwhals/_ibis/__pycache__/__init__.cpython-312.pyc,,
148
+ narwhals/_ibis/__pycache__/dataframe.cpython-312.pyc,,
149
+ narwhals/_ibis/__pycache__/expr.cpython-312.pyc,,
150
+ narwhals/_ibis/__pycache__/expr_dt.cpython-312.pyc,,
151
+ narwhals/_ibis/__pycache__/expr_list.cpython-312.pyc,,
152
+ narwhals/_ibis/__pycache__/expr_str.cpython-312.pyc,,
153
+ narwhals/_ibis/__pycache__/expr_struct.cpython-312.pyc,,
154
+ narwhals/_ibis/__pycache__/group_by.cpython-312.pyc,,
155
+ narwhals/_ibis/__pycache__/namespace.cpython-312.pyc,,
156
+ narwhals/_ibis/__pycache__/selectors.cpython-312.pyc,,
157
+ narwhals/_ibis/__pycache__/series.cpython-312.pyc,,
158
+ narwhals/_ibis/__pycache__/utils.cpython-312.pyc,,
159
+ narwhals/_ibis/dataframe.py,sha256=ihqiWfvAeCRs3Vlcyj75yAel-Z4lGR8IL4g80MjX2cU,16388
160
+ narwhals/_ibis/expr.py,sha256=2Unv20zbWJ52goEPNIlq7zCKXtfDC9Z_B044G54BY_g,14018
161
+ narwhals/_ibis/expr_dt.py,sha256=0RS1B1geFYxyS5RplyG9VES8mFg4tylcG75dIKczvNs,3308
162
+ narwhals/_ibis/expr_list.py,sha256=1REKJRa7930JTMofZbSb4rghjBg1mOAZf8sRcKx1EUs,2343
163
+ narwhals/_ibis/expr_str.py,sha256=fvYzDibIaGH8bE3ZhTUF9yfs--0ONM6l7f5zeW7neLk,3443
164
+ narwhals/_ibis/expr_struct.py,sha256=FDsa5MqcHhqPmpZIEfGBASdqxPkyImrlGTH7XUSw3cs,565
165
+ narwhals/_ibis/group_by.py,sha256=enNzAPUsA_LIwPNJ7jG_MJKyqG2HyCiesBEX3pJgJBg,1031
166
+ narwhals/_ibis/namespace.py,sha256=H3d9nO20RAEF0UVQzBaN4jHkSmk3JHR2iV2tP26uzKE,5635
167
+ narwhals/_ibis/selectors.py,sha256=SkFxoukpKc_OjwKoKHRm8VwMaphCMUeWBJ2g_oWz3D0,961
168
+ narwhals/_ibis/series.py,sha256=CZDwDPsdELKtdr7OWmcFyGqexr33Ucfnv_RU95VJxIQ,1218
169
+ narwhals/_ibis/utils.py,sha256=j2nf-cb3wXP0OOlMuyg3qMsFOYZHD_c5pnW_qwu4uy0,10591
170
+ narwhals/_interchange/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
171
+ narwhals/_interchange/__pycache__/__init__.cpython-312.pyc,,
172
+ narwhals/_interchange/__pycache__/dataframe.cpython-312.pyc,,
173
+ narwhals/_interchange/__pycache__/series.cpython-312.pyc,,
174
+ narwhals/_interchange/dataframe.py,sha256=FC_2WuxxI4RPUBMqcau68rkdfsxhClou4zCErx1flcw,6034
175
+ narwhals/_interchange/series.py,sha256=nSxdlOZrw3wtavS42TMR_b_EGgPBv224ioZBMo5eoC8,1651
176
+ narwhals/_namespace.py,sha256=ARbIk31MgCvYDAxlAz7J9TGKktG0_p-Eu9myDi3nurs,8551
177
+ narwhals/_native.py,sha256=ByNgFo_kGIsgr_dSte8mT6snLjiBbsvAFGrECnXjl-g,15402
178
+ narwhals/_pandas_like/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
179
+ narwhals/_pandas_like/__pycache__/__init__.cpython-312.pyc,,
180
+ narwhals/_pandas_like/__pycache__/dataframe.cpython-312.pyc,,
181
+ narwhals/_pandas_like/__pycache__/expr.cpython-312.pyc,,
182
+ narwhals/_pandas_like/__pycache__/group_by.cpython-312.pyc,,
183
+ narwhals/_pandas_like/__pycache__/namespace.cpython-312.pyc,,
184
+ narwhals/_pandas_like/__pycache__/selectors.cpython-312.pyc,,
185
+ narwhals/_pandas_like/__pycache__/series.cpython-312.pyc,,
186
+ narwhals/_pandas_like/__pycache__/series_cat.cpython-312.pyc,,
187
+ narwhals/_pandas_like/__pycache__/series_dt.cpython-312.pyc,,
188
+ narwhals/_pandas_like/__pycache__/series_list.cpython-312.pyc,,
189
+ narwhals/_pandas_like/__pycache__/series_str.cpython-312.pyc,,
190
+ narwhals/_pandas_like/__pycache__/series_struct.cpython-312.pyc,,
191
+ narwhals/_pandas_like/__pycache__/typing.cpython-312.pyc,,
192
+ narwhals/_pandas_like/__pycache__/utils.cpython-312.pyc,,
193
+ narwhals/_pandas_like/dataframe.py,sha256=S7yOLQzPJkDD0_WG3FRFNXHGi1slBusZ_sFtZlavNbo,46397
194
+ narwhals/_pandas_like/expr.py,sha256=8S2dcPNbB-PpsxWloB_PTVAIg5-wiKXMGHrSws9Eznw,16990
195
+ narwhals/_pandas_like/group_by.py,sha256=09zHMYyVXnQBM7efTHbWYMO4a-QdUYcVBfO3kY9oWjg,15484
196
+ narwhals/_pandas_like/namespace.py,sha256=hEs23p2AqNEp_NqPp_ZCYY9s_geiIuMCJgJ8_hH80mk,17025
197
+ narwhals/_pandas_like/selectors.py,sha256=ksx2a0Pf1g2OJu2dsWGnuUH3095v40OnhzT7zkolfhA,1015
198
+ narwhals/_pandas_like/series.py,sha256=hNPg9jRyDUon9UDJ1xgklako2Dn--cUBfldnBFw_llE,48087
199
+ narwhals/_pandas_like/series_cat.py,sha256=MJwCnJ49hfnODh6JgMHOCQ2KBlTbmySU6_X4XWaqiz4,527
200
+ narwhals/_pandas_like/series_dt.py,sha256=Mq6Dhrki-HoV2yqnbsKWT60W2li1UjtOTnKB5V3FTzA,11814
201
+ narwhals/_pandas_like/series_list.py,sha256=Ew6nc4z3cddOWDAwj-8s-ouHew7Eq9mTQbb55iw7JGI,2960
202
+ narwhals/_pandas_like/series_str.py,sha256=XCX1xE2-GjV5E6VVQWQXVmuyS7UNuG3e5jhgwaDu4ek,4875
203
+ narwhals/_pandas_like/series_struct.py,sha256=vX9HoO42vHackvVozUfp8odM9uJ4owct49ydKDnohdk,518
204
+ narwhals/_pandas_like/typing.py,sha256=4-y2QKdz3GChKp8HStqFLW8Fwe5KUMFFJDtjGR76ERQ,1059
205
+ narwhals/_pandas_like/utils.py,sha256=DBFU2dBqxbaXBP2mClNEGMuL_0hByOsn4yLnUHZLmPE,26543
206
+ narwhals/_polars/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
207
+ narwhals/_polars/__pycache__/__init__.cpython-312.pyc,,
208
+ narwhals/_polars/__pycache__/dataframe.cpython-312.pyc,,
209
+ narwhals/_polars/__pycache__/expr.cpython-312.pyc,,
210
+ narwhals/_polars/__pycache__/group_by.cpython-312.pyc,,
211
+ narwhals/_polars/__pycache__/namespace.cpython-312.pyc,,
212
+ narwhals/_polars/__pycache__/series.cpython-312.pyc,,
213
+ narwhals/_polars/__pycache__/typing.cpython-312.pyc,,
214
+ narwhals/_polars/__pycache__/utils.cpython-312.pyc,,
215
+ narwhals/_polars/dataframe.py,sha256=vTeRBVrS103xVvdGhHJ8Hs31WCpuBGle421Csbi7dYI,26141
216
+ narwhals/_polars/expr.py,sha256=QdRHd7aKjEO1J595zzp4jwLq5lOqoO5c7yPDjB1dcB0,17882
217
+ narwhals/_polars/group_by.py,sha256=PsxQPWX7QWy2iXUWJEelC5O6mR1TKr9MB_i6O5RVxms,2373
218
+ narwhals/_polars/namespace.py,sha256=AFRy05M9TLzYlJVwwKlk1YN7Mb8EWdAc7i132CjGblE,10469
219
+ narwhals/_polars/series.py,sha256=Pdp4B1k6AR4moNWugq4xTUvkHJQizz04wzE1ZAEfaf4,28502
220
+ narwhals/_polars/typing.py,sha256=d11nVYqv1dqC_H2A-PXz1oHYYCAOnkK_s87ytm4twMA,302
221
+ narwhals/_polars/utils.py,sha256=NcNC8kPirVuo3FRVtOcoXMPIfElikdwQ05nfR49flLM,13035
222
+ narwhals/_spark_like/__init__.py,sha256=T7_UCePrrYs1ZeMatvCUYUvQcXvrDjQ4b08_ugWIHAo,87
223
+ narwhals/_spark_like/__pycache__/__init__.cpython-312.pyc,,
224
+ narwhals/_spark_like/__pycache__/dataframe.cpython-312.pyc,,
225
+ narwhals/_spark_like/__pycache__/expr.cpython-312.pyc,,
226
+ narwhals/_spark_like/__pycache__/expr_dt.cpython-312.pyc,,
227
+ narwhals/_spark_like/__pycache__/expr_list.cpython-312.pyc,,
228
+ narwhals/_spark_like/__pycache__/expr_str.cpython-312.pyc,,
229
+ narwhals/_spark_like/__pycache__/expr_struct.cpython-312.pyc,,
230
+ narwhals/_spark_like/__pycache__/group_by.cpython-312.pyc,,
231
+ narwhals/_spark_like/__pycache__/namespace.cpython-312.pyc,,
232
+ narwhals/_spark_like/__pycache__/selectors.cpython-312.pyc,,
233
+ narwhals/_spark_like/__pycache__/utils.cpython-312.pyc,,
234
+ narwhals/_spark_like/dataframe.py,sha256=tcQSJl1RO6i1DuV4bsji1mHWSqHLOy5CAC3UoVsP3tY,23329
235
+ narwhals/_spark_like/expr.py,sha256=oBtmPMTlS356IoDQ47HXzCujDqmh4QXgQQn2le71qC4,15337
236
+ narwhals/_spark_like/expr_dt.py,sha256=EuvgesSi-N4DN3F3zRy9kS2So6gx-w7bxlGbyrJieBU,7874
237
+ narwhals/_spark_like/expr_list.py,sha256=1B9OsYCXYEWJqIUm5Id2ikMMKNTwoCyeia5LXRYp-OA,3853
238
+ narwhals/_spark_like/expr_str.py,sha256=iM2nmJpIeNQP8v5W9kyug1wlVir3cM8VDXHVGyHQMPU,2452
239
+ narwhals/_spark_like/expr_struct.py,sha256=haBDpuRhn_nGAFjMF3arhhRr6NfefNei9vEmAOa0fQI,613
240
+ narwhals/_spark_like/group_by.py,sha256=DH7fgToOMLaQXEVPSkMjqzTpdz2ZjDIAM0WoK8XjQFU,1247
241
+ narwhals/_spark_like/namespace.py,sha256=k1UTQez8qMdgQRj6H8yi4jEcAqhZe7a8w83PwVaFLlk,8522
242
+ narwhals/_spark_like/selectors.py,sha256=SzJPoFjyIEviSSvPRvL81o1jjQJcM-Veqb52vFU66JQ,1086
243
+ narwhals/_spark_like/utils.py,sha256=hRQT2SDrKJfZrfFFqDhW-s8UVkfc0LcKuTjbgoeTcj0,11892
244
+ narwhals/_sql/__init__.py,sha256=T7_UCePrrYs1ZeMatvCUYUvQcXvrDjQ4b08_ugWIHAo,87
245
+ narwhals/_sql/__pycache__/__init__.cpython-312.pyc,,
246
+ narwhals/_sql/__pycache__/dataframe.cpython-312.pyc,,
247
+ narwhals/_sql/__pycache__/expr.cpython-312.pyc,,
248
+ narwhals/_sql/__pycache__/expr_dt.cpython-312.pyc,,
249
+ narwhals/_sql/__pycache__/expr_str.cpython-312.pyc,,
250
+ narwhals/_sql/__pycache__/group_by.cpython-312.pyc,,
251
+ narwhals/_sql/__pycache__/namespace.cpython-312.pyc,,
252
+ narwhals/_sql/__pycache__/typing.cpython-312.pyc,,
253
+ narwhals/_sql/dataframe.py,sha256=itTHoiLQ74S0Z8SeRgFT_Ss4jbWBs9La5DrME4Mm3xU,2451
254
+ narwhals/_sql/expr.py,sha256=-7VO3_RWNAmr-2YANZD0_K6EKD3_dBMUTMi1sHtqI20,34572
255
+ narwhals/_sql/expr_dt.py,sha256=QcBGKkp9_gUgPOMGXcfuGsqeC7iT1AAGrq5ZDX-nEKo,1700
256
+ narwhals/_sql/expr_str.py,sha256=RPsPIqySlNmAOOMGVai0nUnpUqhldc1X6jx-Bsnq6TM,7433
257
+ narwhals/_sql/group_by.py,sha256=-yR5J2-Kk0awFRoFnLici00rfTK_5CxFKJSxc-Bt8Zs,1669
258
+ narwhals/_sql/namespace.py,sha256=hvSGHpWebsx05PYipMQp8GRlM1Zx-_qCopPzhv7nbXo,3352
259
+ narwhals/_sql/typing.py,sha256=e3LkLPI4oa2IzykR7BgO9IIfCKRw0vrX4uHxPTB-uJM,487
260
+ narwhals/_translate.py,sha256=z9BXuXTI6YSjep4I1o9hRE35JT-7sLGt8Z9GF01GhRc,9389
261
+ narwhals/_typing.py,sha256=eneOfgi2z_4rGbYnvT_IWmEyMgSUhWrTZ1kaGFWVLNQ,6497
262
+ narwhals/_typing_compat.py,sha256=h-BtLEl7CrZ-hYLlwYTOcCdsUS3dvgvkxQTcDQ7RYmA,2516
263
+ narwhals/_utils.py,sha256=0P_V4Avv5NdS5HSJg_8ECjzQiadLoSlyEdYU6ekiynU,73287
264
+ narwhals/compliant.py,sha256=MYzN7r6qgieJjw68g4I-HKXum0r_fhlf1vAlfRL47yk,920
265
+ narwhals/dataframe.py,sha256=ChwNNRfP78bDtQMlC6FP_Y0f869avDcRCHvAuWwBxq4,137172
266
+ narwhals/dependencies.py,sha256=ABk7GskzfO4JnEBoH4WotfEEYR3KylOqY8anDjt8140,19926
267
+ narwhals/dtypes.py,sha256=iFv3WabAXslxxDd3ZHshkbLXuTvKNFV4kY7EvoeFAcE,33117
268
+ narwhals/exceptions.py,sha256=97IIfR_YmJYZEb53uwoARpegXleq-Im3QMDjZs7thGo,3758
269
+ narwhals/expr.py,sha256=YB1pRIzmMsfZh3D9qW913EAo-LbQMeMoCn_jdx07Xns,110482
270
+ narwhals/expr_cat.py,sha256=Rfyy4Q_oyFmfz2enTebUY2MCQtwA8ZtBFmhUpQ295UU,1250
271
+ narwhals/expr_dt.py,sha256=FFPj3KcdgZrvv4M7-_IKPvivv5GZFTbjsnULxOB3_6Q,31816
272
+ narwhals/expr_list.py,sha256=K99FGLW9IYeK7NRiVKrICJ6NseQJl86YJcf47sfdHPw,14228
273
+ narwhals/expr_name.py,sha256=yhMal_7caymLduWhTs1NRYb5y35bincnoZK5gCQWX5U,4814
274
+ narwhals/expr_str.py,sha256=b45kQ86rDc5oBETxqw_QXKFEKRJ0E6X9DC40o8wgmic,25270
275
+ narwhals/expr_struct.py,sha256=9sHY743_UDsduwgUfip4X_xs-_A-aCHSVdlMsDk8WNA,1790
276
+ narwhals/functions.py,sha256=q4slLkkjBV-17bPPiTDStZi8TETJ7WrMHixtHM6KMgw,71617
277
+ narwhals/group_by.py,sha256=JLE0hEdi_-0dVAL_ayby7DqUUbxQjSMwBsIh0Cb0OtY,6632
278
+ narwhals/plugins.py,sha256=8ZIhps5rCUgf9ilwvmtgqO4sMOaSaRSekvixlLyzRxg,3878
279
+ narwhals/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
280
+ narwhals/schema.py,sha256=4yiRz6Qv373ATpN6kCFNSblUb4vMDX9USpKeJTDRrYI,12369
281
+ narwhals/selectors.py,sha256=Wig5bbVEE8IYYlErkH_xIeTykC6x7tDb1eXqUDlLfBc,10200
282
+ narwhals/series.py,sha256=ET5N0CkDXu4FdcMi7XKQbYPhRWPdAEMGgsNRVH6_grA,103178
283
+ narwhals/series_cat.py,sha256=mikr2q3S8kWo8uTJ4s2z6ZKv9cgn-jC1xNy_tYQaQyw,831
284
+ narwhals/series_dt.py,sha256=O3ZRXCPbwtQbcyqahyNBw3PMMhJAGMd732pSYjGaF4c,23051
285
+ narwhals/series_list.py,sha256=8QsdcP_HGrvcu-w-l_WT28o_tJ2_C7xKWaN5sCf9-_g,7954
286
+ narwhals/series_str.py,sha256=dPKgIEyb1BP6l1hW4Hl8RsngKPWayXcaWdamkbjuxU0,19378
287
+ narwhals/series_struct.py,sha256=bixxdASlxYyP1prDjMmfltVU5212a596VQZE11yszUg,930
288
+ narwhals/sql.py,sha256=MhWT4E3S4gV4fiQCmVlFd6k01irkF4aJhbpzOEdQIas,3767
289
+ narwhals/stable/__init__.py,sha256=WX57ijebHmAZMq_ngLYyOZFTxiBc99dnxldiXkBDccQ,95
290
+ narwhals/stable/__pycache__/__init__.cpython-312.pyc,,
291
+ narwhals/stable/v1/__init__.py,sha256=twpERqdSTJfqf0EC8gZ0kJrxVXRLuC3Z2BlkzgJXpUY,36571
292
+ narwhals/stable/v1/__pycache__/__init__.cpython-312.pyc,,
293
+ narwhals/stable/v1/__pycache__/_dtypes.cpython-312.pyc,,
294
+ narwhals/stable/v1/__pycache__/_namespace.cpython-312.pyc,,
295
+ narwhals/stable/v1/__pycache__/dependencies.cpython-312.pyc,,
296
+ narwhals/stable/v1/__pycache__/dtypes.cpython-312.pyc,,
297
+ narwhals/stable/v1/__pycache__/selectors.cpython-312.pyc,,
298
+ narwhals/stable/v1/__pycache__/typing.cpython-312.pyc,,
299
+ narwhals/stable/v1/_dtypes.py,sha256=ngGP8hQRdYv19GJgtynHPMEg-RUIDOs_jdbGrt5YO9E,2722
300
+ narwhals/stable/v1/_namespace.py,sha256=gfsbT4R4aLmmdArY35LRpEHPiUeZKEEnXGiY9ypFtwE,296
301
+ narwhals/stable/v1/dependencies.py,sha256=aM0IShF4hbaaMEDRJQXvsu4RABZOdBG4QhrpJPxb7fg,5001
302
+ narwhals/stable/v1/dtypes.py,sha256=u2NFDJyCkjsK6p3K9ULJS7CoG16z0Z1MQiACTVkhkH4,1082
303
+ narwhals/stable/v1/selectors.py,sha256=xEA9bBzkpTwUanGGoFwBCcHIAXb8alwrPX1mjzE9mDM,312
304
+ narwhals/stable/v1/typing.py,sha256=9YhcvKJ8jtN8mQBD0q12HShEM6Q-D10DYB-m4lQYzDM,4998
305
+ narwhals/stable/v2/__init__.py,sha256=7eG-5HA3p70dRpmNIG0SRk6A7bq9qahE9yOibwO2KmA,40312
306
+ narwhals/stable/v2/__pycache__/__init__.cpython-312.pyc,,
307
+ narwhals/stable/v2/__pycache__/_namespace.cpython-312.pyc,,
308
+ narwhals/stable/v2/__pycache__/dependencies.cpython-312.pyc,,
309
+ narwhals/stable/v2/__pycache__/dtypes.cpython-312.pyc,,
310
+ narwhals/stable/v2/__pycache__/selectors.cpython-312.pyc,,
311
+ narwhals/stable/v2/__pycache__/typing.cpython-312.pyc,,
312
+ narwhals/stable/v2/_namespace.py,sha256=oYB5nrFGxqqTonkRx9vUanyBxGs2Yb0j7_juMyvnvWA,296
313
+ narwhals/stable/v2/dependencies.py,sha256=vpYWx_dron6wFdbQ60G06EV2UJ_LMd52LDodCrAY5Jg,86
314
+ narwhals/stable/v2/dtypes.py,sha256=iMpk2Kc1mNiQYmboOSgmiAijklSUBHSHF2LTKMKnGe8,80
315
+ narwhals/stable/v2/selectors.py,sha256=sjJL3agHd8Rgf_lWhgCmEKruhWEkwHdX32-n85OqVJU,83
316
+ narwhals/stable/v2/typing.py,sha256=pAR_JL07FgNaLgCenpQVO3E0oFwYAi2wxCS2htgUJUs,2494
317
+ narwhals/testing/__init__.py,sha256=eCy8mtRcHySZiaWPV2r21DLZrznjtRQggj8ygoQms28,219
318
+ narwhals/testing/__pycache__/__init__.cpython-312.pyc,,
319
+ narwhals/testing/asserts/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
320
+ narwhals/testing/asserts/__pycache__/__init__.cpython-312.pyc,,
321
+ narwhals/testing/asserts/__pycache__/frame.cpython-312.pyc,,
322
+ narwhals/testing/asserts/__pycache__/series.cpython-312.pyc,,
323
+ narwhals/testing/asserts/__pycache__/utils.cpython-312.pyc,,
324
+ narwhals/testing/asserts/frame.py,sha256=SUNo7tFyLcXEyEKK1SHaPmM6O99YSpGYKNf5kY3Obm8,10511
325
+ narwhals/testing/asserts/series.py,sha256=MWhbghtXnT7GX8hsOS31TkoX0TpmkLmsFReaUaPR1F8,11118
326
+ narwhals/testing/asserts/utils.py,sha256=3VLqrRONh5e_-sQfhweOEr7gDjvZISq_o-XxGBn4mrU,2188
327
+ narwhals/this.py,sha256=BbKcj0ReWqE01lznzKjuqq7otXONvjBevWWC5aJhQxs,1584
328
+ narwhals/translate.py,sha256=YlS3UQWdU7JXbZq2ZcY1HVPBQLAKIMFhlY3AOQ_67cM,24169
329
+ narwhals/typing.py,sha256=2imWqcYKdpbSfjjNtwNSQ1Y_hm078_rre1cGX0ox3qg,13970
330
+ narwhals/utils.py,sha256=2GT3XxucWI6l9r9jTwMw7Aha2G73FsSXgXNFZ3O_ZyA,223
.venv_haddock/lib/python3.12/site-packages/narwhals-2.19.0.dist-info/WHEEL ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
.venv_haddock/lib/python3.12/site-packages/numpy/__init__.cython-30.pxd ADDED
@@ -0,0 +1,1242 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NumPy static imports for Cython >= 3.0
2
+ #
3
+ # If any of the PyArray_* functions are called, import_array must be
4
+ # called first. This is done automatically by Cython 3.0+ if a call
5
+ # is not detected inside of the module.
6
+ #
7
+ # Author: Dag Sverre Seljebotn
8
+ #
9
+
10
+ from cpython.ref cimport Py_INCREF
11
+ from cpython.object cimport PyObject, PyTypeObject, PyObject_TypeCheck
12
+ cimport libc.stdio as stdio
13
+
14
+
15
+ cdef extern from *:
16
+ # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython.
17
+ # See https://github.com/cython/cython/issues/3573
18
+ """
19
+ /* Using NumPy API declarations from "numpy/__init__.cython-30.pxd" */
20
+ """
21
+
22
+
23
+ cdef extern from "numpy/arrayobject.h":
24
+ # It would be nice to use size_t and ssize_t, but ssize_t has special
25
+ # implicit conversion rules, so just use "long".
26
+ # Note: The actual type only matters for Cython promotion, so long
27
+ # is closer than int, but could lead to incorrect promotion.
28
+ # (Not to worrying, and always the status-quo.)
29
+ ctypedef signed long npy_intp
30
+ ctypedef unsigned long npy_uintp
31
+
32
+ ctypedef unsigned char npy_bool
33
+
34
+ ctypedef signed char npy_byte
35
+ ctypedef signed short npy_short
36
+ ctypedef signed int npy_int
37
+ ctypedef signed long npy_long
38
+ ctypedef signed long long npy_longlong
39
+
40
+ ctypedef unsigned char npy_ubyte
41
+ ctypedef unsigned short npy_ushort
42
+ ctypedef unsigned int npy_uint
43
+ ctypedef unsigned long npy_ulong
44
+ ctypedef unsigned long long npy_ulonglong
45
+
46
+ ctypedef float npy_float
47
+ ctypedef double npy_double
48
+ ctypedef long double npy_longdouble
49
+
50
+ ctypedef signed char npy_int8
51
+ ctypedef signed short npy_int16
52
+ ctypedef signed int npy_int32
53
+ ctypedef signed long long npy_int64
54
+
55
+ ctypedef unsigned char npy_uint8
56
+ ctypedef unsigned short npy_uint16
57
+ ctypedef unsigned int npy_uint32
58
+ ctypedef unsigned long long npy_uint64
59
+
60
+ ctypedef float npy_float32
61
+ ctypedef double npy_float64
62
+ ctypedef long double npy_float80
63
+ ctypedef long double npy_float96
64
+ ctypedef long double npy_float128
65
+
66
+ ctypedef struct npy_cfloat:
67
+ pass
68
+
69
+ ctypedef struct npy_cdouble:
70
+ pass
71
+
72
+ ctypedef struct npy_clongdouble:
73
+ pass
74
+
75
+ ctypedef struct npy_complex64:
76
+ pass
77
+
78
+ ctypedef struct npy_complex128:
79
+ pass
80
+
81
+ ctypedef struct npy_complex160:
82
+ pass
83
+
84
+ ctypedef struct npy_complex192:
85
+ pass
86
+
87
+ ctypedef struct npy_complex256:
88
+ pass
89
+
90
+ ctypedef struct PyArray_Dims:
91
+ npy_intp *ptr
92
+ int len
93
+
94
+
95
+ cdef enum NPY_TYPES:
96
+ NPY_BOOL
97
+ NPY_BYTE
98
+ NPY_UBYTE
99
+ NPY_SHORT
100
+ NPY_USHORT
101
+ NPY_INT
102
+ NPY_UINT
103
+ NPY_LONG
104
+ NPY_ULONG
105
+ NPY_LONGLONG
106
+ NPY_ULONGLONG
107
+ NPY_FLOAT
108
+ NPY_DOUBLE
109
+ NPY_LONGDOUBLE
110
+ NPY_CFLOAT
111
+ NPY_CDOUBLE
112
+ NPY_CLONGDOUBLE
113
+ NPY_OBJECT
114
+ NPY_STRING
115
+ NPY_UNICODE
116
+ NPY_VSTRING
117
+ NPY_VOID
118
+ NPY_DATETIME
119
+ NPY_TIMEDELTA
120
+ NPY_NTYPES_LEGACY
121
+ NPY_NOTYPE
122
+
123
+ NPY_INT8
124
+ NPY_INT16
125
+ NPY_INT32
126
+ NPY_INT64
127
+ NPY_UINT8
128
+ NPY_UINT16
129
+ NPY_UINT32
130
+ NPY_UINT64
131
+ NPY_FLOAT16
132
+ NPY_FLOAT32
133
+ NPY_FLOAT64
134
+ NPY_FLOAT80
135
+ NPY_FLOAT96
136
+ NPY_FLOAT128
137
+ NPY_COMPLEX64
138
+ NPY_COMPLEX128
139
+ NPY_COMPLEX160
140
+ NPY_COMPLEX192
141
+ NPY_COMPLEX256
142
+
143
+ NPY_INTP
144
+ NPY_UINTP
145
+ NPY_DEFAULT_INT # Not a compile time constant (normally)!
146
+
147
+ ctypedef enum NPY_ORDER:
148
+ NPY_ANYORDER
149
+ NPY_CORDER
150
+ NPY_FORTRANORDER
151
+ NPY_KEEPORDER
152
+
153
+ ctypedef enum NPY_CASTING:
154
+ NPY_NO_CASTING
155
+ NPY_EQUIV_CASTING
156
+ NPY_SAFE_CASTING
157
+ NPY_SAME_KIND_CASTING
158
+ NPY_UNSAFE_CASTING
159
+ NPY_SAME_VALUE_CASTING
160
+
161
+ ctypedef enum NPY_CLIPMODE:
162
+ NPY_CLIP
163
+ NPY_WRAP
164
+ NPY_RAISE
165
+
166
+ ctypedef enum NPY_SCALARKIND:
167
+ NPY_NOSCALAR,
168
+ NPY_BOOL_SCALAR,
169
+ NPY_INTPOS_SCALAR,
170
+ NPY_INTNEG_SCALAR,
171
+ NPY_FLOAT_SCALAR,
172
+ NPY_COMPLEX_SCALAR,
173
+ NPY_OBJECT_SCALAR
174
+
175
+ ctypedef enum NPY_SORTKIND:
176
+ NPY_QUICKSORT
177
+ NPY_HEAPSORT
178
+ NPY_MERGESORT
179
+
180
+ ctypedef enum NPY_SEARCHSIDE:
181
+ NPY_SEARCHLEFT
182
+ NPY_SEARCHRIGHT
183
+
184
+ enum:
185
+ NPY_ARRAY_C_CONTIGUOUS
186
+ NPY_ARRAY_F_CONTIGUOUS
187
+ NPY_ARRAY_OWNDATA
188
+ NPY_ARRAY_FORCECAST
189
+ NPY_ARRAY_ENSURECOPY
190
+ NPY_ARRAY_ENSUREARRAY
191
+ NPY_ARRAY_ELEMENTSTRIDES
192
+ NPY_ARRAY_ALIGNED
193
+ NPY_ARRAY_NOTSWAPPED
194
+ NPY_ARRAY_WRITEABLE
195
+ NPY_ARRAY_WRITEBACKIFCOPY
196
+
197
+ NPY_ARRAY_BEHAVED
198
+ NPY_ARRAY_BEHAVED_NS
199
+ NPY_ARRAY_CARRAY
200
+ NPY_ARRAY_CARRAY_RO
201
+ NPY_ARRAY_FARRAY
202
+ NPY_ARRAY_FARRAY_RO
203
+ NPY_ARRAY_DEFAULT
204
+
205
+ NPY_ARRAY_IN_ARRAY
206
+ NPY_ARRAY_OUT_ARRAY
207
+ NPY_ARRAY_INOUT_ARRAY
208
+ NPY_ARRAY_IN_FARRAY
209
+ NPY_ARRAY_OUT_FARRAY
210
+ NPY_ARRAY_INOUT_FARRAY
211
+
212
+ NPY_ARRAY_UPDATE_ALL
213
+
214
+ cdef enum:
215
+ NPY_MAXDIMS # 64 on NumPy 2.x and 32 on NumPy 1.x
216
+ NPY_RAVEL_AXIS # Used for functions like PyArray_Mean
217
+
218
+ ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
219
+
220
+ ctypedef struct PyArray_ArrayDescr:
221
+ # shape is a tuple, but Cython doesn't support "tuple shape"
222
+ # inside a non-PyObject declaration, so we have to declare it
223
+ # as just a PyObject*.
224
+ PyObject* shape
225
+
226
+ ctypedef struct PyArray_Descr:
227
+ pass
228
+
229
+ ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
230
+ # Use PyDataType_* macros when possible, however there are no macros
231
+ # for accessing some of the fields, so some are defined.
232
+ cdef PyTypeObject* typeobj
233
+ cdef char kind
234
+ cdef char type
235
+ # Numpy sometimes mutates this without warning (e.g. it'll
236
+ # sometimes change "|" to "<" in shared dtype objects on
237
+ # little-endian machines). If this matters to you, use
238
+ # PyArray_IsNativeByteOrder(dtype.byteorder) instead of
239
+ # directly accessing this field.
240
+ cdef char byteorder
241
+ cdef int type_num
242
+
243
+ @property
244
+ cdef inline npy_intp itemsize(self) noexcept nogil:
245
+ return PyDataType_ELSIZE(self)
246
+
247
+ @property
248
+ cdef inline npy_intp alignment(self) noexcept nogil:
249
+ return PyDataType_ALIGNMENT(self)
250
+
251
+ # Use fields/names with care as they may be NULL. You must check
252
+ # for this using PyDataType_HASFIELDS.
253
+ @property
254
+ cdef inline object fields(self):
255
+ return <object>PyDataType_FIELDS(self)
256
+
257
+ @property
258
+ cdef inline tuple names(self):
259
+ return <tuple>PyDataType_NAMES(self)
260
+
261
+ # Use PyDataType_HASSUBARRAY to test whether this field is
262
+ # valid (the pointer can be NULL). Most users should access
263
+ # this field via the inline helper method PyDataType_SHAPE.
264
+ @property
265
+ cdef inline PyArray_ArrayDescr* subarray(self) noexcept nogil:
266
+ return PyDataType_SUBARRAY(self)
267
+
268
+ @property
269
+ cdef inline npy_uint64 flags(self) noexcept nogil:
270
+ """The data types flags."""
271
+ return PyDataType_FLAGS(self)
272
+
273
+
274
+ ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
275
+ # Use through macros
276
+ pass
277
+
278
+ ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
279
+
280
+ @property
281
+ cdef inline int numiter(self) noexcept nogil:
282
+ """The number of arrays that need to be broadcast to the same shape."""
283
+ return PyArray_MultiIter_NUMITER(self)
284
+
285
+ @property
286
+ cdef inline npy_intp size(self) noexcept nogil:
287
+ """The total broadcasted size."""
288
+ return PyArray_MultiIter_SIZE(self)
289
+
290
+ @property
291
+ cdef inline npy_intp index(self) noexcept nogil:
292
+ """The current (1-d) index into the broadcasted result."""
293
+ return PyArray_MultiIter_INDEX(self)
294
+
295
+ @property
296
+ cdef inline int nd(self) noexcept nogil:
297
+ """The number of dimensions in the broadcasted result."""
298
+ return PyArray_MultiIter_NDIM(self)
299
+
300
+ @property
301
+ cdef inline npy_intp* dimensions(self) noexcept nogil:
302
+ """The shape of the broadcasted result."""
303
+ return PyArray_MultiIter_DIMS(self)
304
+
305
+ @property
306
+ cdef inline void** iters(self) noexcept nogil:
307
+ """An array of iterator objects that holds the iterators for the arrays to be broadcast together.
308
+ On return, the iterators are adjusted for broadcasting."""
309
+ return PyArray_MultiIter_ITERS(self)
310
+
311
+
312
+ ctypedef struct PyArrayObject:
313
+ # For use in situations where ndarray can't replace PyArrayObject*,
314
+ # like PyArrayObject**.
315
+ pass
316
+
317
+ ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
318
+ cdef __cythonbufferdefaults__ = {"mode": "strided"}
319
+
320
+ # NOTE: no field declarations since direct access is deprecated since NumPy 1.7
321
+ # Instead, we use properties that map to the corresponding C-API functions.
322
+
323
+ @property
324
+ cdef inline PyObject* base(self) noexcept nogil:
325
+ """Returns a borrowed reference to the object owning the data/memory.
326
+ """
327
+ return PyArray_BASE(self)
328
+
329
+ @property
330
+ cdef inline dtype descr(self):
331
+ """Returns an owned reference to the dtype of the array.
332
+ """
333
+ return <dtype>PyArray_DESCR(self)
334
+
335
+ @property
336
+ cdef inline int ndim(self) noexcept nogil:
337
+ """Returns the number of dimensions in the array.
338
+ """
339
+ return PyArray_NDIM(self)
340
+
341
+ @property
342
+ cdef inline npy_intp *shape(self) noexcept nogil:
343
+ """Returns a pointer to the dimensions/shape of the array.
344
+ The number of elements matches the number of dimensions of the array (ndim).
345
+ Can return NULL for 0-dimensional arrays.
346
+ """
347
+ return PyArray_DIMS(self)
348
+
349
+ @property
350
+ cdef inline npy_intp *strides(self) noexcept nogil:
351
+ """Returns a pointer to the strides of the array.
352
+ The number of elements matches the number of dimensions of the array (ndim).
353
+ """
354
+ return PyArray_STRIDES(self)
355
+
356
+ @property
357
+ cdef inline npy_intp size(self) noexcept nogil:
358
+ """Returns the total size (in number of elements) of the array.
359
+ """
360
+ return PyArray_SIZE(self)
361
+
362
+ @property
363
+ cdef inline char* data(self) noexcept nogil:
364
+ """The pointer to the data buffer as a char*.
365
+ This is provided for legacy reasons to avoid direct struct field access.
366
+ For new code that needs this access, you probably want to cast the result
367
+ of `PyArray_DATA()` instead, which returns a 'void*'.
368
+ """
369
+ return PyArray_BYTES(self)
370
+
371
+
372
+ int _import_array() except -1
373
+ # A second definition so _import_array isn't marked as used when we use it here.
374
+ # Do not use - subject to change any time.
375
+ int __pyx_import_array "_import_array"() except -1
376
+
377
+ #
378
+ # Macros from ndarrayobject.h
379
+ #
380
+ bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
381
+ bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
382
+ bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
383
+ bint PyArray_ISCONTIGUOUS(ndarray m) nogil
384
+ bint PyArray_ISWRITEABLE(ndarray m) nogil
385
+ bint PyArray_ISALIGNED(ndarray m) nogil
386
+
387
+ int PyArray_NDIM(ndarray) nogil
388
+ bint PyArray_ISONESEGMENT(ndarray) nogil
389
+ bint PyArray_ISFORTRAN(ndarray) nogil
390
+ int PyArray_FORTRANIF(ndarray) nogil
391
+
392
+ void* PyArray_DATA(ndarray) nogil
393
+ char* PyArray_BYTES(ndarray) nogil
394
+
395
+ npy_intp* PyArray_DIMS(ndarray) nogil
396
+ npy_intp* PyArray_STRIDES(ndarray) nogil
397
+ npy_intp PyArray_DIM(ndarray, size_t) nogil
398
+ npy_intp PyArray_STRIDE(ndarray, size_t) nogil
399
+
400
+ PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference!
401
+ PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype!
402
+ PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr.
403
+ int PyArray_FLAGS(ndarray) nogil
404
+ void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
405
+ void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
406
+ npy_intp PyArray_ITEMSIZE(ndarray) nogil
407
+ int PyArray_TYPE(ndarray arr) nogil
408
+
409
+ object PyArray_GETITEM(ndarray arr, void *itemptr)
410
+ int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1
411
+
412
+ bint PyTypeNum_ISBOOL(int) nogil
413
+ bint PyTypeNum_ISUNSIGNED(int) nogil
414
+ bint PyTypeNum_ISSIGNED(int) nogil
415
+ bint PyTypeNum_ISINTEGER(int) nogil
416
+ bint PyTypeNum_ISFLOAT(int) nogil
417
+ bint PyTypeNum_ISNUMBER(int) nogil
418
+ bint PyTypeNum_ISSTRING(int) nogil
419
+ bint PyTypeNum_ISCOMPLEX(int) nogil
420
+ bint PyTypeNum_ISFLEXIBLE(int) nogil
421
+ bint PyTypeNum_ISUSERDEF(int) nogil
422
+ bint PyTypeNum_ISEXTENDED(int) nogil
423
+ bint PyTypeNum_ISOBJECT(int) nogil
424
+
425
+ npy_intp PyDataType_ELSIZE(dtype) nogil
426
+ npy_intp PyDataType_ALIGNMENT(dtype) nogil
427
+ PyObject* PyDataType_METADATA(dtype) nogil
428
+ PyArray_ArrayDescr* PyDataType_SUBARRAY(dtype) nogil
429
+ PyObject* PyDataType_NAMES(dtype) nogil
430
+ PyObject* PyDataType_FIELDS(dtype) nogil
431
+
432
+ bint PyDataType_ISBOOL(dtype) nogil
433
+ bint PyDataType_ISUNSIGNED(dtype) nogil
434
+ bint PyDataType_ISSIGNED(dtype) nogil
435
+ bint PyDataType_ISINTEGER(dtype) nogil
436
+ bint PyDataType_ISFLOAT(dtype) nogil
437
+ bint PyDataType_ISNUMBER(dtype) nogil
438
+ bint PyDataType_ISSTRING(dtype) nogil
439
+ bint PyDataType_ISCOMPLEX(dtype) nogil
440
+ bint PyDataType_ISFLEXIBLE(dtype) nogil
441
+ bint PyDataType_ISUSERDEF(dtype) nogil
442
+ bint PyDataType_ISEXTENDED(dtype) nogil
443
+ bint PyDataType_ISOBJECT(dtype) nogil
444
+ bint PyDataType_HASFIELDS(dtype) nogil
445
+ bint PyDataType_HASSUBARRAY(dtype) nogil
446
+ npy_uint64 PyDataType_FLAGS(dtype) nogil
447
+
448
+ bint PyArray_ISBOOL(ndarray) nogil
449
+ bint PyArray_ISUNSIGNED(ndarray) nogil
450
+ bint PyArray_ISSIGNED(ndarray) nogil
451
+ bint PyArray_ISINTEGER(ndarray) nogil
452
+ bint PyArray_ISFLOAT(ndarray) nogil
453
+ bint PyArray_ISNUMBER(ndarray) nogil
454
+ bint PyArray_ISSTRING(ndarray) nogil
455
+ bint PyArray_ISCOMPLEX(ndarray) nogil
456
+ bint PyArray_ISFLEXIBLE(ndarray) nogil
457
+ bint PyArray_ISUSERDEF(ndarray) nogil
458
+ bint PyArray_ISEXTENDED(ndarray) nogil
459
+ bint PyArray_ISOBJECT(ndarray) nogil
460
+ bint PyArray_HASFIELDS(ndarray) nogil
461
+
462
+ bint PyArray_ISVARIABLE(ndarray) nogil
463
+
464
+ bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil
465
+ bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder
466
+ bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder
467
+ bint PyArray_ISNOTSWAPPED(ndarray) nogil
468
+ bint PyArray_ISBYTESWAPPED(ndarray) nogil
469
+
470
+ bint PyArray_FLAGSWAP(ndarray, int) nogil
471
+
472
+ bint PyArray_ISCARRAY(ndarray) nogil
473
+ bint PyArray_ISCARRAY_RO(ndarray) nogil
474
+ bint PyArray_ISFARRAY(ndarray) nogil
475
+ bint PyArray_ISFARRAY_RO(ndarray) nogil
476
+ bint PyArray_ISBEHAVED(ndarray) nogil
477
+ bint PyArray_ISBEHAVED_RO(ndarray) nogil
478
+
479
+
480
+ bint PyDataType_ISNOTSWAPPED(dtype) nogil
481
+ bint PyDataType_ISBYTESWAPPED(dtype) nogil
482
+
483
+ bint PyArray_DescrCheck(object)
484
+
485
+ bint PyArray_Check(object)
486
+ bint PyArray_CheckExact(object)
487
+
488
+ # Cannot be supported due to out arg:
489
+ # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&)
490
+ # bint PyArray_HasArrayInterface(op, out)
491
+
492
+
493
+ bint PyArray_IsZeroDim(object)
494
+ # Cannot be supported due to ## ## in macro:
495
+ # bint PyArray_IsScalar(object, verbatim work)
496
+ bint PyArray_CheckScalar(object)
497
+ bint PyArray_IsPythonNumber(object)
498
+ bint PyArray_IsPythonScalar(object)
499
+ bint PyArray_IsAnyScalar(object)
500
+ bint PyArray_CheckAnyScalar(object)
501
+
502
+ ndarray PyArray_GETCONTIGUOUS(ndarray)
503
+ bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
504
+ npy_intp PyArray_SIZE(ndarray) nogil
505
+ npy_intp PyArray_NBYTES(ndarray) nogil
506
+
507
+ object PyArray_FROM_O(object)
508
+ object PyArray_FROM_OF(object m, int flags)
509
+ object PyArray_FROM_OT(object m, int type)
510
+ object PyArray_FROM_OTF(object m, int type, int flags)
511
+ object PyArray_FROMANY(object m, int type, int min, int max, int flags)
512
+ object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
513
+ object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
514
+ void PyArray_FILLWBYTE(ndarray, int val)
515
+ object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
516
+ unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
517
+ bint PyArray_EquivByteorders(int b1, int b2) nogil
518
+ object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
519
+ object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
520
+ #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr)
521
+ object PyArray_ToScalar(void* data, ndarray arr)
522
+
523
+ void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
524
+ void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
525
+ void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
526
+ void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
527
+
528
+ # Cannot be supported due to out arg
529
+ # void PyArray_DESCR_REPLACE(descr)
530
+
531
+
532
+ object PyArray_Copy(ndarray)
533
+ object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
534
+ object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
535
+ object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
536
+
537
+ object PyArray_Cast(ndarray mp, int type_num)
538
+ object PyArray_Take(ndarray ap, object items, int axis)
539
+ object PyArray_Put(ndarray ap, object items, object values)
540
+
541
+ void PyArray_ITER_RESET(flatiter it) nogil
542
+ void PyArray_ITER_NEXT(flatiter it) nogil
543
+ void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
544
+ void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
545
+ void* PyArray_ITER_DATA(flatiter it) nogil
546
+ bint PyArray_ITER_NOTDONE(flatiter it) nogil
547
+
548
+ void PyArray_MultiIter_RESET(broadcast multi) nogil
549
+ void PyArray_MultiIter_NEXT(broadcast multi) nogil
550
+ void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
551
+ void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
552
+ void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
553
+ void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
554
+ bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
555
+ npy_intp PyArray_MultiIter_SIZE(broadcast multi) nogil
556
+ int PyArray_MultiIter_NDIM(broadcast multi) nogil
557
+ npy_intp PyArray_MultiIter_INDEX(broadcast multi) nogil
558
+ int PyArray_MultiIter_NUMITER(broadcast multi) nogil
559
+ npy_intp* PyArray_MultiIter_DIMS(broadcast multi) nogil
560
+ void** PyArray_MultiIter_ITERS(broadcast multi) nogil
561
+
562
+ # Functions from __multiarray_api.h
563
+
564
+ # Functions taking dtype and returning object/ndarray are disabled
565
+ # for now as they steal dtype references. I'm conservative and disable
566
+ # more than is probably needed until it can be checked further.
567
+ int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF...
568
+ int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF...
569
+ dtype PyArray_DescrFromType (int)
570
+ object PyArray_TypeObjectFromType (int)
571
+ char * PyArray_Zero (ndarray)
572
+ char * PyArray_One (ndarray)
573
+ #object PyArray_CastToType (ndarray, dtype, int)
574
+ int PyArray_CanCastSafely (int, int) # writes errors
575
+ npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors
576
+ int PyArray_ObjectType (object, int) except 0
577
+ dtype PyArray_DescrFromObject (object, dtype)
578
+ #ndarray* PyArray_ConvertToCommonType (object, int *)
579
+ dtype PyArray_DescrFromScalar (object)
580
+ dtype PyArray_DescrFromTypeObject (object)
581
+ npy_intp PyArray_Size (object)
582
+ #object PyArray_Scalar (void *, dtype, object)
583
+ #object PyArray_FromScalar (object, dtype)
584
+ void PyArray_ScalarAsCtype (object, void *)
585
+ #int PyArray_CastScalarToCtype (object, void *, dtype)
586
+ #int PyArray_CastScalarDirect (object, dtype, void *, int)
587
+ #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int)
588
+ #object PyArray_FromAny (object, dtype, int, int, int, object)
589
+ object PyArray_EnsureArray (object)
590
+ object PyArray_EnsureAnyArray (object)
591
+ #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *)
592
+ #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *)
593
+ #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp)
594
+ #object PyArray_FromIter (object, dtype, npy_intp)
595
+ object PyArray_Return (ndarray)
596
+ #object PyArray_GetField (ndarray, dtype, int)
597
+ #int PyArray_SetField (ndarray, dtype, int, object) except -1
598
+ object PyArray_Byteswap (ndarray, npy_bool)
599
+ object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
600
+ int PyArray_CopyInto (ndarray, ndarray) except -1
601
+ int PyArray_CopyAnyInto (ndarray, ndarray) except -1
602
+ int PyArray_CopyObject (ndarray, object) except -1
603
+ object PyArray_NewCopy (ndarray, NPY_ORDER)
604
+ object PyArray_ToList (ndarray)
605
+ object PyArray_ToString (ndarray, NPY_ORDER)
606
+ int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1
607
+ int PyArray_Dump (object, object, int) except -1
608
+ object PyArray_Dumps (object, int)
609
+ int PyArray_ValidType (int) # Cannot error
610
+ void PyArray_UpdateFlags (ndarray, int)
611
+ object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
612
+ #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object)
613
+ #dtype PyArray_DescrNew (dtype)
614
+ dtype PyArray_DescrNewFromType (int)
615
+ double PyArray_GetPriority (object, double) # clears errors as of 1.25
616
+ object PyArray_IterNew (object)
617
+ object PyArray_MultiIterNew (int, ...)
618
+
619
+ int PyArray_PyIntAsInt (object) except? -1
620
+ npy_intp PyArray_PyIntAsIntp (object)
621
+ int PyArray_Broadcast (broadcast) except -1
622
+ int PyArray_FillWithScalar (ndarray, object) except -1
623
+ npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
624
+ dtype PyArray_DescrNewByteorder (dtype, char)
625
+ object PyArray_IterAllButAxis (object, int *)
626
+ #object PyArray_CheckFromAny (object, dtype, int, int, int, object)
627
+ #object PyArray_FromArray (ndarray, dtype, int)
628
+ object PyArray_FromInterface (object)
629
+ object PyArray_FromStructInterface (object)
630
+ #object PyArray_FromArrayAttr (object, dtype, object)
631
+ #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*)
632
+ int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
633
+ npy_bool PyArray_CanCastScalar (type, type)
634
+ int PyArray_RemoveSmallest (broadcast) except -1
635
+ int PyArray_ElementStrides (object)
636
+ void PyArray_Item_INCREF (char *, dtype) except *
637
+ void PyArray_Item_XDECREF (char *, dtype) except *
638
+ object PyArray_Transpose (ndarray, PyArray_Dims *)
639
+ object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
640
+ object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
641
+ object PyArray_PutMask (ndarray, object, object)
642
+ object PyArray_Repeat (ndarray, object, int)
643
+ object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
644
+ int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1
645
+ object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
646
+ object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *)
647
+ object PyArray_ArgMax (ndarray, int, ndarray)
648
+ object PyArray_ArgMin (ndarray, int, ndarray)
649
+ object PyArray_Reshape (ndarray, object)
650
+ object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
651
+ object PyArray_Squeeze (ndarray)
652
+ #object PyArray_View (ndarray, dtype, type)
653
+ object PyArray_SwapAxes (ndarray, int, int)
654
+ object PyArray_Max (ndarray, int, ndarray)
655
+ object PyArray_Min (ndarray, int, ndarray)
656
+ object PyArray_Ptp (ndarray, int, ndarray)
657
+ object PyArray_Mean (ndarray, int, int, ndarray)
658
+ object PyArray_Trace (ndarray, int, int, int, int, ndarray)
659
+ object PyArray_Diagonal (ndarray, int, int, int)
660
+ object PyArray_Clip (ndarray, object, object, ndarray)
661
+ object PyArray_Conjugate (ndarray, ndarray)
662
+ object PyArray_Nonzero (ndarray)
663
+ object PyArray_Std (ndarray, int, int, ndarray, int)
664
+ object PyArray_Sum (ndarray, int, int, ndarray)
665
+ object PyArray_CumSum (ndarray, int, int, ndarray)
666
+ object PyArray_Prod (ndarray, int, int, ndarray)
667
+ object PyArray_CumProd (ndarray, int, int, ndarray)
668
+ object PyArray_All (ndarray, int, ndarray)
669
+ object PyArray_Any (ndarray, int, ndarray)
670
+ object PyArray_Compress (ndarray, object, int, ndarray)
671
+ object PyArray_Flatten (ndarray, NPY_ORDER)
672
+ object PyArray_Ravel (ndarray, NPY_ORDER)
673
+ npy_intp PyArray_MultiplyList (npy_intp *, int)
674
+ int PyArray_MultiplyIntList (int *, int)
675
+ void * PyArray_GetPtr (ndarray, npy_intp*)
676
+ int PyArray_CompareLists (npy_intp *, npy_intp *, int)
677
+ #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype)
678
+ int PyArray_Free (object, void *)
679
+ #int PyArray_Converter (object, object*)
680
+ int PyArray_IntpFromSequence (object, npy_intp *, int) except -1
681
+ object PyArray_Concatenate (object, int)
682
+ object PyArray_InnerProduct (object, object)
683
+ object PyArray_MatrixProduct (object, object)
684
+ object PyArray_Correlate (object, object, int)
685
+ #int PyArray_DescrConverter (object, dtype*) except 0
686
+ #int PyArray_DescrConverter2 (object, dtype*) except 0
687
+ int PyArray_IntpConverter (object, PyArray_Dims *) except 0
688
+ #int PyArray_BufferConverter (object, chunk) except 0
689
+ int PyArray_AxisConverter (object, int *) except 0
690
+ int PyArray_BoolConverter (object, npy_bool *) except 0
691
+ int PyArray_ByteorderConverter (object, char *) except 0
692
+ int PyArray_OrderConverter (object, NPY_ORDER *) except 0
693
+ unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors
694
+ #object PyArray_Zeros (int, npy_intp *, dtype, int)
695
+ #object PyArray_Empty (int, npy_intp *, dtype, int)
696
+ object PyArray_Where (object, object, object)
697
+ object PyArray_Arange (double, double, double, int)
698
+ #object PyArray_ArangeObj (object, object, object, dtype)
699
+ int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0
700
+ object PyArray_LexSort (object, int)
701
+ object PyArray_Round (ndarray, int, ndarray)
702
+ unsigned char PyArray_EquivTypenums (int, int)
703
+ int PyArray_RegisterDataType (dtype) except -1
704
+ int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1
705
+ int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1
706
+ #void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
707
+ object PyArray_IntTupleFromIntp (int, npy_intp *)
708
+ int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0
709
+ #int PyArray_OutputConverter (object, ndarray*) except 0
710
+ object PyArray_BroadcastToShape (object, npy_intp *, int)
711
+ #int PyArray_DescrAlignConverter (object, dtype*) except 0
712
+ #int PyArray_DescrAlignConverter2 (object, dtype*) except 0
713
+ int PyArray_SearchsideConverter (object, void *) except 0
714
+ object PyArray_CheckAxis (ndarray, int *, int)
715
+ npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
716
+ int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead.
717
+
718
+ # The memory handler functions require the NumPy 1.22 API
719
+ # and may require defining NPY_TARGET_VERSION
720
+ ctypedef struct PyDataMemAllocator:
721
+ void *ctx
722
+ void* (*malloc) (void *ctx, size_t size)
723
+ void* (*calloc) (void *ctx, size_t nelem, size_t elsize)
724
+ void* (*realloc) (void *ctx, void *ptr, size_t new_size)
725
+ void (*free) (void *ctx, void *ptr, size_t size)
726
+
727
+ ctypedef struct PyDataMem_Handler:
728
+ char* name
729
+ npy_uint8 version
730
+ PyDataMemAllocator allocator
731
+
732
+ object PyDataMem_SetHandler(object handler)
733
+ object PyDataMem_GetHandler()
734
+
735
+ # additional datetime related functions are defined below
736
+
737
+
738
+ # Typedefs that matches the runtime dtype objects in
739
+ # the numpy module.
740
+
741
+ # The ones that are commented out needs an IFDEF function
742
+ # in Cython to enable them only on the right systems.
743
+
744
+ ctypedef npy_int8 int8_t
745
+ ctypedef npy_int16 int16_t
746
+ ctypedef npy_int32 int32_t
747
+ ctypedef npy_int64 int64_t
748
+
749
+ ctypedef npy_uint8 uint8_t
750
+ ctypedef npy_uint16 uint16_t
751
+ ctypedef npy_uint32 uint32_t
752
+ ctypedef npy_uint64 uint64_t
753
+
754
+ ctypedef npy_float32 float32_t
755
+ ctypedef npy_float64 float64_t
756
+ #ctypedef npy_float80 float80_t
757
+ #ctypedef npy_float128 float128_t
758
+
759
+ ctypedef float complex complex64_t
760
+ ctypedef double complex complex128_t
761
+
762
+ ctypedef npy_longlong longlong_t
763
+ ctypedef npy_ulonglong ulonglong_t
764
+
765
+ ctypedef npy_intp intp_t
766
+ ctypedef npy_uintp uintp_t
767
+
768
+ ctypedef npy_double float_t
769
+ ctypedef npy_double double_t
770
+ ctypedef npy_longdouble longdouble_t
771
+
772
+ ctypedef float complex cfloat_t
773
+ ctypedef double complex cdouble_t
774
+ ctypedef double complex complex_t
775
+ ctypedef long double complex clongdouble_t
776
+
777
+ cdef inline object PyArray_MultiIterNew1(a):
778
+ return PyArray_MultiIterNew(1, <void*>a)
779
+
780
+ cdef inline object PyArray_MultiIterNew2(a, b):
781
+ return PyArray_MultiIterNew(2, <void*>a, <void*>b)
782
+
783
+ cdef inline object PyArray_MultiIterNew3(a, b, c):
784
+ return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
785
+
786
+ cdef inline object PyArray_MultiIterNew4(a, b, c, d):
787
+ return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
788
+
789
+ cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
790
+ return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
791
+
792
+ cdef inline tuple PyDataType_SHAPE(dtype d):
793
+ if PyDataType_HASSUBARRAY(d):
794
+ return <tuple>d.subarray.shape
795
+ else:
796
+ return ()
797
+
798
+
799
+ cdef extern from "numpy/ndarrayobject.h":
800
+ PyTypeObject PyTimedeltaArrType_Type
801
+ PyTypeObject PyDatetimeArrType_Type
802
+ ctypedef int64_t npy_timedelta
803
+ ctypedef int64_t npy_datetime
804
+
805
+ cdef extern from "numpy/ndarraytypes.h":
806
+ ctypedef struct PyArray_DatetimeMetaData:
807
+ NPY_DATETIMEUNIT base
808
+ int64_t num
809
+
810
+ ctypedef struct npy_datetimestruct:
811
+ int64_t year
812
+ int32_t month, day, hour, min, sec, us, ps, as
813
+
814
+ # Iterator API added in v1.6
815
+ #
816
+ # These don't match the definition in the C API because Cython can't wrap
817
+ # function pointers that return functions.
818
+ # https://github.com/cython/cython/issues/6720
819
+ ctypedef int (*NpyIter_IterNextFunc "NpyIter_IterNextFunc *")(NpyIter* it) noexcept nogil
820
+ ctypedef void (*NpyIter_GetMultiIndexFunc "NpyIter_GetMultiIndexFunc *")(NpyIter* it, npy_intp* outcoords) noexcept nogil
821
+
822
+
823
+ cdef extern from "numpy/arrayscalars.h":
824
+
825
+ # abstract types
826
+ ctypedef class numpy.generic [object PyObject]:
827
+ pass
828
+ ctypedef class numpy.number [object PyObject]:
829
+ pass
830
+ ctypedef class numpy.integer [object PyObject]:
831
+ pass
832
+ ctypedef class numpy.signedinteger [object PyObject]:
833
+ pass
834
+ ctypedef class numpy.unsignedinteger [object PyObject]:
835
+ pass
836
+ ctypedef class numpy.inexact [object PyObject]:
837
+ pass
838
+ ctypedef class numpy.floating [object PyObject]:
839
+ pass
840
+ ctypedef class numpy.complexfloating [object PyObject]:
841
+ pass
842
+ ctypedef class numpy.flexible [object PyObject]:
843
+ pass
844
+ ctypedef class numpy.character [object PyObject]:
845
+ pass
846
+
847
+ ctypedef struct PyDatetimeScalarObject:
848
+ # PyObject_HEAD
849
+ npy_datetime obval
850
+ PyArray_DatetimeMetaData obmeta
851
+
852
+ ctypedef struct PyTimedeltaScalarObject:
853
+ # PyObject_HEAD
854
+ npy_timedelta obval
855
+ PyArray_DatetimeMetaData obmeta
856
+
857
+ ctypedef enum NPY_DATETIMEUNIT:
858
+ NPY_FR_Y
859
+ NPY_FR_M
860
+ NPY_FR_W
861
+ NPY_FR_D
862
+ NPY_FR_B
863
+ NPY_FR_h
864
+ NPY_FR_m
865
+ NPY_FR_s
866
+ NPY_FR_ms
867
+ NPY_FR_us
868
+ NPY_FR_ns
869
+ NPY_FR_ps
870
+ NPY_FR_fs
871
+ NPY_FR_as
872
+ NPY_FR_GENERIC
873
+
874
+
875
+ cdef extern from "numpy/arrayobject.h":
876
+ # These are part of the C-API defined in `__multiarray_api.h`
877
+
878
+ # NumPy internal definitions in datetime_strings.c:
879
+ int get_datetime_iso_8601_strlen "NpyDatetime_GetDatetimeISO8601StrLen" (
880
+ int local, NPY_DATETIMEUNIT base)
881
+ int make_iso_8601_datetime "NpyDatetime_MakeISO8601Datetime" (
882
+ npy_datetimestruct *dts, char *outstr, npy_intp outlen,
883
+ int local, int utc, NPY_DATETIMEUNIT base, int tzoffset,
884
+ NPY_CASTING casting) except -1
885
+
886
+ # NumPy internal definition in datetime.c:
887
+ # May return 1 to indicate that object does not appear to be a datetime
888
+ # (returns 0 on success).
889
+ int convert_pydatetime_to_datetimestruct "NpyDatetime_ConvertPyDateTimeToDatetimeStruct" (
890
+ PyObject *obj, npy_datetimestruct *out,
891
+ NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) except -1
892
+ int convert_datetime64_to_datetimestruct "NpyDatetime_ConvertDatetime64ToDatetimeStruct" (
893
+ PyArray_DatetimeMetaData *meta, npy_datetime dt,
894
+ npy_datetimestruct *out) except -1
895
+ int convert_datetimestruct_to_datetime64 "NpyDatetime_ConvertDatetimeStructToDatetime64"(
896
+ PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts,
897
+ npy_datetime *out) except -1
898
+
899
+
900
+ #
901
+ # ufunc API
902
+ #
903
+
904
+ cdef extern from "numpy/ufuncobject.h":
905
+
906
+ ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
907
+
908
+ ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
909
+ cdef:
910
+ int nin, nout, nargs
911
+ int identity
912
+ PyUFuncGenericFunction *functions
913
+ void **data
914
+ int ntypes
915
+ int check_return
916
+ char *name
917
+ char *types
918
+ char *doc
919
+ void *ptr
920
+ PyObject *obj
921
+ PyObject *userloops
922
+
923
+ cdef enum:
924
+ PyUFunc_Zero
925
+ PyUFunc_One
926
+ PyUFunc_None
927
+ # deprecated
928
+ UFUNC_FPE_DIVIDEBYZERO
929
+ UFUNC_FPE_OVERFLOW
930
+ UFUNC_FPE_UNDERFLOW
931
+ UFUNC_FPE_INVALID
932
+ # use these instead
933
+ NPY_FPE_DIVIDEBYZERO
934
+ NPY_FPE_OVERFLOW
935
+ NPY_FPE_UNDERFLOW
936
+ NPY_FPE_INVALID
937
+
938
+
939
+ object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
940
+ void **, char *, int, int, int, int, char *, char *, int)
941
+ int PyUFunc_RegisterLoopForType(ufunc, int,
942
+ PyUFuncGenericFunction, int *, void *) except -1
943
+ void PyUFunc_f_f_As_d_d \
944
+ (char **, npy_intp *, npy_intp *, void *)
945
+ void PyUFunc_d_d \
946
+ (char **, npy_intp *, npy_intp *, void *)
947
+ void PyUFunc_f_f \
948
+ (char **, npy_intp *, npy_intp *, void *)
949
+ void PyUFunc_g_g \
950
+ (char **, npy_intp *, npy_intp *, void *)
951
+ void PyUFunc_F_F_As_D_D \
952
+ (char **, npy_intp *, npy_intp *, void *)
953
+ void PyUFunc_F_F \
954
+ (char **, npy_intp *, npy_intp *, void *)
955
+ void PyUFunc_D_D \
956
+ (char **, npy_intp *, npy_intp *, void *)
957
+ void PyUFunc_G_G \
958
+ (char **, npy_intp *, npy_intp *, void *)
959
+ void PyUFunc_O_O \
960
+ (char **, npy_intp *, npy_intp *, void *)
961
+ void PyUFunc_ff_f_As_dd_d \
962
+ (char **, npy_intp *, npy_intp *, void *)
963
+ void PyUFunc_ff_f \
964
+ (char **, npy_intp *, npy_intp *, void *)
965
+ void PyUFunc_dd_d \
966
+ (char **, npy_intp *, npy_intp *, void *)
967
+ void PyUFunc_gg_g \
968
+ (char **, npy_intp *, npy_intp *, void *)
969
+ void PyUFunc_FF_F_As_DD_D \
970
+ (char **, npy_intp *, npy_intp *, void *)
971
+ void PyUFunc_DD_D \
972
+ (char **, npy_intp *, npy_intp *, void *)
973
+ void PyUFunc_FF_F \
974
+ (char **, npy_intp *, npy_intp *, void *)
975
+ void PyUFunc_GG_G \
976
+ (char **, npy_intp *, npy_intp *, void *)
977
+ void PyUFunc_OO_O \
978
+ (char **, npy_intp *, npy_intp *, void *)
979
+ void PyUFunc_O_O_method \
980
+ (char **, npy_intp *, npy_intp *, void *)
981
+ void PyUFunc_OO_O_method \
982
+ (char **, npy_intp *, npy_intp *, void *)
983
+ void PyUFunc_On_Om \
984
+ (char **, npy_intp *, npy_intp *, void *)
985
+ void PyUFunc_clearfperr()
986
+ int PyUFunc_getfperr()
987
+ int PyUFunc_ReplaceLoopBySignature \
988
+ (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
989
+ object PyUFunc_FromFuncAndDataAndSignature \
990
+ (PyUFuncGenericFunction *, void **, char *, int, int, int,
991
+ int, char *, char *, int, char *)
992
+
993
+ int _import_umath() except -1
994
+
995
+ cdef inline void set_array_base(ndarray arr, object base) except *:
996
+ Py_INCREF(base) # important to do this before stealing the reference below!
997
+ PyArray_SetBaseObject(arr, base)
998
+
999
+ cdef inline object get_array_base(ndarray arr):
1000
+ base = PyArray_BASE(arr)
1001
+ if base is NULL:
1002
+ return None
1003
+ return <object>base
1004
+
1005
+ # Versions of the import_* functions which are more suitable for
1006
+ # Cython code.
1007
+ cdef inline int import_array() except -1:
1008
+ try:
1009
+ __pyx_import_array()
1010
+ except Exception:
1011
+ raise ImportError("numpy._core.multiarray failed to import")
1012
+
1013
+ cdef inline int import_umath() except -1:
1014
+ try:
1015
+ _import_umath()
1016
+ except Exception:
1017
+ raise ImportError("numpy._core.umath failed to import")
1018
+
1019
+ cdef inline int import_ufunc() except -1:
1020
+ try:
1021
+ _import_umath()
1022
+ except Exception:
1023
+ raise ImportError("numpy._core.umath failed to import")
1024
+
1025
+
1026
+ cdef inline bint is_timedelta64_object(object obj) noexcept:
1027
+ """
1028
+ Cython equivalent of `isinstance(obj, np.timedelta64)`
1029
+
1030
+ Parameters
1031
+ ----------
1032
+ obj : object
1033
+
1034
+ Returns
1035
+ -------
1036
+ bool
1037
+ """
1038
+ return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
1039
+
1040
+
1041
+ cdef inline bint is_datetime64_object(object obj) noexcept:
1042
+ """
1043
+ Cython equivalent of `isinstance(obj, np.datetime64)`
1044
+
1045
+ Parameters
1046
+ ----------
1047
+ obj : object
1048
+
1049
+ Returns
1050
+ -------
1051
+ bool
1052
+ """
1053
+ return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
1054
+
1055
+
1056
+ cdef inline npy_datetime get_datetime64_value(object obj) noexcept nogil:
1057
+ """
1058
+ returns the int64 value underlying scalar numpy datetime64 object
1059
+
1060
+ Note that to interpret this as a datetime, the corresponding unit is
1061
+ also needed. That can be found using `get_datetime64_unit`.
1062
+ """
1063
+ return (<PyDatetimeScalarObject*>obj).obval
1064
+
1065
+
1066
+ cdef inline npy_timedelta get_timedelta64_value(object obj) noexcept nogil:
1067
+ """
1068
+ returns the int64 value underlying scalar numpy timedelta64 object
1069
+ """
1070
+ return (<PyTimedeltaScalarObject*>obj).obval
1071
+
1072
+
1073
+ cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) noexcept nogil:
1074
+ """
1075
+ returns the unit part of the dtype for a numpy datetime64 object.
1076
+ """
1077
+ return <NPY_DATETIMEUNIT>(<PyDatetimeScalarObject*>obj).obmeta.base
1078
+
1079
+
1080
+ cdef extern from "numpy/arrayobject.h":
1081
+
1082
+ ctypedef struct NpyIter:
1083
+ pass
1084
+
1085
+ cdef enum:
1086
+ NPY_FAIL
1087
+ NPY_SUCCEED
1088
+
1089
+ cdef enum:
1090
+ # Track an index representing C order
1091
+ NPY_ITER_C_INDEX
1092
+ # Track an index representing Fortran order
1093
+ NPY_ITER_F_INDEX
1094
+ # Track a multi-index
1095
+ NPY_ITER_MULTI_INDEX
1096
+ # User code external to the iterator does the 1-dimensional innermost loop
1097
+ NPY_ITER_EXTERNAL_LOOP
1098
+ # Convert all the operands to a common data type
1099
+ NPY_ITER_COMMON_DTYPE
1100
+ # Operands may hold references, requiring API access during iteration
1101
+ NPY_ITER_REFS_OK
1102
+ # Zero-sized operands should be permitted, iteration checks IterSize for 0
1103
+ NPY_ITER_ZEROSIZE_OK
1104
+ # Permits reductions (size-0 stride with dimension size > 1)
1105
+ NPY_ITER_REDUCE_OK
1106
+ # Enables sub-range iteration
1107
+ NPY_ITER_RANGED
1108
+ # Enables buffering
1109
+ NPY_ITER_BUFFERED
1110
+ # When buffering is enabled, grows the inner loop if possible
1111
+ NPY_ITER_GROWINNER
1112
+ # Delay allocation of buffers until first Reset* call
1113
+ NPY_ITER_DELAY_BUFALLOC
1114
+ # When NPY_KEEPORDER is specified, disable reversing negative-stride axes
1115
+ NPY_ITER_DONT_NEGATE_STRIDES
1116
+ NPY_ITER_COPY_IF_OVERLAP
1117
+ # The operand will be read from and written to
1118
+ NPY_ITER_READWRITE
1119
+ # The operand will only be read from
1120
+ NPY_ITER_READONLY
1121
+ # The operand will only be written to
1122
+ NPY_ITER_WRITEONLY
1123
+ # The operand's data must be in native byte order
1124
+ NPY_ITER_NBO
1125
+ # The operand's data must be aligned
1126
+ NPY_ITER_ALIGNED
1127
+ # The operand's data must be contiguous (within the inner loop)
1128
+ NPY_ITER_CONTIG
1129
+ # The operand may be copied to satisfy requirements
1130
+ NPY_ITER_COPY
1131
+ # The operand may be copied with WRITEBACKIFCOPY to satisfy requirements
1132
+ NPY_ITER_UPDATEIFCOPY
1133
+ # Allocate the operand if it is NULL
1134
+ NPY_ITER_ALLOCATE
1135
+ # If an operand is allocated, don't use any subtype
1136
+ NPY_ITER_NO_SUBTYPE
1137
+ # This is a virtual array slot, operand is NULL but temporary data is there
1138
+ NPY_ITER_VIRTUAL
1139
+ # Require that the dimension match the iterator dimensions exactly
1140
+ NPY_ITER_NO_BROADCAST
1141
+ # A mask is being used on this array, affects buffer -> array copy
1142
+ NPY_ITER_WRITEMASKED
1143
+ # This array is the mask for all WRITEMASKED operands
1144
+ NPY_ITER_ARRAYMASK
1145
+ # Assume iterator order data access for COPY_IF_OVERLAP
1146
+ NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE
1147
+
1148
+ # construction and destruction functions
1149
+ NpyIter* NpyIter_New(ndarray arr, npy_uint32 flags, NPY_ORDER order,
1150
+ NPY_CASTING casting, dtype datatype) except NULL
1151
+ NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags,
1152
+ NPY_ORDER order, NPY_CASTING casting, npy_uint32*
1153
+ op_flags, PyArray_Descr** op_dtypes) except NULL
1154
+ NpyIter* NpyIter_AdvancedNew(npy_intp nop, PyArrayObject** op,
1155
+ npy_uint32 flags, NPY_ORDER order,
1156
+ NPY_CASTING casting, npy_uint32* op_flags,
1157
+ PyArray_Descr** op_dtypes, int oa_ndim,
1158
+ int** op_axes, const npy_intp* itershape,
1159
+ npy_intp buffersize) except NULL
1160
+ NpyIter* NpyIter_Copy(NpyIter* it) except NULL
1161
+ int NpyIter_RemoveAxis(NpyIter* it, int axis) except NPY_FAIL
1162
+ int NpyIter_RemoveMultiIndex(NpyIter* it) except NPY_FAIL
1163
+ int NpyIter_EnableExternalLoop(NpyIter* it) except NPY_FAIL
1164
+ int NpyIter_Deallocate(NpyIter* it) except NPY_FAIL
1165
+ int NpyIter_Reset(NpyIter* it, char** errmsg) except NPY_FAIL
1166
+ int NpyIter_ResetToIterIndexRange(NpyIter* it, npy_intp istart,
1167
+ npy_intp iend, char** errmsg) except NPY_FAIL
1168
+ int NpyIter_ResetBasePointers(NpyIter* it, char** baseptrs, char** errmsg) except NPY_FAIL
1169
+ int NpyIter_GotoMultiIndex(NpyIter* it, const npy_intp* multi_index) except NPY_FAIL
1170
+ int NpyIter_GotoIndex(NpyIter* it, npy_intp index) except NPY_FAIL
1171
+ npy_intp NpyIter_GetIterSize(NpyIter* it) nogil
1172
+ npy_intp NpyIter_GetIterIndex(NpyIter* it) nogil
1173
+ void NpyIter_GetIterIndexRange(NpyIter* it, npy_intp* istart,
1174
+ npy_intp* iend) nogil
1175
+ int NpyIter_GotoIterIndex(NpyIter* it, npy_intp iterindex) except NPY_FAIL
1176
+ npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* it) nogil
1177
+ npy_bool NpyIter_HasExternalLoop(NpyIter* it) nogil
1178
+ npy_bool NpyIter_HasMultiIndex(NpyIter* it) nogil
1179
+ npy_bool NpyIter_HasIndex(NpyIter* it) nogil
1180
+ npy_bool NpyIter_RequiresBuffering(NpyIter* it) nogil
1181
+ npy_bool NpyIter_IsBuffered(NpyIter* it) nogil
1182
+ npy_bool NpyIter_IsGrowInner(NpyIter* it) nogil
1183
+ npy_intp NpyIter_GetBufferSize(NpyIter* it) nogil
1184
+ int NpyIter_GetNDim(NpyIter* it) nogil
1185
+ int NpyIter_GetNOp(NpyIter* it) nogil
1186
+ npy_intp* NpyIter_GetAxisStrideArray(NpyIter* it, int axis) except NULL
1187
+ int NpyIter_GetShape(NpyIter* it, npy_intp* outshape) nogil
1188
+ PyArray_Descr** NpyIter_GetDescrArray(NpyIter* it)
1189
+ PyArrayObject** NpyIter_GetOperandArray(NpyIter* it)
1190
+ ndarray NpyIter_GetIterView(NpyIter* it, npy_intp i)
1191
+ void NpyIter_GetReadFlags(NpyIter* it, char* outreadflags)
1192
+ void NpyIter_GetWriteFlags(NpyIter* it, char* outwriteflags)
1193
+ int NpyIter_CreateCompatibleStrides(NpyIter* it, npy_intp itemsize,
1194
+ npy_intp* outstrides) except NPY_FAIL
1195
+ npy_bool NpyIter_IsFirstVisit(NpyIter* it, int iop) nogil
1196
+ # functions for iterating an NpyIter object
1197
+ #
1198
+ # These don't match the definition in the C API because Cython can't wrap
1199
+ # function pointers that return functions.
1200
+ NpyIter_IterNextFunc NpyIter_GetIterNext(NpyIter* it, char** errmsg) except NULL
1201
+ NpyIter_GetMultiIndexFunc NpyIter_GetGetMultiIndex(NpyIter* it,
1202
+ char** errmsg) except NULL
1203
+ char** NpyIter_GetDataPtrArray(NpyIter* it) nogil
1204
+ char** NpyIter_GetInitialDataPtrArray(NpyIter* it) nogil
1205
+ npy_intp* NpyIter_GetIndexPtr(NpyIter* it)
1206
+ npy_intp* NpyIter_GetInnerStrideArray(NpyIter* it) nogil
1207
+ npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* it) nogil
1208
+ void NpyIter_GetInnerFixedStrideArray(NpyIter* it, npy_intp* outstrides) nogil
1209
+ npy_bool NpyIter_IterationNeedsAPI(NpyIter* it) nogil
1210
+ void NpyIter_DebugPrint(NpyIter* it)
1211
+
1212
+ # NpyString API
1213
+ cdef extern from "numpy/ndarraytypes.h":
1214
+ ctypedef struct npy_string_allocator:
1215
+ pass
1216
+
1217
+ ctypedef struct npy_packed_static_string:
1218
+ pass
1219
+
1220
+ ctypedef struct npy_static_string:
1221
+ size_t size
1222
+ const char *buf
1223
+
1224
+ ctypedef struct PyArray_StringDTypeObject:
1225
+ PyArray_Descr base
1226
+ PyObject *na_object
1227
+ char coerce
1228
+ char has_nan_na
1229
+ char has_string_na
1230
+ char array_owned
1231
+ npy_static_string default_string
1232
+ npy_static_string na_name
1233
+ npy_string_allocator *allocator
1234
+
1235
+ cdef extern from "numpy/arrayobject.h":
1236
+ npy_string_allocator *NpyString_acquire_allocator(const PyArray_StringDTypeObject *descr)
1237
+ void NpyString_acquire_allocators(size_t n_descriptors, PyArray_Descr *const descrs[], npy_string_allocator *allocators[])
1238
+ void NpyString_release_allocator(npy_string_allocator *allocator)
1239
+ void NpyString_release_allocators(size_t length, npy_string_allocator *allocators[])
1240
+ int NpyString_load(npy_string_allocator *allocator, const npy_packed_static_string *packed_string, npy_static_string *unpacked_string)
1241
+ int NpyString_pack_null(npy_string_allocator *allocator, npy_packed_static_string *packed_string)
1242
+ int NpyString_pack(npy_string_allocator *allocator, npy_packed_static_string *packed_string, const char *buf, size_t size)
.venv_haddock/lib/python3.12/site-packages/numpy/__init__.pxd ADDED
@@ -0,0 +1,1155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # NumPy static imports for Cython < 3.0
2
+ #
3
+ # If any of the PyArray_* functions are called, import_array must be
4
+ # called first.
5
+ #
6
+ # Author: Dag Sverre Seljebotn
7
+ #
8
+
9
+ DEF _buffer_format_string_len = 255
10
+
11
+ cimport cpython.buffer as pybuf
12
+ from cpython.ref cimport Py_INCREF
13
+ from cpython.mem cimport PyObject_Malloc, PyObject_Free
14
+ from cpython.object cimport PyObject, PyTypeObject
15
+ from cpython.buffer cimport PyObject_GetBuffer
16
+ from cpython.type cimport type
17
+ cimport libc.stdio as stdio
18
+
19
+
20
+ cdef extern from *:
21
+ # Leave a marker that the NumPy declarations came from NumPy itself and not from Cython.
22
+ # See https://github.com/cython/cython/issues/3573
23
+ """
24
+ /* Using NumPy API declarations from "numpy/__init__.pxd" */
25
+ """
26
+
27
+
28
+ cdef extern from "Python.h":
29
+ ctypedef int Py_intptr_t
30
+ bint PyObject_TypeCheck(object obj, PyTypeObject* type)
31
+
32
+ cdef extern from "numpy/arrayobject.h":
33
+ # It would be nice to use size_t and ssize_t, but ssize_t has special
34
+ # implicit conversion rules, so just use "long".
35
+ # Note: The actual type only matters for Cython promotion, so long
36
+ # is closer than int, but could lead to incorrect promotion.
37
+ # (Not to worrying, and always the status-quo.)
38
+ ctypedef signed long npy_intp
39
+ ctypedef unsigned long npy_uintp
40
+
41
+ ctypedef unsigned char npy_bool
42
+
43
+ ctypedef signed char npy_byte
44
+ ctypedef signed short npy_short
45
+ ctypedef signed int npy_int
46
+ ctypedef signed long npy_long
47
+ ctypedef signed long long npy_longlong
48
+
49
+ ctypedef unsigned char npy_ubyte
50
+ ctypedef unsigned short npy_ushort
51
+ ctypedef unsigned int npy_uint
52
+ ctypedef unsigned long npy_ulong
53
+ ctypedef unsigned long long npy_ulonglong
54
+
55
+ ctypedef float npy_float
56
+ ctypedef double npy_double
57
+ ctypedef long double npy_longdouble
58
+
59
+ ctypedef signed char npy_int8
60
+ ctypedef signed short npy_int16
61
+ ctypedef signed int npy_int32
62
+ ctypedef signed long long npy_int64
63
+
64
+ ctypedef unsigned char npy_uint8
65
+ ctypedef unsigned short npy_uint16
66
+ ctypedef unsigned int npy_uint32
67
+ ctypedef unsigned long long npy_uint64
68
+
69
+ ctypedef float npy_float32
70
+ ctypedef double npy_float64
71
+ ctypedef long double npy_float80
72
+ ctypedef long double npy_float96
73
+ ctypedef long double npy_float128
74
+
75
+ ctypedef struct npy_cfloat:
76
+ pass
77
+
78
+ ctypedef struct npy_cdouble:
79
+ pass
80
+
81
+ ctypedef struct npy_clongdouble:
82
+ pass
83
+
84
+ ctypedef struct npy_complex64:
85
+ pass
86
+
87
+ ctypedef struct npy_complex128:
88
+ pass
89
+
90
+ ctypedef struct npy_complex160:
91
+ pass
92
+
93
+ ctypedef struct npy_complex192:
94
+ pass
95
+
96
+ ctypedef struct npy_complex256:
97
+ pass
98
+
99
+ ctypedef struct PyArray_Dims:
100
+ npy_intp *ptr
101
+ int len
102
+
103
+
104
+ cdef enum NPY_TYPES:
105
+ NPY_BOOL
106
+ NPY_BYTE
107
+ NPY_UBYTE
108
+ NPY_SHORT
109
+ NPY_USHORT
110
+ NPY_INT
111
+ NPY_UINT
112
+ NPY_LONG
113
+ NPY_ULONG
114
+ NPY_LONGLONG
115
+ NPY_ULONGLONG
116
+ NPY_FLOAT
117
+ NPY_DOUBLE
118
+ NPY_LONGDOUBLE
119
+ NPY_CFLOAT
120
+ NPY_CDOUBLE
121
+ NPY_CLONGDOUBLE
122
+ NPY_OBJECT
123
+ NPY_STRING
124
+ NPY_UNICODE
125
+ NPY_VSTRING
126
+ NPY_VOID
127
+ NPY_DATETIME
128
+ NPY_TIMEDELTA
129
+ NPY_NTYPES_LEGACY
130
+ NPY_NOTYPE
131
+
132
+ NPY_INT8
133
+ NPY_INT16
134
+ NPY_INT32
135
+ NPY_INT64
136
+ NPY_UINT8
137
+ NPY_UINT16
138
+ NPY_UINT32
139
+ NPY_UINT64
140
+ NPY_FLOAT16
141
+ NPY_FLOAT32
142
+ NPY_FLOAT64
143
+ NPY_FLOAT80
144
+ NPY_FLOAT96
145
+ NPY_FLOAT128
146
+ NPY_COMPLEX64
147
+ NPY_COMPLEX128
148
+ NPY_COMPLEX160
149
+ NPY_COMPLEX192
150
+ NPY_COMPLEX256
151
+
152
+ NPY_INTP
153
+ NPY_UINTP
154
+ NPY_DEFAULT_INT # Not a compile time constant (normally)!
155
+
156
+ ctypedef enum NPY_ORDER:
157
+ NPY_ANYORDER
158
+ NPY_CORDER
159
+ NPY_FORTRANORDER
160
+ NPY_KEEPORDER
161
+
162
+ ctypedef enum NPY_CASTING:
163
+ NPY_NO_CASTING
164
+ NPY_EQUIV_CASTING
165
+ NPY_SAFE_CASTING
166
+ NPY_SAME_KIND_CASTING
167
+ NPY_UNSAFE_CASTING
168
+ NPY_SAME_VALUE_CASTING
169
+
170
+ ctypedef enum NPY_CLIPMODE:
171
+ NPY_CLIP
172
+ NPY_WRAP
173
+ NPY_RAISE
174
+
175
+ ctypedef enum NPY_SCALARKIND:
176
+ NPY_NOSCALAR,
177
+ NPY_BOOL_SCALAR,
178
+ NPY_INTPOS_SCALAR,
179
+ NPY_INTNEG_SCALAR,
180
+ NPY_FLOAT_SCALAR,
181
+ NPY_COMPLEX_SCALAR,
182
+ NPY_OBJECT_SCALAR
183
+
184
+ ctypedef enum NPY_SORTKIND:
185
+ NPY_QUICKSORT
186
+ NPY_HEAPSORT
187
+ NPY_MERGESORT
188
+
189
+ ctypedef enum NPY_SEARCHSIDE:
190
+ NPY_SEARCHLEFT
191
+ NPY_SEARCHRIGHT
192
+
193
+ enum:
194
+ NPY_ARRAY_C_CONTIGUOUS
195
+ NPY_ARRAY_F_CONTIGUOUS
196
+ NPY_ARRAY_OWNDATA
197
+ NPY_ARRAY_FORCECAST
198
+ NPY_ARRAY_ENSURECOPY
199
+ NPY_ARRAY_ENSUREARRAY
200
+ NPY_ARRAY_ELEMENTSTRIDES
201
+ NPY_ARRAY_ALIGNED
202
+ NPY_ARRAY_NOTSWAPPED
203
+ NPY_ARRAY_WRITEABLE
204
+ NPY_ARRAY_WRITEBACKIFCOPY
205
+
206
+ NPY_ARRAY_BEHAVED
207
+ NPY_ARRAY_BEHAVED_NS
208
+ NPY_ARRAY_CARRAY
209
+ NPY_ARRAY_CARRAY_RO
210
+ NPY_ARRAY_FARRAY
211
+ NPY_ARRAY_FARRAY_RO
212
+ NPY_ARRAY_DEFAULT
213
+
214
+ NPY_ARRAY_IN_ARRAY
215
+ NPY_ARRAY_OUT_ARRAY
216
+ NPY_ARRAY_INOUT_ARRAY
217
+ NPY_ARRAY_IN_FARRAY
218
+ NPY_ARRAY_OUT_FARRAY
219
+ NPY_ARRAY_INOUT_FARRAY
220
+
221
+ NPY_ARRAY_UPDATE_ALL
222
+
223
+ cdef enum:
224
+ NPY_MAXDIMS # 64 on NumPy 2.x and 32 on NumPy 1.x
225
+ NPY_RAVEL_AXIS # Used for functions like PyArray_Mean
226
+
227
+ ctypedef void (*PyArray_VectorUnaryFunc)(void *, void *, npy_intp, void *, void *)
228
+
229
+ ctypedef struct PyArray_ArrayDescr:
230
+ # shape is a tuple, but Cython doesn't support "tuple shape"
231
+ # inside a non-PyObject declaration, so we have to declare it
232
+ # as just a PyObject*.
233
+ PyObject* shape
234
+
235
+ ctypedef struct PyArray_Descr:
236
+ pass
237
+
238
+ ctypedef class numpy.dtype [object PyArray_Descr, check_size ignore]:
239
+ # Use PyDataType_* macros when possible, however there are no macros
240
+ # for accessing some of the fields, so some are defined.
241
+ cdef PyTypeObject* typeobj
242
+ cdef char kind
243
+ cdef char type
244
+ # Numpy sometimes mutates this without warning (e.g. it'll
245
+ # sometimes change "|" to "<" in shared dtype objects on
246
+ # little-endian machines). If this matters to you, use
247
+ # PyArray_IsNativeByteOrder(dtype.byteorder) instead of
248
+ # directly accessing this field.
249
+ cdef char byteorder
250
+ # Flags are not directly accessible on Cython <3. Use PyDataType_FLAGS.
251
+ # cdef char flags
252
+ cdef int type_num
253
+ # itemsize/elsize, alignment, fields, names, and subarray must
254
+ # use the `PyDataType_*` accessor macros. With Cython 3 you can
255
+ # still use getter attributes `dtype.itemsize`
256
+
257
+ ctypedef class numpy.flatiter [object PyArrayIterObject, check_size ignore]:
258
+ # Use through macros
259
+ pass
260
+
261
+ ctypedef class numpy.broadcast [object PyArrayMultiIterObject, check_size ignore]:
262
+ cdef int numiter
263
+ cdef npy_intp size, index
264
+ cdef int nd
265
+ cdef npy_intp *dimensions
266
+ cdef void **iters
267
+
268
+ ctypedef struct PyArrayObject:
269
+ # For use in situations where ndarray can't replace PyArrayObject*,
270
+ # like PyArrayObject**.
271
+ pass
272
+
273
+ ctypedef class numpy.ndarray [object PyArrayObject, check_size ignore]:
274
+ cdef __cythonbufferdefaults__ = {"mode": "strided"}
275
+
276
+ cdef:
277
+ # Only taking a few of the most commonly used and stable fields.
278
+ # One should use PyArray_* macros instead to access the C fields.
279
+ char *data
280
+ int ndim "nd"
281
+ npy_intp *shape "dimensions"
282
+ npy_intp *strides
283
+ dtype descr # deprecated since NumPy 1.7 !
284
+ PyObject* base # NOT PUBLIC, DO NOT USE !
285
+
286
+
287
+ int _import_array() except -1
288
+ # A second definition so _import_array isn't marked as used when we use it here.
289
+ # Do not use - subject to change any time.
290
+ int __pyx_import_array "_import_array"() except -1
291
+
292
+ #
293
+ # Macros from ndarrayobject.h
294
+ #
295
+ bint PyArray_CHKFLAGS(ndarray m, int flags) nogil
296
+ bint PyArray_IS_C_CONTIGUOUS(ndarray arr) nogil
297
+ bint PyArray_IS_F_CONTIGUOUS(ndarray arr) nogil
298
+ bint PyArray_ISCONTIGUOUS(ndarray m) nogil
299
+ bint PyArray_ISWRITEABLE(ndarray m) nogil
300
+ bint PyArray_ISALIGNED(ndarray m) nogil
301
+
302
+ int PyArray_NDIM(ndarray) nogil
303
+ bint PyArray_ISONESEGMENT(ndarray) nogil
304
+ bint PyArray_ISFORTRAN(ndarray) nogil
305
+ int PyArray_FORTRANIF(ndarray) nogil
306
+
307
+ void* PyArray_DATA(ndarray) nogil
308
+ char* PyArray_BYTES(ndarray) nogil
309
+
310
+ npy_intp* PyArray_DIMS(ndarray) nogil
311
+ npy_intp* PyArray_STRIDES(ndarray) nogil
312
+ npy_intp PyArray_DIM(ndarray, size_t) nogil
313
+ npy_intp PyArray_STRIDE(ndarray, size_t) nogil
314
+
315
+ PyObject *PyArray_BASE(ndarray) nogil # returns borrowed reference!
316
+ PyArray_Descr *PyArray_DESCR(ndarray) nogil # returns borrowed reference to dtype!
317
+ PyArray_Descr *PyArray_DTYPE(ndarray) nogil # returns borrowed reference to dtype! NP 1.7+ alias for descr.
318
+ int PyArray_FLAGS(ndarray) nogil
319
+ void PyArray_CLEARFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
320
+ void PyArray_ENABLEFLAGS(ndarray, int flags) nogil # Added in NumPy 1.7
321
+ npy_intp PyArray_ITEMSIZE(ndarray) nogil
322
+ int PyArray_TYPE(ndarray arr) nogil
323
+
324
+ object PyArray_GETITEM(ndarray arr, void *itemptr)
325
+ int PyArray_SETITEM(ndarray arr, void *itemptr, object obj) except -1
326
+
327
+ bint PyTypeNum_ISBOOL(int) nogil
328
+ bint PyTypeNum_ISUNSIGNED(int) nogil
329
+ bint PyTypeNum_ISSIGNED(int) nogil
330
+ bint PyTypeNum_ISINTEGER(int) nogil
331
+ bint PyTypeNum_ISFLOAT(int) nogil
332
+ bint PyTypeNum_ISNUMBER(int) nogil
333
+ bint PyTypeNum_ISSTRING(int) nogil
334
+ bint PyTypeNum_ISCOMPLEX(int) nogil
335
+ bint PyTypeNum_ISFLEXIBLE(int) nogil
336
+ bint PyTypeNum_ISUSERDEF(int) nogil
337
+ bint PyTypeNum_ISEXTENDED(int) nogil
338
+ bint PyTypeNum_ISOBJECT(int) nogil
339
+
340
+ npy_intp PyDataType_ELSIZE(dtype) nogil
341
+ npy_intp PyDataType_ALIGNMENT(dtype) nogil
342
+ PyObject* PyDataType_METADATA(dtype) nogil
343
+ PyArray_ArrayDescr* PyDataType_SUBARRAY(dtype) nogil
344
+ PyObject* PyDataType_NAMES(dtype) nogil
345
+ PyObject* PyDataType_FIELDS(dtype) nogil
346
+
347
+ bint PyDataType_ISBOOL(dtype) nogil
348
+ bint PyDataType_ISUNSIGNED(dtype) nogil
349
+ bint PyDataType_ISSIGNED(dtype) nogil
350
+ bint PyDataType_ISINTEGER(dtype) nogil
351
+ bint PyDataType_ISFLOAT(dtype) nogil
352
+ bint PyDataType_ISNUMBER(dtype) nogil
353
+ bint PyDataType_ISSTRING(dtype) nogil
354
+ bint PyDataType_ISCOMPLEX(dtype) nogil
355
+ bint PyDataType_ISFLEXIBLE(dtype) nogil
356
+ bint PyDataType_ISUSERDEF(dtype) nogil
357
+ bint PyDataType_ISEXTENDED(dtype) nogil
358
+ bint PyDataType_ISOBJECT(dtype) nogil
359
+ bint PyDataType_HASFIELDS(dtype) nogil
360
+ bint PyDataType_HASSUBARRAY(dtype) nogil
361
+ npy_uint64 PyDataType_FLAGS(dtype) nogil
362
+
363
+ bint PyArray_ISBOOL(ndarray) nogil
364
+ bint PyArray_ISUNSIGNED(ndarray) nogil
365
+ bint PyArray_ISSIGNED(ndarray) nogil
366
+ bint PyArray_ISINTEGER(ndarray) nogil
367
+ bint PyArray_ISFLOAT(ndarray) nogil
368
+ bint PyArray_ISNUMBER(ndarray) nogil
369
+ bint PyArray_ISSTRING(ndarray) nogil
370
+ bint PyArray_ISCOMPLEX(ndarray) nogil
371
+ bint PyArray_ISFLEXIBLE(ndarray) nogil
372
+ bint PyArray_ISUSERDEF(ndarray) nogil
373
+ bint PyArray_ISEXTENDED(ndarray) nogil
374
+ bint PyArray_ISOBJECT(ndarray) nogil
375
+ bint PyArray_HASFIELDS(ndarray) nogil
376
+
377
+ bint PyArray_ISVARIABLE(ndarray) nogil
378
+
379
+ bint PyArray_SAFEALIGNEDCOPY(ndarray) nogil
380
+ bint PyArray_ISNBO(char) nogil # works on ndarray.byteorder
381
+ bint PyArray_IsNativeByteOrder(char) nogil # works on ndarray.byteorder
382
+ bint PyArray_ISNOTSWAPPED(ndarray) nogil
383
+ bint PyArray_ISBYTESWAPPED(ndarray) nogil
384
+
385
+ bint PyArray_FLAGSWAP(ndarray, int) nogil
386
+
387
+ bint PyArray_ISCARRAY(ndarray) nogil
388
+ bint PyArray_ISCARRAY_RO(ndarray) nogil
389
+ bint PyArray_ISFARRAY(ndarray) nogil
390
+ bint PyArray_ISFARRAY_RO(ndarray) nogil
391
+ bint PyArray_ISBEHAVED(ndarray) nogil
392
+ bint PyArray_ISBEHAVED_RO(ndarray) nogil
393
+
394
+
395
+ bint PyDataType_ISNOTSWAPPED(dtype) nogil
396
+ bint PyDataType_ISBYTESWAPPED(dtype) nogil
397
+
398
+ bint PyArray_DescrCheck(object)
399
+
400
+ bint PyArray_Check(object)
401
+ bint PyArray_CheckExact(object)
402
+
403
+ # Cannot be supported due to out arg:
404
+ # bint PyArray_HasArrayInterfaceType(object, dtype, object, object&)
405
+ # bint PyArray_HasArrayInterface(op, out)
406
+
407
+
408
+ bint PyArray_IsZeroDim(object)
409
+ # Cannot be supported due to ## ## in macro:
410
+ # bint PyArray_IsScalar(object, verbatim work)
411
+ bint PyArray_CheckScalar(object)
412
+ bint PyArray_IsPythonNumber(object)
413
+ bint PyArray_IsPythonScalar(object)
414
+ bint PyArray_IsAnyScalar(object)
415
+ bint PyArray_CheckAnyScalar(object)
416
+
417
+ ndarray PyArray_GETCONTIGUOUS(ndarray)
418
+ bint PyArray_SAMESHAPE(ndarray, ndarray) nogil
419
+ npy_intp PyArray_SIZE(ndarray) nogil
420
+ npy_intp PyArray_NBYTES(ndarray) nogil
421
+
422
+ object PyArray_FROM_O(object)
423
+ object PyArray_FROM_OF(object m, int flags)
424
+ object PyArray_FROM_OT(object m, int type)
425
+ object PyArray_FROM_OTF(object m, int type, int flags)
426
+ object PyArray_FROMANY(object m, int type, int min, int max, int flags)
427
+ object PyArray_ZEROS(int nd, npy_intp* dims, int type, int fortran)
428
+ object PyArray_EMPTY(int nd, npy_intp* dims, int type, int fortran)
429
+ void PyArray_FILLWBYTE(ndarray, int val)
430
+ object PyArray_ContiguousFromAny(op, int, int min_depth, int max_depth)
431
+ unsigned char PyArray_EquivArrTypes(ndarray a1, ndarray a2)
432
+ bint PyArray_EquivByteorders(int b1, int b2) nogil
433
+ object PyArray_SimpleNew(int nd, npy_intp* dims, int typenum)
434
+ object PyArray_SimpleNewFromData(int nd, npy_intp* dims, int typenum, void* data)
435
+ #object PyArray_SimpleNewFromDescr(int nd, npy_intp* dims, dtype descr)
436
+ object PyArray_ToScalar(void* data, ndarray arr)
437
+
438
+ void* PyArray_GETPTR1(ndarray m, npy_intp i) nogil
439
+ void* PyArray_GETPTR2(ndarray m, npy_intp i, npy_intp j) nogil
440
+ void* PyArray_GETPTR3(ndarray m, npy_intp i, npy_intp j, npy_intp k) nogil
441
+ void* PyArray_GETPTR4(ndarray m, npy_intp i, npy_intp j, npy_intp k, npy_intp l) nogil
442
+
443
+ # Cannot be supported due to out arg
444
+ # void PyArray_DESCR_REPLACE(descr)
445
+
446
+
447
+ object PyArray_Copy(ndarray)
448
+ object PyArray_FromObject(object op, int type, int min_depth, int max_depth)
449
+ object PyArray_ContiguousFromObject(object op, int type, int min_depth, int max_depth)
450
+ object PyArray_CopyFromObject(object op, int type, int min_depth, int max_depth)
451
+
452
+ object PyArray_Cast(ndarray mp, int type_num)
453
+ object PyArray_Take(ndarray ap, object items, int axis)
454
+ object PyArray_Put(ndarray ap, object items, object values)
455
+
456
+ void PyArray_ITER_RESET(flatiter it) nogil
457
+ void PyArray_ITER_NEXT(flatiter it) nogil
458
+ void PyArray_ITER_GOTO(flatiter it, npy_intp* destination) nogil
459
+ void PyArray_ITER_GOTO1D(flatiter it, npy_intp ind) nogil
460
+ void* PyArray_ITER_DATA(flatiter it) nogil
461
+ bint PyArray_ITER_NOTDONE(flatiter it) nogil
462
+
463
+ void PyArray_MultiIter_RESET(broadcast multi) nogil
464
+ void PyArray_MultiIter_NEXT(broadcast multi) nogil
465
+ void PyArray_MultiIter_GOTO(broadcast multi, npy_intp dest) nogil
466
+ void PyArray_MultiIter_GOTO1D(broadcast multi, npy_intp ind) nogil
467
+ void* PyArray_MultiIter_DATA(broadcast multi, npy_intp i) nogil
468
+ void PyArray_MultiIter_NEXTi(broadcast multi, npy_intp i) nogil
469
+ bint PyArray_MultiIter_NOTDONE(broadcast multi) nogil
470
+ npy_intp PyArray_MultiIter_SIZE(broadcast multi) nogil
471
+ int PyArray_MultiIter_NDIM(broadcast multi) nogil
472
+ npy_intp PyArray_MultiIter_INDEX(broadcast multi) nogil
473
+ int PyArray_MultiIter_NUMITER(broadcast multi) nogil
474
+ npy_intp* PyArray_MultiIter_DIMS(broadcast multi) nogil
475
+ void** PyArray_MultiIter_ITERS(broadcast multi) nogil
476
+
477
+ # Functions from __multiarray_api.h
478
+
479
+ # Functions taking dtype and returning object/ndarray are disabled
480
+ # for now as they steal dtype references. I'm conservative and disable
481
+ # more than is probably needed until it can be checked further.
482
+ int PyArray_INCREF (ndarray) except * # uses PyArray_Item_INCREF...
483
+ int PyArray_XDECREF (ndarray) except * # uses PyArray_Item_DECREF...
484
+ dtype PyArray_DescrFromType (int)
485
+ object PyArray_TypeObjectFromType (int)
486
+ char * PyArray_Zero (ndarray)
487
+ char * PyArray_One (ndarray)
488
+ #object PyArray_CastToType (ndarray, dtype, int)
489
+ int PyArray_CanCastSafely (int, int) # writes errors
490
+ npy_bool PyArray_CanCastTo (dtype, dtype) # writes errors
491
+ int PyArray_ObjectType (object, int) except 0
492
+ dtype PyArray_DescrFromObject (object, dtype)
493
+ #ndarray* PyArray_ConvertToCommonType (object, int *)
494
+ dtype PyArray_DescrFromScalar (object)
495
+ dtype PyArray_DescrFromTypeObject (object)
496
+ npy_intp PyArray_Size (object)
497
+ #object PyArray_Scalar (void *, dtype, object)
498
+ #object PyArray_FromScalar (object, dtype)
499
+ void PyArray_ScalarAsCtype (object, void *)
500
+ #int PyArray_CastScalarToCtype (object, void *, dtype)
501
+ #int PyArray_CastScalarDirect (object, dtype, void *, int)
502
+ #PyArray_VectorUnaryFunc * PyArray_GetCastFunc (dtype, int)
503
+ #object PyArray_FromAny (object, dtype, int, int, int, object)
504
+ object PyArray_EnsureArray (object)
505
+ object PyArray_EnsureAnyArray (object)
506
+ #object PyArray_FromFile (stdio.FILE *, dtype, npy_intp, char *)
507
+ #object PyArray_FromString (char *, npy_intp, dtype, npy_intp, char *)
508
+ #object PyArray_FromBuffer (object, dtype, npy_intp, npy_intp)
509
+ #object PyArray_FromIter (object, dtype, npy_intp)
510
+ object PyArray_Return (ndarray)
511
+ #object PyArray_GetField (ndarray, dtype, int)
512
+ #int PyArray_SetField (ndarray, dtype, int, object) except -1
513
+ object PyArray_Byteswap (ndarray, npy_bool)
514
+ object PyArray_Resize (ndarray, PyArray_Dims *, int, NPY_ORDER)
515
+ int PyArray_CopyInto (ndarray, ndarray) except -1
516
+ int PyArray_CopyAnyInto (ndarray, ndarray) except -1
517
+ int PyArray_CopyObject (ndarray, object) except -1
518
+ object PyArray_NewCopy (ndarray, NPY_ORDER)
519
+ object PyArray_ToList (ndarray)
520
+ object PyArray_ToString (ndarray, NPY_ORDER)
521
+ int PyArray_ToFile (ndarray, stdio.FILE *, char *, char *) except -1
522
+ int PyArray_Dump (object, object, int) except -1
523
+ object PyArray_Dumps (object, int)
524
+ int PyArray_ValidType (int) # Cannot error
525
+ void PyArray_UpdateFlags (ndarray, int)
526
+ object PyArray_New (type, int, npy_intp *, int, npy_intp *, void *, int, int, object)
527
+ #object PyArray_NewFromDescr (type, dtype, int, npy_intp *, npy_intp *, void *, int, object)
528
+ #dtype PyArray_DescrNew (dtype)
529
+ dtype PyArray_DescrNewFromType (int)
530
+ double PyArray_GetPriority (object, double) # clears errors as of 1.25
531
+ object PyArray_IterNew (object)
532
+ object PyArray_MultiIterNew (int, ...)
533
+
534
+ int PyArray_PyIntAsInt (object) except? -1
535
+ npy_intp PyArray_PyIntAsIntp (object)
536
+ int PyArray_Broadcast (broadcast) except -1
537
+ int PyArray_FillWithScalar (ndarray, object) except -1
538
+ npy_bool PyArray_CheckStrides (int, int, npy_intp, npy_intp, npy_intp *, npy_intp *)
539
+ dtype PyArray_DescrNewByteorder (dtype, char)
540
+ object PyArray_IterAllButAxis (object, int *)
541
+ #object PyArray_CheckFromAny (object, dtype, int, int, int, object)
542
+ #object PyArray_FromArray (ndarray, dtype, int)
543
+ object PyArray_FromInterface (object)
544
+ object PyArray_FromStructInterface (object)
545
+ #object PyArray_FromArrayAttr (object, dtype, object)
546
+ #NPY_SCALARKIND PyArray_ScalarKind (int, ndarray*)
547
+ int PyArray_CanCoerceScalar (int, int, NPY_SCALARKIND)
548
+ npy_bool PyArray_CanCastScalar (type, type)
549
+ int PyArray_RemoveSmallest (broadcast) except -1
550
+ int PyArray_ElementStrides (object)
551
+ void PyArray_Item_INCREF (char *, dtype) except *
552
+ void PyArray_Item_XDECREF (char *, dtype) except *
553
+ object PyArray_Transpose (ndarray, PyArray_Dims *)
554
+ object PyArray_TakeFrom (ndarray, object, int, ndarray, NPY_CLIPMODE)
555
+ object PyArray_PutTo (ndarray, object, object, NPY_CLIPMODE)
556
+ object PyArray_PutMask (ndarray, object, object)
557
+ object PyArray_Repeat (ndarray, object, int)
558
+ object PyArray_Choose (ndarray, object, ndarray, NPY_CLIPMODE)
559
+ int PyArray_Sort (ndarray, int, NPY_SORTKIND) except -1
560
+ object PyArray_ArgSort (ndarray, int, NPY_SORTKIND)
561
+ object PyArray_SearchSorted (ndarray, object, NPY_SEARCHSIDE, PyObject *)
562
+ object PyArray_ArgMax (ndarray, int, ndarray)
563
+ object PyArray_ArgMin (ndarray, int, ndarray)
564
+ object PyArray_Reshape (ndarray, object)
565
+ object PyArray_Newshape (ndarray, PyArray_Dims *, NPY_ORDER)
566
+ object PyArray_Squeeze (ndarray)
567
+ #object PyArray_View (ndarray, dtype, type)
568
+ object PyArray_SwapAxes (ndarray, int, int)
569
+ object PyArray_Max (ndarray, int, ndarray)
570
+ object PyArray_Min (ndarray, int, ndarray)
571
+ object PyArray_Ptp (ndarray, int, ndarray)
572
+ object PyArray_Mean (ndarray, int, int, ndarray)
573
+ object PyArray_Trace (ndarray, int, int, int, int, ndarray)
574
+ object PyArray_Diagonal (ndarray, int, int, int)
575
+ object PyArray_Clip (ndarray, object, object, ndarray)
576
+ object PyArray_Conjugate (ndarray, ndarray)
577
+ object PyArray_Nonzero (ndarray)
578
+ object PyArray_Std (ndarray, int, int, ndarray, int)
579
+ object PyArray_Sum (ndarray, int, int, ndarray)
580
+ object PyArray_CumSum (ndarray, int, int, ndarray)
581
+ object PyArray_Prod (ndarray, int, int, ndarray)
582
+ object PyArray_CumProd (ndarray, int, int, ndarray)
583
+ object PyArray_All (ndarray, int, ndarray)
584
+ object PyArray_Any (ndarray, int, ndarray)
585
+ object PyArray_Compress (ndarray, object, int, ndarray)
586
+ object PyArray_Flatten (ndarray, NPY_ORDER)
587
+ object PyArray_Ravel (ndarray, NPY_ORDER)
588
+ npy_intp PyArray_MultiplyList (npy_intp *, int)
589
+ int PyArray_MultiplyIntList (int *, int)
590
+ void * PyArray_GetPtr (ndarray, npy_intp*)
591
+ int PyArray_CompareLists (npy_intp *, npy_intp *, int)
592
+ #int PyArray_AsCArray (object*, void *, npy_intp *, int, dtype)
593
+ int PyArray_Free (object, void *)
594
+ #int PyArray_Converter (object, object*)
595
+ int PyArray_IntpFromSequence (object, npy_intp *, int) except -1
596
+ object PyArray_Concatenate (object, int)
597
+ object PyArray_InnerProduct (object, object)
598
+ object PyArray_MatrixProduct (object, object)
599
+ object PyArray_Correlate (object, object, int)
600
+ #int PyArray_DescrConverter (object, dtype*) except 0
601
+ #int PyArray_DescrConverter2 (object, dtype*) except 0
602
+ int PyArray_IntpConverter (object, PyArray_Dims *) except 0
603
+ #int PyArray_BufferConverter (object, chunk) except 0
604
+ int PyArray_AxisConverter (object, int *) except 0
605
+ int PyArray_BoolConverter (object, npy_bool *) except 0
606
+ int PyArray_ByteorderConverter (object, char *) except 0
607
+ int PyArray_OrderConverter (object, NPY_ORDER *) except 0
608
+ unsigned char PyArray_EquivTypes (dtype, dtype) # clears errors
609
+ #object PyArray_Zeros (int, npy_intp *, dtype, int)
610
+ #object PyArray_Empty (int, npy_intp *, dtype, int)
611
+ object PyArray_Where (object, object, object)
612
+ object PyArray_Arange (double, double, double, int)
613
+ #object PyArray_ArangeObj (object, object, object, dtype)
614
+ int PyArray_SortkindConverter (object, NPY_SORTKIND *) except 0
615
+ object PyArray_LexSort (object, int)
616
+ object PyArray_Round (ndarray, int, ndarray)
617
+ unsigned char PyArray_EquivTypenums (int, int)
618
+ int PyArray_RegisterDataType (dtype) except -1
619
+ int PyArray_RegisterCastFunc (dtype, int, PyArray_VectorUnaryFunc *) except -1
620
+ int PyArray_RegisterCanCast (dtype, int, NPY_SCALARKIND) except -1
621
+ #void PyArray_InitArrFuncs (PyArray_ArrFuncs *)
622
+ object PyArray_IntTupleFromIntp (int, npy_intp *)
623
+ int PyArray_ClipmodeConverter (object, NPY_CLIPMODE *) except 0
624
+ #int PyArray_OutputConverter (object, ndarray*) except 0
625
+ object PyArray_BroadcastToShape (object, npy_intp *, int)
626
+ #int PyArray_DescrAlignConverter (object, dtype*) except 0
627
+ #int PyArray_DescrAlignConverter2 (object, dtype*) except 0
628
+ int PyArray_SearchsideConverter (object, void *) except 0
629
+ object PyArray_CheckAxis (ndarray, int *, int)
630
+ npy_intp PyArray_OverflowMultiplyList (npy_intp *, int)
631
+ int PyArray_SetBaseObject(ndarray, base) except -1 # NOTE: steals a reference to base! Use "set_array_base()" instead.
632
+
633
+ # The memory handler functions require the NumPy 1.22 API
634
+ # and may require defining NPY_TARGET_VERSION
635
+ ctypedef struct PyDataMemAllocator:
636
+ void *ctx
637
+ void* (*malloc) (void *ctx, size_t size)
638
+ void* (*calloc) (void *ctx, size_t nelem, size_t elsize)
639
+ void* (*realloc) (void *ctx, void *ptr, size_t new_size)
640
+ void (*free) (void *ctx, void *ptr, size_t size)
641
+
642
+ ctypedef struct PyDataMem_Handler:
643
+ char* name
644
+ npy_uint8 version
645
+ PyDataMemAllocator allocator
646
+
647
+ object PyDataMem_SetHandler(object handler)
648
+ object PyDataMem_GetHandler()
649
+
650
+ # additional datetime related functions are defined below
651
+
652
+
653
+ # Typedefs that matches the runtime dtype objects in
654
+ # the numpy module.
655
+
656
+ # The ones that are commented out needs an IFDEF function
657
+ # in Cython to enable them only on the right systems.
658
+
659
+ ctypedef npy_int8 int8_t
660
+ ctypedef npy_int16 int16_t
661
+ ctypedef npy_int32 int32_t
662
+ ctypedef npy_int64 int64_t
663
+
664
+ ctypedef npy_uint8 uint8_t
665
+ ctypedef npy_uint16 uint16_t
666
+ ctypedef npy_uint32 uint32_t
667
+ ctypedef npy_uint64 uint64_t
668
+
669
+ ctypedef npy_float32 float32_t
670
+ ctypedef npy_float64 float64_t
671
+ #ctypedef npy_float80 float80_t
672
+ #ctypedef npy_float128 float128_t
673
+
674
+ ctypedef float complex complex64_t
675
+ ctypedef double complex complex128_t
676
+
677
+ ctypedef npy_longlong longlong_t
678
+ ctypedef npy_ulonglong ulonglong_t
679
+
680
+ ctypedef npy_intp intp_t
681
+ ctypedef npy_uintp uintp_t
682
+
683
+ ctypedef npy_double float_t
684
+ ctypedef npy_double double_t
685
+ ctypedef npy_longdouble longdouble_t
686
+
687
+ ctypedef float complex cfloat_t
688
+ ctypedef double complex cdouble_t
689
+ ctypedef double complex complex_t
690
+ ctypedef long double complex clongdouble_t
691
+
692
+ cdef inline object PyArray_MultiIterNew1(a):
693
+ return PyArray_MultiIterNew(1, <void*>a)
694
+
695
+ cdef inline object PyArray_MultiIterNew2(a, b):
696
+ return PyArray_MultiIterNew(2, <void*>a, <void*>b)
697
+
698
+ cdef inline object PyArray_MultiIterNew3(a, b, c):
699
+ return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
700
+
701
+ cdef inline object PyArray_MultiIterNew4(a, b, c, d):
702
+ return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
703
+
704
+ cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
705
+ return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
706
+
707
+ cdef inline tuple PyDataType_SHAPE(dtype d):
708
+ if PyDataType_HASSUBARRAY(d):
709
+ return <tuple>d.subarray.shape
710
+ else:
711
+ return ()
712
+
713
+
714
+ cdef extern from "numpy/ndarrayobject.h":
715
+ PyTypeObject PyTimedeltaArrType_Type
716
+ PyTypeObject PyDatetimeArrType_Type
717
+ ctypedef int64_t npy_timedelta
718
+ ctypedef int64_t npy_datetime
719
+
720
+ cdef extern from "numpy/ndarraytypes.h":
721
+ ctypedef struct PyArray_DatetimeMetaData:
722
+ NPY_DATETIMEUNIT base
723
+ int64_t num
724
+
725
+ ctypedef struct npy_datetimestruct:
726
+ int64_t year
727
+ int32_t month, day, hour, min, sec, us, ps, as
728
+
729
+ # Iterator API added in v1.6
730
+ #
731
+ # These don't match the definition in the C API because Cython can't wrap
732
+ # function pointers that return functions.
733
+ # https://github.com/cython/cython/issues/6720
734
+ ctypedef int (*NpyIter_IterNextFunc "NpyIter_IterNextFunc *")(NpyIter* it) noexcept nogil
735
+ ctypedef void (*NpyIter_GetMultiIndexFunc "NpyIter_GetMultiIndexFunc *")(NpyIter* it, npy_intp* outcoords) noexcept nogil
736
+
737
+ cdef extern from "numpy/arrayscalars.h":
738
+
739
+ # abstract types
740
+ ctypedef class numpy.generic [object PyObject]:
741
+ pass
742
+ ctypedef class numpy.number [object PyObject]:
743
+ pass
744
+ ctypedef class numpy.integer [object PyObject]:
745
+ pass
746
+ ctypedef class numpy.signedinteger [object PyObject]:
747
+ pass
748
+ ctypedef class numpy.unsignedinteger [object PyObject]:
749
+ pass
750
+ ctypedef class numpy.inexact [object PyObject]:
751
+ pass
752
+ ctypedef class numpy.floating [object PyObject]:
753
+ pass
754
+ ctypedef class numpy.complexfloating [object PyObject]:
755
+ pass
756
+ ctypedef class numpy.flexible [object PyObject]:
757
+ pass
758
+ ctypedef class numpy.character [object PyObject]:
759
+ pass
760
+
761
+ ctypedef struct PyDatetimeScalarObject:
762
+ # PyObject_HEAD
763
+ npy_datetime obval
764
+ PyArray_DatetimeMetaData obmeta
765
+
766
+ ctypedef struct PyTimedeltaScalarObject:
767
+ # PyObject_HEAD
768
+ npy_timedelta obval
769
+ PyArray_DatetimeMetaData obmeta
770
+
771
+ ctypedef enum NPY_DATETIMEUNIT:
772
+ NPY_FR_Y
773
+ NPY_FR_M
774
+ NPY_FR_W
775
+ NPY_FR_D
776
+ NPY_FR_B
777
+ NPY_FR_h
778
+ NPY_FR_m
779
+ NPY_FR_s
780
+ NPY_FR_ms
781
+ NPY_FR_us
782
+ NPY_FR_ns
783
+ NPY_FR_ps
784
+ NPY_FR_fs
785
+ NPY_FR_as
786
+ NPY_FR_GENERIC
787
+
788
+
789
+ cdef extern from "numpy/arrayobject.h":
790
+ # These are part of the C-API defined in `__multiarray_api.h`
791
+
792
+ # NumPy internal definitions in datetime_strings.c:
793
+ int get_datetime_iso_8601_strlen "NpyDatetime_GetDatetimeISO8601StrLen" (
794
+ int local, NPY_DATETIMEUNIT base)
795
+ int make_iso_8601_datetime "NpyDatetime_MakeISO8601Datetime" (
796
+ npy_datetimestruct *dts, char *outstr, npy_intp outlen,
797
+ int local, int utc, NPY_DATETIMEUNIT base, int tzoffset,
798
+ NPY_CASTING casting) except -1
799
+
800
+ # NumPy internal definition in datetime.c:
801
+ # May return 1 to indicate that object does not appear to be a datetime
802
+ # (returns 0 on success).
803
+ int convert_pydatetime_to_datetimestruct "NpyDatetime_ConvertPyDateTimeToDatetimeStruct" (
804
+ PyObject *obj, npy_datetimestruct *out,
805
+ NPY_DATETIMEUNIT *out_bestunit, int apply_tzinfo) except -1
806
+ int convert_datetime64_to_datetimestruct "NpyDatetime_ConvertDatetime64ToDatetimeStruct" (
807
+ PyArray_DatetimeMetaData *meta, npy_datetime dt,
808
+ npy_datetimestruct *out) except -1
809
+ int convert_datetimestruct_to_datetime64 "NpyDatetime_ConvertDatetimeStructToDatetime64"(
810
+ PyArray_DatetimeMetaData *meta, const npy_datetimestruct *dts,
811
+ npy_datetime *out) except -1
812
+
813
+
814
+ #
815
+ # ufunc API
816
+ #
817
+
818
+ cdef extern from "numpy/ufuncobject.h":
819
+
820
+ ctypedef void (*PyUFuncGenericFunction) (char **, npy_intp *, npy_intp *, void *)
821
+
822
+ ctypedef class numpy.ufunc [object PyUFuncObject, check_size ignore]:
823
+ cdef:
824
+ int nin, nout, nargs
825
+ int identity
826
+ PyUFuncGenericFunction *functions
827
+ void **data
828
+ int ntypes
829
+ int check_return
830
+ char *name
831
+ char *types
832
+ char *doc
833
+ void *ptr
834
+ PyObject *obj
835
+ PyObject *userloops
836
+
837
+ cdef enum:
838
+ PyUFunc_Zero
839
+ PyUFunc_One
840
+ PyUFunc_None
841
+ # deprecated
842
+ UFUNC_FPE_DIVIDEBYZERO
843
+ UFUNC_FPE_OVERFLOW
844
+ UFUNC_FPE_UNDERFLOW
845
+ UFUNC_FPE_INVALID
846
+ # use these instead
847
+ NPY_FPE_DIVIDEBYZERO
848
+ NPY_FPE_OVERFLOW
849
+ NPY_FPE_UNDERFLOW
850
+ NPY_FPE_INVALID
851
+
852
+ object PyUFunc_FromFuncAndData(PyUFuncGenericFunction *,
853
+ void **, char *, int, int, int, int, char *, char *, int)
854
+ int PyUFunc_RegisterLoopForType(ufunc, int,
855
+ PyUFuncGenericFunction, int *, void *) except -1
856
+ void PyUFunc_f_f_As_d_d \
857
+ (char **, npy_intp *, npy_intp *, void *)
858
+ void PyUFunc_d_d \
859
+ (char **, npy_intp *, npy_intp *, void *)
860
+ void PyUFunc_f_f \
861
+ (char **, npy_intp *, npy_intp *, void *)
862
+ void PyUFunc_g_g \
863
+ (char **, npy_intp *, npy_intp *, void *)
864
+ void PyUFunc_F_F_As_D_D \
865
+ (char **, npy_intp *, npy_intp *, void *)
866
+ void PyUFunc_F_F \
867
+ (char **, npy_intp *, npy_intp *, void *)
868
+ void PyUFunc_D_D \
869
+ (char **, npy_intp *, npy_intp *, void *)
870
+ void PyUFunc_G_G \
871
+ (char **, npy_intp *, npy_intp *, void *)
872
+ void PyUFunc_O_O \
873
+ (char **, npy_intp *, npy_intp *, void *)
874
+ void PyUFunc_ff_f_As_dd_d \
875
+ (char **, npy_intp *, npy_intp *, void *)
876
+ void PyUFunc_ff_f \
877
+ (char **, npy_intp *, npy_intp *, void *)
878
+ void PyUFunc_dd_d \
879
+ (char **, npy_intp *, npy_intp *, void *)
880
+ void PyUFunc_gg_g \
881
+ (char **, npy_intp *, npy_intp *, void *)
882
+ void PyUFunc_FF_F_As_DD_D \
883
+ (char **, npy_intp *, npy_intp *, void *)
884
+ void PyUFunc_DD_D \
885
+ (char **, npy_intp *, npy_intp *, void *)
886
+ void PyUFunc_FF_F \
887
+ (char **, npy_intp *, npy_intp *, void *)
888
+ void PyUFunc_GG_G \
889
+ (char **, npy_intp *, npy_intp *, void *)
890
+ void PyUFunc_OO_O \
891
+ (char **, npy_intp *, npy_intp *, void *)
892
+ void PyUFunc_O_O_method \
893
+ (char **, npy_intp *, npy_intp *, void *)
894
+ void PyUFunc_OO_O_method \
895
+ (char **, npy_intp *, npy_intp *, void *)
896
+ void PyUFunc_On_Om \
897
+ (char **, npy_intp *, npy_intp *, void *)
898
+ void PyUFunc_clearfperr()
899
+ int PyUFunc_getfperr()
900
+ int PyUFunc_ReplaceLoopBySignature \
901
+ (ufunc, PyUFuncGenericFunction, int *, PyUFuncGenericFunction *)
902
+ object PyUFunc_FromFuncAndDataAndSignature \
903
+ (PyUFuncGenericFunction *, void **, char *, int, int, int,
904
+ int, char *, char *, int, char *)
905
+
906
+ int _import_umath() except -1
907
+
908
+ cdef inline void set_array_base(ndarray arr, object base):
909
+ Py_INCREF(base) # important to do this before stealing the reference below!
910
+ PyArray_SetBaseObject(arr, base)
911
+
912
+ cdef inline object get_array_base(ndarray arr):
913
+ base = PyArray_BASE(arr)
914
+ if base is NULL:
915
+ return None
916
+ return <object>base
917
+
918
+ # Versions of the import_* functions which are more suitable for
919
+ # Cython code.
920
+ cdef inline int import_array() except -1:
921
+ try:
922
+ __pyx_import_array()
923
+ except Exception:
924
+ raise ImportError("numpy._core.multiarray failed to import")
925
+
926
+ cdef inline int import_umath() except -1:
927
+ try:
928
+ _import_umath()
929
+ except Exception:
930
+ raise ImportError("numpy._core.umath failed to import")
931
+
932
+ cdef inline int import_ufunc() except -1:
933
+ try:
934
+ _import_umath()
935
+ except Exception:
936
+ raise ImportError("numpy._core.umath failed to import")
937
+
938
+
939
+ cdef inline bint is_timedelta64_object(object obj):
940
+ """
941
+ Cython equivalent of `isinstance(obj, np.timedelta64)`
942
+
943
+ Parameters
944
+ ----------
945
+ obj : object
946
+
947
+ Returns
948
+ -------
949
+ bool
950
+ """
951
+ return PyObject_TypeCheck(obj, &PyTimedeltaArrType_Type)
952
+
953
+
954
+ cdef inline bint is_datetime64_object(object obj):
955
+ """
956
+ Cython equivalent of `isinstance(obj, np.datetime64)`
957
+
958
+ Parameters
959
+ ----------
960
+ obj : object
961
+
962
+ Returns
963
+ -------
964
+ bool
965
+ """
966
+ return PyObject_TypeCheck(obj, &PyDatetimeArrType_Type)
967
+
968
+
969
+ cdef inline npy_datetime get_datetime64_value(object obj) nogil:
970
+ """
971
+ returns the int64 value underlying scalar numpy datetime64 object
972
+
973
+ Note that to interpret this as a datetime, the corresponding unit is
974
+ also needed. That can be found using `get_datetime64_unit`.
975
+ """
976
+ return (<PyDatetimeScalarObject*>obj).obval
977
+
978
+
979
+ cdef inline npy_timedelta get_timedelta64_value(object obj) nogil:
980
+ """
981
+ returns the int64 value underlying scalar numpy timedelta64 object
982
+ """
983
+ return (<PyTimedeltaScalarObject*>obj).obval
984
+
985
+
986
+ cdef inline NPY_DATETIMEUNIT get_datetime64_unit(object obj) nogil:
987
+ """
988
+ returns the unit part of the dtype for a numpy datetime64 object.
989
+ """
990
+ return <NPY_DATETIMEUNIT>(<PyDatetimeScalarObject*>obj).obmeta.base
991
+
992
+
993
+ cdef extern from "numpy/arrayobject.h":
994
+
995
+ ctypedef struct NpyIter:
996
+ pass
997
+
998
+ cdef enum:
999
+ NPY_FAIL
1000
+ NPY_SUCCEED
1001
+
1002
+ cdef enum:
1003
+ # Track an index representing C order
1004
+ NPY_ITER_C_INDEX
1005
+ # Track an index representing Fortran order
1006
+ NPY_ITER_F_INDEX
1007
+ # Track a multi-index
1008
+ NPY_ITER_MULTI_INDEX
1009
+ # User code external to the iterator does the 1-dimensional innermost loop
1010
+ NPY_ITER_EXTERNAL_LOOP
1011
+ # Convert all the operands to a common data type
1012
+ NPY_ITER_COMMON_DTYPE
1013
+ # Operands may hold references, requiring API access during iteration
1014
+ NPY_ITER_REFS_OK
1015
+ # Zero-sized operands should be permitted, iteration checks IterSize for 0
1016
+ NPY_ITER_ZEROSIZE_OK
1017
+ # Permits reductions (size-0 stride with dimension size > 1)
1018
+ NPY_ITER_REDUCE_OK
1019
+ # Enables sub-range iteration
1020
+ NPY_ITER_RANGED
1021
+ # Enables buffering
1022
+ NPY_ITER_BUFFERED
1023
+ # When buffering is enabled, grows the inner loop if possible
1024
+ NPY_ITER_GROWINNER
1025
+ # Delay allocation of buffers until first Reset* call
1026
+ NPY_ITER_DELAY_BUFALLOC
1027
+ # When NPY_KEEPORDER is specified, disable reversing negative-stride axes
1028
+ NPY_ITER_DONT_NEGATE_STRIDES
1029
+ NPY_ITER_COPY_IF_OVERLAP
1030
+ # The operand will be read from and written to
1031
+ NPY_ITER_READWRITE
1032
+ # The operand will only be read from
1033
+ NPY_ITER_READONLY
1034
+ # The operand will only be written to
1035
+ NPY_ITER_WRITEONLY
1036
+ # The operand's data must be in native byte order
1037
+ NPY_ITER_NBO
1038
+ # The operand's data must be aligned
1039
+ NPY_ITER_ALIGNED
1040
+ # The operand's data must be contiguous (within the inner loop)
1041
+ NPY_ITER_CONTIG
1042
+ # The operand may be copied to satisfy requirements
1043
+ NPY_ITER_COPY
1044
+ # The operand may be copied with WRITEBACKIFCOPY to satisfy requirements
1045
+ NPY_ITER_UPDATEIFCOPY
1046
+ # Allocate the operand if it is NULL
1047
+ NPY_ITER_ALLOCATE
1048
+ # If an operand is allocated, don't use any subtype
1049
+ NPY_ITER_NO_SUBTYPE
1050
+ # This is a virtual array slot, operand is NULL but temporary data is there
1051
+ NPY_ITER_VIRTUAL
1052
+ # Require that the dimension match the iterator dimensions exactly
1053
+ NPY_ITER_NO_BROADCAST
1054
+ # A mask is being used on this array, affects buffer -> array copy
1055
+ NPY_ITER_WRITEMASKED
1056
+ # This array is the mask for all WRITEMASKED operands
1057
+ NPY_ITER_ARRAYMASK
1058
+ # Assume iterator order data access for COPY_IF_OVERLAP
1059
+ NPY_ITER_OVERLAP_ASSUME_ELEMENTWISE
1060
+
1061
+ # construction and destruction functions
1062
+ NpyIter* NpyIter_New(ndarray arr, npy_uint32 flags, NPY_ORDER order,
1063
+ NPY_CASTING casting, dtype datatype) except NULL
1064
+ NpyIter* NpyIter_MultiNew(npy_intp nop, PyArrayObject** op, npy_uint32 flags,
1065
+ NPY_ORDER order, NPY_CASTING casting, npy_uint32*
1066
+ op_flags, PyArray_Descr** op_dtypes) except NULL
1067
+ NpyIter* NpyIter_AdvancedNew(npy_intp nop, PyArrayObject** op,
1068
+ npy_uint32 flags, NPY_ORDER order,
1069
+ NPY_CASTING casting, npy_uint32* op_flags,
1070
+ PyArray_Descr** op_dtypes, int oa_ndim,
1071
+ int** op_axes, const npy_intp* itershape,
1072
+ npy_intp buffersize) except NULL
1073
+ NpyIter* NpyIter_Copy(NpyIter* it) except NULL
1074
+ int NpyIter_RemoveAxis(NpyIter* it, int axis) except NPY_FAIL
1075
+ int NpyIter_RemoveMultiIndex(NpyIter* it) except NPY_FAIL
1076
+ int NpyIter_EnableExternalLoop(NpyIter* it) except NPY_FAIL
1077
+ int NpyIter_Deallocate(NpyIter* it) except NPY_FAIL
1078
+ int NpyIter_Reset(NpyIter* it, char** errmsg) except NPY_FAIL
1079
+ int NpyIter_ResetToIterIndexRange(NpyIter* it, npy_intp istart,
1080
+ npy_intp iend, char** errmsg) except NPY_FAIL
1081
+ int NpyIter_ResetBasePointers(NpyIter* it, char** baseptrs, char** errmsg) except NPY_FAIL
1082
+ int NpyIter_GotoMultiIndex(NpyIter* it, const npy_intp* multi_index) except NPY_FAIL
1083
+ int NpyIter_GotoIndex(NpyIter* it, npy_intp index) except NPY_FAIL
1084
+ npy_intp NpyIter_GetIterSize(NpyIter* it) nogil
1085
+ npy_intp NpyIter_GetIterIndex(NpyIter* it) nogil
1086
+ void NpyIter_GetIterIndexRange(NpyIter* it, npy_intp* istart,
1087
+ npy_intp* iend) nogil
1088
+ int NpyIter_GotoIterIndex(NpyIter* it, npy_intp iterindex) except NPY_FAIL
1089
+ npy_bool NpyIter_HasDelayedBufAlloc(NpyIter* it) nogil
1090
+ npy_bool NpyIter_HasExternalLoop(NpyIter* it) nogil
1091
+ npy_bool NpyIter_HasMultiIndex(NpyIter* it) nogil
1092
+ npy_bool NpyIter_HasIndex(NpyIter* it) nogil
1093
+ npy_bool NpyIter_RequiresBuffering(NpyIter* it) nogil
1094
+ npy_bool NpyIter_IsBuffered(NpyIter* it) nogil
1095
+ npy_bool NpyIter_IsGrowInner(NpyIter* it) nogil
1096
+ npy_intp NpyIter_GetBufferSize(NpyIter* it) nogil
1097
+ int NpyIter_GetNDim(NpyIter* it) nogil
1098
+ int NpyIter_GetNOp(NpyIter* it) nogil
1099
+ npy_intp* NpyIter_GetAxisStrideArray(NpyIter* it, int axis) except NULL
1100
+ int NpyIter_GetShape(NpyIter* it, npy_intp* outshape) nogil
1101
+ PyArray_Descr** NpyIter_GetDescrArray(NpyIter* it)
1102
+ PyArrayObject** NpyIter_GetOperandArray(NpyIter* it)
1103
+ ndarray NpyIter_GetIterView(NpyIter* it, npy_intp i)
1104
+ void NpyIter_GetReadFlags(NpyIter* it, char* outreadflags)
1105
+ void NpyIter_GetWriteFlags(NpyIter* it, char* outwriteflags)
1106
+ int NpyIter_CreateCompatibleStrides(NpyIter* it, npy_intp itemsize,
1107
+ npy_intp* outstrides) except NPY_FAIL
1108
+ npy_bool NpyIter_IsFirstVisit(NpyIter* it, int iop) nogil
1109
+ # functions for iterating an NpyIter object
1110
+ #
1111
+ # These don't match the definition in the C API because Cython can't wrap
1112
+ # function pointers that return functions.
1113
+ NpyIter_IterNextFunc* NpyIter_GetIterNext(NpyIter* it, char** errmsg) except NULL
1114
+ NpyIter_GetMultiIndexFunc* NpyIter_GetGetMultiIndex(NpyIter* it,
1115
+ char** errmsg) except NULL
1116
+ char** NpyIter_GetDataPtrArray(NpyIter* it) nogil
1117
+ char** NpyIter_GetInitialDataPtrArray(NpyIter* it) nogil
1118
+ npy_intp* NpyIter_GetIndexPtr(NpyIter* it)
1119
+ npy_intp* NpyIter_GetInnerStrideArray(NpyIter* it) nogil
1120
+ npy_intp* NpyIter_GetInnerLoopSizePtr(NpyIter* it) nogil
1121
+ void NpyIter_GetInnerFixedStrideArray(NpyIter* it, npy_intp* outstrides) nogil
1122
+ npy_bool NpyIter_IterationNeedsAPI(NpyIter* it) nogil
1123
+ void NpyIter_DebugPrint(NpyIter* it)
1124
+
1125
+ # NpyString API
1126
+ cdef extern from "numpy/ndarraytypes.h":
1127
+ ctypedef struct npy_string_allocator:
1128
+ pass
1129
+
1130
+ ctypedef struct npy_packed_static_string:
1131
+ pass
1132
+
1133
+ ctypedef struct npy_static_string:
1134
+ size_t size
1135
+ const char *buf
1136
+
1137
+ ctypedef struct PyArray_StringDTypeObject:
1138
+ PyArray_Descr base
1139
+ PyObject *na_object
1140
+ char coerce
1141
+ char has_nan_na
1142
+ char has_string_na
1143
+ char array_owned
1144
+ npy_static_string default_string
1145
+ npy_static_string na_name
1146
+ npy_string_allocator *allocator
1147
+
1148
+ cdef extern from "numpy/arrayobject.h":
1149
+ npy_string_allocator *NpyString_acquire_allocator(const PyArray_StringDTypeObject *descr)
1150
+ void NpyString_acquire_allocators(size_t n_descriptors, PyArray_Descr *const descrs[], npy_string_allocator *allocators[])
1151
+ void NpyString_release_allocator(npy_string_allocator *allocator)
1152
+ void NpyString_release_allocators(size_t length, npy_string_allocator *allocators[])
1153
+ int NpyString_load(npy_string_allocator *allocator, const npy_packed_static_string *packed_string, npy_static_string *unpacked_string)
1154
+ int NpyString_pack_null(npy_string_allocator *allocator, npy_packed_static_string *packed_string)
1155
+ int NpyString_pack(npy_string_allocator *allocator, npy_packed_static_string *packed_string, const char *buf, size_t size)
.venv_haddock/lib/python3.12/site-packages/numpy/__init__.py ADDED
@@ -0,0 +1,942 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ NumPy
3
+ =====
4
+
5
+ Provides
6
+ 1. An array object of arbitrary homogeneous items
7
+ 2. Fast mathematical operations over arrays
8
+ 3. Linear Algebra, Fourier Transforms, Random Number Generation
9
+
10
+ How to use the documentation
11
+ ----------------------------
12
+ Documentation is available in two forms: docstrings provided
13
+ with the code, and a loose standing reference guide, available from
14
+ `the NumPy homepage <https://numpy.org>`_.
15
+
16
+ We recommend exploring the docstrings using
17
+ `IPython <https://ipython.org>`_, an advanced Python shell with
18
+ TAB-completion and introspection capabilities. See below for further
19
+ instructions.
20
+
21
+ The docstring examples assume that `numpy` has been imported as ``np``::
22
+
23
+ >>> import numpy as np
24
+
25
+ Code snippets are indicated by three greater-than signs::
26
+
27
+ >>> x = 42
28
+ >>> x = x + 1
29
+
30
+ Use the built-in ``help`` function to view a function's docstring::
31
+
32
+ >>> help(np.sort)
33
+ ... # doctest: +SKIP
34
+
35
+ For some objects, ``np.info(obj)`` may provide additional help. This is
36
+ particularly true if you see the line "Help on ufunc object:" at the top
37
+ of the help() page. Ufuncs are implemented in C, not Python, for speed.
38
+ The native Python help() does not know how to view their help, but our
39
+ np.info() function does.
40
+
41
+ Available subpackages
42
+ ---------------------
43
+ lib
44
+ Basic functions used by several sub-packages.
45
+ random
46
+ Core Random Tools
47
+ linalg
48
+ Core Linear Algebra Tools
49
+ fft
50
+ Core FFT routines
51
+ polynomial
52
+ Polynomial tools
53
+ testing
54
+ NumPy testing tools
55
+ distutils
56
+ Enhancements to distutils with support for
57
+ Fortran compilers support and more (for Python <= 3.11)
58
+
59
+ Utilities
60
+ ---------
61
+ test
62
+ Run numpy unittests
63
+ show_config
64
+ Show numpy build configuration
65
+ __version__
66
+ NumPy version string
67
+
68
+ Viewing documentation using IPython
69
+ -----------------------------------
70
+
71
+ Start IPython and import `numpy` usually under the alias ``np``: `import
72
+ numpy as np`. Then, directly past or use the ``%cpaste`` magic to paste
73
+ examples into the shell. To see which functions are available in `numpy`,
74
+ type ``np.<TAB>`` (where ``<TAB>`` refers to the TAB key), or use
75
+ ``np.*cos*?<ENTER>`` (where ``<ENTER>`` refers to the ENTER key) to narrow
76
+ down the list. To view the docstring for a function, use
77
+ ``np.cos?<ENTER>`` (to view the docstring) and ``np.cos??<ENTER>`` (to view
78
+ the source code).
79
+
80
+ Copies vs. in-place operation
81
+ -----------------------------
82
+ Most of the functions in `numpy` return a copy of the array argument
83
+ (e.g., `np.sort`). In-place versions of these functions are often
84
+ available as array methods, i.e. ``x = np.array([1,2,3]); x.sort()``.
85
+ Exceptions to this rule are documented.
86
+
87
+ """
88
+ import os
89
+ import sys
90
+ import warnings
91
+
92
+ # If a version with git hash was stored, use that instead
93
+ from . import version
94
+ from ._expired_attrs_2_0 import __expired_attributes__
95
+ from ._globals import _CopyMode, _NoValue
96
+ from .version import __version__
97
+
98
+ # We first need to detect if we're being called as part of the numpy setup
99
+ # procedure itself in a reliable manner.
100
+ try:
101
+ __NUMPY_SETUP__ # noqa: B018
102
+ except NameError:
103
+ __NUMPY_SETUP__ = False
104
+
105
+ if __NUMPY_SETUP__:
106
+ sys.stderr.write('Running from numpy source directory.\n')
107
+ else:
108
+ # Allow distributors to run custom init code before importing numpy._core
109
+ from . import _distributor_init
110
+
111
+ try:
112
+ from numpy.__config__ import show_config
113
+ except ImportError as e:
114
+ if isinstance(e, ModuleNotFoundError) and e.name == "numpy.__config__":
115
+ # The __config__ module itself was not found, so add this info:
116
+ msg = """Error importing numpy: you should not try to import numpy from
117
+ its source directory; please exit the numpy source tree, and relaunch
118
+ your python interpreter from there."""
119
+ raise ImportError(msg) from e
120
+ raise
121
+
122
+ from . import _core
123
+ from ._core import (
124
+ False_,
125
+ ScalarType,
126
+ True_,
127
+ abs,
128
+ absolute,
129
+ acos,
130
+ acosh,
131
+ add,
132
+ all,
133
+ allclose,
134
+ amax,
135
+ amin,
136
+ any,
137
+ arange,
138
+ arccos,
139
+ arccosh,
140
+ arcsin,
141
+ arcsinh,
142
+ arctan,
143
+ arctan2,
144
+ arctanh,
145
+ argmax,
146
+ argmin,
147
+ argpartition,
148
+ argsort,
149
+ argwhere,
150
+ around,
151
+ array,
152
+ array2string,
153
+ array_equal,
154
+ array_equiv,
155
+ array_repr,
156
+ array_str,
157
+ asanyarray,
158
+ asarray,
159
+ ascontiguousarray,
160
+ asfortranarray,
161
+ asin,
162
+ asinh,
163
+ astype,
164
+ atan,
165
+ atan2,
166
+ atanh,
167
+ atleast_1d,
168
+ atleast_2d,
169
+ atleast_3d,
170
+ base_repr,
171
+ binary_repr,
172
+ bitwise_and,
173
+ bitwise_count,
174
+ bitwise_invert,
175
+ bitwise_left_shift,
176
+ bitwise_not,
177
+ bitwise_or,
178
+ bitwise_right_shift,
179
+ bitwise_xor,
180
+ block,
181
+ bool,
182
+ bool_,
183
+ broadcast,
184
+ busday_count,
185
+ busday_offset,
186
+ busdaycalendar,
187
+ byte,
188
+ bytes_,
189
+ can_cast,
190
+ cbrt,
191
+ cdouble,
192
+ ceil,
193
+ character,
194
+ choose,
195
+ clip,
196
+ clongdouble,
197
+ complex64,
198
+ complex128,
199
+ complexfloating,
200
+ compress,
201
+ concat,
202
+ concatenate,
203
+ conj,
204
+ conjugate,
205
+ convolve,
206
+ copysign,
207
+ copyto,
208
+ correlate,
209
+ cos,
210
+ cosh,
211
+ count_nonzero,
212
+ cross,
213
+ csingle,
214
+ cumprod,
215
+ cumsum,
216
+ cumulative_prod,
217
+ cumulative_sum,
218
+ datetime64,
219
+ datetime_as_string,
220
+ datetime_data,
221
+ deg2rad,
222
+ degrees,
223
+ diagonal,
224
+ divide,
225
+ divmod,
226
+ dot,
227
+ double,
228
+ dtype,
229
+ e,
230
+ einsum,
231
+ einsum_path,
232
+ empty,
233
+ empty_like,
234
+ equal,
235
+ errstate,
236
+ euler_gamma,
237
+ exp,
238
+ exp2,
239
+ expm1,
240
+ fabs,
241
+ finfo,
242
+ flatiter,
243
+ flatnonzero,
244
+ flexible,
245
+ float16,
246
+ float32,
247
+ float64,
248
+ float_power,
249
+ floating,
250
+ floor,
251
+ floor_divide,
252
+ fmax,
253
+ fmin,
254
+ fmod,
255
+ format_float_positional,
256
+ format_float_scientific,
257
+ frexp,
258
+ from_dlpack,
259
+ frombuffer,
260
+ fromfile,
261
+ fromfunction,
262
+ fromiter,
263
+ frompyfunc,
264
+ fromstring,
265
+ full,
266
+ full_like,
267
+ gcd,
268
+ generic,
269
+ geomspace,
270
+ get_printoptions,
271
+ getbufsize,
272
+ geterr,
273
+ geterrcall,
274
+ greater,
275
+ greater_equal,
276
+ half,
277
+ heaviside,
278
+ hstack,
279
+ hypot,
280
+ identity,
281
+ iinfo,
282
+ indices,
283
+ inexact,
284
+ inf,
285
+ inner,
286
+ int8,
287
+ int16,
288
+ int32,
289
+ int64,
290
+ int_,
291
+ intc,
292
+ integer,
293
+ intp,
294
+ invert,
295
+ is_busday,
296
+ isclose,
297
+ isdtype,
298
+ isfinite,
299
+ isfortran,
300
+ isinf,
301
+ isnan,
302
+ isnat,
303
+ isscalar,
304
+ issubdtype,
305
+ lcm,
306
+ ldexp,
307
+ left_shift,
308
+ less,
309
+ less_equal,
310
+ lexsort,
311
+ linspace,
312
+ little_endian,
313
+ log,
314
+ log1p,
315
+ log2,
316
+ log10,
317
+ logaddexp,
318
+ logaddexp2,
319
+ logical_and,
320
+ logical_not,
321
+ logical_or,
322
+ logical_xor,
323
+ logspace,
324
+ long,
325
+ longdouble,
326
+ longlong,
327
+ matmul,
328
+ matrix_transpose,
329
+ matvec,
330
+ max,
331
+ maximum,
332
+ may_share_memory,
333
+ mean,
334
+ memmap,
335
+ min,
336
+ min_scalar_type,
337
+ minimum,
338
+ mod,
339
+ modf,
340
+ moveaxis,
341
+ multiply,
342
+ nan,
343
+ ndarray,
344
+ ndim,
345
+ nditer,
346
+ negative,
347
+ nested_iters,
348
+ newaxis,
349
+ nextafter,
350
+ nonzero,
351
+ not_equal,
352
+ number,
353
+ object_,
354
+ ones,
355
+ ones_like,
356
+ outer,
357
+ partition,
358
+ permute_dims,
359
+ pi,
360
+ positive,
361
+ pow,
362
+ power,
363
+ printoptions,
364
+ prod,
365
+ promote_types,
366
+ ptp,
367
+ put,
368
+ putmask,
369
+ rad2deg,
370
+ radians,
371
+ ravel,
372
+ recarray,
373
+ reciprocal,
374
+ record,
375
+ remainder,
376
+ repeat,
377
+ require,
378
+ reshape,
379
+ resize,
380
+ result_type,
381
+ right_shift,
382
+ rint,
383
+ roll,
384
+ rollaxis,
385
+ round,
386
+ sctypeDict,
387
+ searchsorted,
388
+ set_printoptions,
389
+ setbufsize,
390
+ seterr,
391
+ seterrcall,
392
+ shape,
393
+ shares_memory,
394
+ short,
395
+ sign,
396
+ signbit,
397
+ signedinteger,
398
+ sin,
399
+ single,
400
+ sinh,
401
+ size,
402
+ sort,
403
+ spacing,
404
+ sqrt,
405
+ square,
406
+ squeeze,
407
+ stack,
408
+ std,
409
+ str_,
410
+ subtract,
411
+ sum,
412
+ swapaxes,
413
+ take,
414
+ tan,
415
+ tanh,
416
+ tensordot,
417
+ timedelta64,
418
+ trace,
419
+ transpose,
420
+ true_divide,
421
+ trunc,
422
+ typecodes,
423
+ ubyte,
424
+ ufunc,
425
+ uint,
426
+ uint8,
427
+ uint16,
428
+ uint32,
429
+ uint64,
430
+ uintc,
431
+ uintp,
432
+ ulong,
433
+ ulonglong,
434
+ unsignedinteger,
435
+ unstack,
436
+ ushort,
437
+ var,
438
+ vdot,
439
+ vecdot,
440
+ vecmat,
441
+ void,
442
+ vstack,
443
+ where,
444
+ zeros,
445
+ zeros_like,
446
+ )
447
+
448
+ # NOTE: It's still under discussion whether these aliases
449
+ # should be removed.
450
+ for ta in ["float96", "float128", "complex192", "complex256"]:
451
+ try:
452
+ globals()[ta] = getattr(_core, ta)
453
+ except AttributeError:
454
+ pass
455
+ del ta
456
+
457
+ from . import lib, matrixlib as _mat
458
+ from .lib import scimath as emath
459
+ from .lib._arraypad_impl import pad
460
+ from .lib._arraysetops_impl import (
461
+ ediff1d,
462
+ intersect1d,
463
+ isin,
464
+ setdiff1d,
465
+ setxor1d,
466
+ union1d,
467
+ unique,
468
+ unique_all,
469
+ unique_counts,
470
+ unique_inverse,
471
+ unique_values,
472
+ )
473
+ from .lib._function_base_impl import (
474
+ angle,
475
+ append,
476
+ asarray_chkfinite,
477
+ average,
478
+ bartlett,
479
+ bincount,
480
+ blackman,
481
+ copy,
482
+ corrcoef,
483
+ cov,
484
+ delete,
485
+ diff,
486
+ digitize,
487
+ extract,
488
+ flip,
489
+ gradient,
490
+ hamming,
491
+ hanning,
492
+ i0,
493
+ insert,
494
+ interp,
495
+ iterable,
496
+ kaiser,
497
+ median,
498
+ meshgrid,
499
+ percentile,
500
+ piecewise,
501
+ place,
502
+ quantile,
503
+ rot90,
504
+ select,
505
+ sinc,
506
+ sort_complex,
507
+ trapezoid,
508
+ trim_zeros,
509
+ unwrap,
510
+ vectorize,
511
+ )
512
+ from .lib._histograms_impl import histogram, histogram_bin_edges, histogramdd
513
+ from .lib._index_tricks_impl import (
514
+ c_,
515
+ diag_indices,
516
+ diag_indices_from,
517
+ fill_diagonal,
518
+ index_exp,
519
+ ix_,
520
+ mgrid,
521
+ ndenumerate,
522
+ ndindex,
523
+ ogrid,
524
+ r_,
525
+ ravel_multi_index,
526
+ s_,
527
+ unravel_index,
528
+ )
529
+ from .lib._nanfunctions_impl import (
530
+ nanargmax,
531
+ nanargmin,
532
+ nancumprod,
533
+ nancumsum,
534
+ nanmax,
535
+ nanmean,
536
+ nanmedian,
537
+ nanmin,
538
+ nanpercentile,
539
+ nanprod,
540
+ nanquantile,
541
+ nanstd,
542
+ nansum,
543
+ nanvar,
544
+ )
545
+ from .lib._npyio_impl import (
546
+ fromregex,
547
+ genfromtxt,
548
+ load,
549
+ loadtxt,
550
+ packbits,
551
+ save,
552
+ savetxt,
553
+ savez,
554
+ savez_compressed,
555
+ unpackbits,
556
+ )
557
+ from .lib._polynomial_impl import (
558
+ poly,
559
+ poly1d,
560
+ polyadd,
561
+ polyder,
562
+ polydiv,
563
+ polyfit,
564
+ polyint,
565
+ polymul,
566
+ polysub,
567
+ polyval,
568
+ roots,
569
+ )
570
+ from .lib._shape_base_impl import (
571
+ apply_along_axis,
572
+ apply_over_axes,
573
+ array_split,
574
+ column_stack,
575
+ dsplit,
576
+ dstack,
577
+ expand_dims,
578
+ hsplit,
579
+ kron,
580
+ put_along_axis,
581
+ row_stack,
582
+ split,
583
+ take_along_axis,
584
+ tile,
585
+ vsplit,
586
+ )
587
+ from .lib._stride_tricks_impl import (
588
+ broadcast_arrays,
589
+ broadcast_shapes,
590
+ broadcast_to,
591
+ )
592
+ from .lib._twodim_base_impl import (
593
+ diag,
594
+ diagflat,
595
+ eye,
596
+ fliplr,
597
+ flipud,
598
+ histogram2d,
599
+ mask_indices,
600
+ tri,
601
+ tril,
602
+ tril_indices,
603
+ tril_indices_from,
604
+ triu,
605
+ triu_indices,
606
+ triu_indices_from,
607
+ vander,
608
+ )
609
+ from .lib._type_check_impl import (
610
+ common_type,
611
+ imag,
612
+ iscomplex,
613
+ iscomplexobj,
614
+ isreal,
615
+ isrealobj,
616
+ mintypecode,
617
+ nan_to_num,
618
+ real,
619
+ real_if_close,
620
+ typename,
621
+ )
622
+ from .lib._ufunclike_impl import fix, isneginf, isposinf
623
+ from .lib._utils_impl import get_include, info, show_runtime
624
+ from .matrixlib import asmatrix, bmat, matrix
625
+
626
+ # public submodules are imported lazily, therefore are accessible from
627
+ # __getattr__. Note that `distutils` (deprecated) and `array_api`
628
+ # (experimental label) are not added here, because `from numpy import *`
629
+ # must not raise any warnings - that's too disruptive.
630
+ __numpy_submodules__ = {
631
+ "linalg", "fft", "dtypes", "random", "polynomial", "ma",
632
+ "exceptions", "lib", "ctypeslib", "testing", "typing",
633
+ "f2py", "test", "rec", "char", "core", "strings",
634
+ }
635
+
636
+ # We build warning messages for former attributes
637
+ _msg = (
638
+ "module 'numpy' has no attribute '{n}'.\n"
639
+ "`np.{n}` was a deprecated alias for the builtin `{n}`. "
640
+ "To avoid this error in existing code, use `{n}` by itself. "
641
+ "Doing this will not modify any behavior and is safe. {extended_msg}\n"
642
+ "The aliases was originally deprecated in NumPy 1.20; for more "
643
+ "details and guidance see the original release note at:\n"
644
+ " https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations")
645
+
646
+ _specific_msg = (
647
+ "If you specifically wanted the numpy scalar type, use `np.{}` here.")
648
+
649
+ _int_extended_msg = (
650
+ "When replacing `np.{}`, you may wish to use e.g. `np.int64` "
651
+ "or `np.int32` to specify the precision. If you wish to review "
652
+ "your current use, check the release note link for "
653
+ "additional information.")
654
+
655
+ _type_info = [
656
+ ("object", ""), # The NumPy scalar only exists by name.
657
+ ("float", _specific_msg.format("float64")),
658
+ ("complex", _specific_msg.format("complex128")),
659
+ ("str", _specific_msg.format("str_")),
660
+ ("int", _int_extended_msg.format("int"))]
661
+
662
+ __former_attrs__ = {
663
+ n: _msg.format(n=n, extended_msg=extended_msg)
664
+ for n, extended_msg in _type_info
665
+ }
666
+
667
+ # Some of these could be defined right away, but most were aliases to
668
+ # the Python objects and only removed in NumPy 1.24. Defining them should
669
+ # probably wait for NumPy 1.26 or 2.0.
670
+ # When defined, these should possibly not be added to `__all__` to avoid
671
+ # import with `from numpy import *`.
672
+ __future_scalars__ = {"str", "bytes", "object"}
673
+
674
+ __array_api_version__ = "2024.12"
675
+
676
+ from ._array_api_info import __array_namespace_info__
677
+
678
+ __all__ = list(
679
+ __numpy_submodules__ |
680
+ set(_core.__all__) |
681
+ set(_mat.__all__) |
682
+ set(lib._histograms_impl.__all__) |
683
+ set(lib._nanfunctions_impl.__all__) |
684
+ set(lib._function_base_impl.__all__) |
685
+ set(lib._twodim_base_impl.__all__) |
686
+ set(lib._shape_base_impl.__all__) |
687
+ set(lib._type_check_impl.__all__) |
688
+ set(lib._arraysetops_impl.__all__) |
689
+ set(lib._ufunclike_impl.__all__) |
690
+ set(lib._arraypad_impl.__all__) |
691
+ set(lib._utils_impl.__all__) |
692
+ set(lib._stride_tricks_impl.__all__) |
693
+ set(lib._polynomial_impl.__all__) |
694
+ set(lib._npyio_impl.__all__) |
695
+ set(lib._index_tricks_impl.__all__) |
696
+ {"emath", "show_config", "__version__", "__array_namespace_info__"}
697
+ )
698
+
699
+ # Filter out Cython harmless warnings
700
+ warnings.filterwarnings("ignore", message="numpy.dtype size changed")
701
+ warnings.filterwarnings("ignore", message="numpy.ufunc size changed")
702
+ warnings.filterwarnings("ignore", message="numpy.ndarray size changed")
703
+
704
+ def __getattr__(attr):
705
+ # Warn for expired attributes
706
+ import warnings
707
+
708
+ if attr == "linalg":
709
+ import numpy.linalg as linalg
710
+ return linalg
711
+ elif attr == "fft":
712
+ import numpy.fft as fft
713
+ return fft
714
+ elif attr == "dtypes":
715
+ import numpy.dtypes as dtypes
716
+ return dtypes
717
+ elif attr == "random":
718
+ import numpy.random as random
719
+ return random
720
+ elif attr == "polynomial":
721
+ import numpy.polynomial as polynomial
722
+ return polynomial
723
+ elif attr == "ma":
724
+ import numpy.ma as ma
725
+ return ma
726
+ elif attr == "ctypeslib":
727
+ import numpy.ctypeslib as ctypeslib
728
+ return ctypeslib
729
+ elif attr == "exceptions":
730
+ import numpy.exceptions as exceptions
731
+ return exceptions
732
+ elif attr == "testing":
733
+ import numpy.testing as testing
734
+ return testing
735
+ elif attr == "matlib":
736
+ import numpy.matlib as matlib
737
+ return matlib
738
+ elif attr == "f2py":
739
+ import numpy.f2py as f2py
740
+ return f2py
741
+ elif attr == "typing":
742
+ import numpy.typing as typing
743
+ return typing
744
+ elif attr == "rec":
745
+ import numpy.rec as rec
746
+ return rec
747
+ elif attr == "char":
748
+ import numpy.char as char
749
+ return char
750
+ elif attr == "array_api":
751
+ raise AttributeError("`numpy.array_api` is not available from "
752
+ "numpy 2.0 onwards", name=None)
753
+ elif attr == "core":
754
+ import numpy.core as core
755
+ return core
756
+ elif attr == "strings":
757
+ import numpy.strings as strings
758
+ return strings
759
+ elif attr == "distutils":
760
+ if 'distutils' in __numpy_submodules__:
761
+ import numpy.distutils as distutils
762
+ return distutils
763
+ else:
764
+ raise AttributeError("`numpy.distutils` is not available from "
765
+ "Python 3.12 onwards", name=None)
766
+
767
+ if attr in __future_scalars__:
768
+ # And future warnings for those that will change, but also give
769
+ # the AttributeError
770
+ warnings.warn(
771
+ f"In the future `np.{attr}` will be defined as the "
772
+ "corresponding NumPy scalar.", FutureWarning, stacklevel=2)
773
+
774
+ if attr in __former_attrs__:
775
+ raise AttributeError(__former_attrs__[attr], name=None)
776
+
777
+ if attr in __expired_attributes__:
778
+ raise AttributeError(
779
+ f"`np.{attr}` was removed in the NumPy 2.0 release. "
780
+ f"{__expired_attributes__[attr]}",
781
+ name=None
782
+ )
783
+
784
+ if attr == "chararray":
785
+ warnings.warn(
786
+ "`np.chararray` is deprecated and will be removed from "
787
+ "the main namespace in the future. Use an array with a string "
788
+ "or bytes dtype instead.", DeprecationWarning, stacklevel=2)
789
+ import numpy.char as char
790
+ return char.chararray
791
+
792
+ raise AttributeError(f"module {__name__!r} has no attribute {attr!r}")
793
+
794
+ def __dir__():
795
+ public_symbols = (
796
+ globals().keys() | __numpy_submodules__
797
+ )
798
+ public_symbols -= {
799
+ "matrixlib", "matlib", "tests", "conftest", "version",
800
+ "distutils", "array_api"
801
+ }
802
+ return list(public_symbols)
803
+
804
+ # Pytest testing
805
+ from numpy._pytesttester import PytestTester
806
+ test = PytestTester(__name__)
807
+ del PytestTester
808
+
809
+ def _sanity_check():
810
+ """
811
+ Quick sanity checks for common bugs caused by environment.
812
+ There are some cases e.g. with wrong BLAS ABI that cause wrong
813
+ results under specific runtime conditions that are not necessarily
814
+ achieved during test suite runs, and it is useful to catch those early.
815
+
816
+ See https://github.com/numpy/numpy/issues/8577 and other
817
+ similar bug reports.
818
+
819
+ """
820
+ try:
821
+ x = ones(2, dtype=float32)
822
+ if not abs(x.dot(x) - float32(2.0)) < 1e-5:
823
+ raise AssertionError
824
+ except AssertionError:
825
+ msg = ("The current Numpy installation ({!r}) fails to "
826
+ "pass simple sanity checks. This can be caused for example "
827
+ "by incorrect BLAS library being linked in, or by mixing "
828
+ "package managers (pip, conda, apt, ...). Search closed "
829
+ "numpy issues for similar problems.")
830
+ raise RuntimeError(msg.format(__file__)) from None
831
+
832
+ _sanity_check()
833
+ del _sanity_check
834
+
835
+ def _mac_os_check():
836
+ """
837
+ Quick Sanity check for Mac OS look for accelerate build bugs.
838
+ Testing numpy polyfit calls init_dgelsd(LAPACK)
839
+ """
840
+ try:
841
+ c = array([3., 2., 1.])
842
+ x = linspace(0, 2, 5)
843
+ y = polyval(c, x)
844
+ _ = polyfit(x, y, 2, cov=True)
845
+ except ValueError:
846
+ pass
847
+
848
+ if sys.platform == "darwin":
849
+ from . import exceptions
850
+ with warnings.catch_warnings(record=True) as w:
851
+ _mac_os_check()
852
+ # Throw runtime error, if the test failed
853
+ # Check for warning and report the error_message
854
+ if len(w) > 0:
855
+ for _wn in w:
856
+ if _wn.category is exceptions.RankWarning:
857
+ # Ignore other warnings, they may not be relevant (see gh-25433)
858
+ error_message = (
859
+ f"{_wn.category.__name__}: {_wn.message}"
860
+ )
861
+ msg = (
862
+ "Polyfit sanity test emitted a warning, most likely due "
863
+ "to using a buggy Accelerate backend."
864
+ "\nIf you compiled yourself, more information is available at:" # noqa: E501
865
+ "\nhttps://numpy.org/devdocs/building/index.html"
866
+ "\nOtherwise report this to the vendor "
867
+ f"that provided NumPy.\n\n{error_message}\n")
868
+ raise RuntimeError(msg)
869
+ del _wn
870
+ del w
871
+ del _mac_os_check
872
+
873
+ def blas_fpe_check():
874
+ # Check if BLAS adds spurious FPEs, mostly seen on M4 arms with Accelerate.
875
+ with errstate(all='raise'):
876
+ x = ones((20, 20))
877
+ try:
878
+ x @ x
879
+ except FloatingPointError:
880
+ res = _core._multiarray_umath._blas_supports_fpe(False)
881
+ if res: # res was not modified (hardcoded to True for now)
882
+ warnings.warn(
883
+ "Spurious warnings given by blas but suppression not "
884
+ "set up on this platform. Please open a NumPy issue.",
885
+ UserWarning, stacklevel=2)
886
+
887
+ blas_fpe_check()
888
+ del blas_fpe_check
889
+
890
+ def hugepage_setup():
891
+ """
892
+ We usually use madvise hugepages support, but on some old kernels it
893
+ is slow and thus better avoided. Specifically kernel version 4.6
894
+ had a bug fix which probably fixed this:
895
+ https://github.com/torvalds/linux/commit/7cf91a98e607c2f935dbcc177d70011e95b8faff
896
+ """
897
+ use_hugepage = os.environ.get("NUMPY_MADVISE_HUGEPAGE", None)
898
+ if sys.platform == "linux" and use_hugepage is None:
899
+ # If there is an issue with parsing the kernel version,
900
+ # set use_hugepage to 0. Usage of LooseVersion will handle
901
+ # the kernel version parsing better, but avoided since it
902
+ # will increase the import time.
903
+ # See: #16679 for related discussion.
904
+ try:
905
+ use_hugepage = 1
906
+ kernel_version = os.uname().release.split(".")[:2]
907
+ kernel_version = tuple(int(v) for v in kernel_version)
908
+ if kernel_version < (4, 6):
909
+ use_hugepage = 0
910
+ except ValueError:
911
+ use_hugepage = 0
912
+ elif use_hugepage is None:
913
+ # This is not Linux, so it should not matter, just enable anyway
914
+ use_hugepage = 1
915
+ else:
916
+ use_hugepage = int(use_hugepage)
917
+ return use_hugepage
918
+
919
+ # Note that this will currently only make a difference on Linux
920
+ _core.multiarray._set_madvise_hugepage(hugepage_setup())
921
+ del hugepage_setup
922
+
923
+ # Give a warning if NumPy is reloaded or imported on a sub-interpreter
924
+ # We do this from python, since the C-module may not be reloaded and
925
+ # it is tidier organized.
926
+ _core.multiarray._multiarray_umath._reload_guard()
927
+
928
+ # TODO: Remove the environment variable entirely now that it is "weak"
929
+ if (os.environ.get("NPY_PROMOTION_STATE", "weak") != "weak"):
930
+ warnings.warn(
931
+ "NPY_PROMOTION_STATE was a temporary feature for NumPy 2.0 "
932
+ "transition and is ignored after NumPy 2.2.",
933
+ UserWarning, stacklevel=2)
934
+
935
+ # Tell PyInstaller where to find hook-numpy.py
936
+ def _pyinstaller_hooks_dir():
937
+ from pathlib import Path
938
+ return [str(Path(__file__).with_name("_pyinstaller").resolve())]
939
+
940
+
941
+ # Remove symbols imported for internal use
942
+ del os, sys, warnings
.venv_haddock/lib/python3.12/site-packages/numpy/__init__.pyi ADDED
The diff for this file is too large to render. See raw diff
 
.venv_haddock/lib/python3.12/site-packages/numpy/_array_api_info.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Array API Inspection namespace
3
+
4
+ This is the namespace for inspection functions as defined by the array API
5
+ standard. See
6
+ https://data-apis.org/array-api/latest/API_specification/inspection.html for
7
+ more details.
8
+
9
+ """
10
+ from numpy._core import (
11
+ bool,
12
+ complex64,
13
+ complex128,
14
+ dtype,
15
+ float32,
16
+ float64,
17
+ int8,
18
+ int16,
19
+ int32,
20
+ int64,
21
+ intp,
22
+ uint8,
23
+ uint16,
24
+ uint32,
25
+ uint64,
26
+ )
27
+ from numpy._utils import set_module
28
+
29
+
30
+ @set_module('numpy')
31
+ class __array_namespace_info__:
32
+ """
33
+ Get the array API inspection namespace for NumPy.
34
+
35
+ The array API inspection namespace defines the following functions:
36
+
37
+ - capabilities()
38
+ - default_device()
39
+ - default_dtypes()
40
+ - dtypes()
41
+ - devices()
42
+
43
+ See
44
+ https://data-apis.org/array-api/latest/API_specification/inspection.html
45
+ for more details.
46
+
47
+ Returns
48
+ -------
49
+ info : ModuleType
50
+ The array API inspection namespace for NumPy.
51
+
52
+ Examples
53
+ --------
54
+ >>> info = np.__array_namespace_info__()
55
+ >>> info.default_dtypes()
56
+ {'real floating': numpy.float64,
57
+ 'complex floating': numpy.complex128,
58
+ 'integral': numpy.int64,
59
+ 'indexing': numpy.int64}
60
+
61
+ """
62
+
63
+ def capabilities(self):
64
+ """
65
+ Return a dictionary of array API library capabilities.
66
+
67
+ The resulting dictionary has the following keys:
68
+
69
+ - **"boolean indexing"**: boolean indicating whether an array library
70
+ supports boolean indexing. Always ``True`` for NumPy.
71
+
72
+ - **"data-dependent shapes"**: boolean indicating whether an array
73
+ library supports data-dependent output shapes. Always ``True`` for
74
+ NumPy.
75
+
76
+ See
77
+ https://data-apis.org/array-api/latest/API_specification/generated/array_api.info.capabilities.html
78
+ for more details.
79
+
80
+ See Also
81
+ --------
82
+ __array_namespace_info__.default_device,
83
+ __array_namespace_info__.default_dtypes,
84
+ __array_namespace_info__.dtypes,
85
+ __array_namespace_info__.devices
86
+
87
+ Returns
88
+ -------
89
+ capabilities : dict
90
+ A dictionary of array API library capabilities.
91
+
92
+ Examples
93
+ --------
94
+ >>> info = np.__array_namespace_info__()
95
+ >>> info.capabilities()
96
+ {'boolean indexing': True,
97
+ 'data-dependent shapes': True,
98
+ 'max dimensions': 64}
99
+
100
+ """
101
+ return {
102
+ "boolean indexing": True,
103
+ "data-dependent shapes": True,
104
+ "max dimensions": 64,
105
+ }
106
+
107
+ def default_device(self):
108
+ """
109
+ The default device used for new NumPy arrays.
110
+
111
+ For NumPy, this always returns ``'cpu'``.
112
+
113
+ See Also
114
+ --------
115
+ __array_namespace_info__.capabilities,
116
+ __array_namespace_info__.default_dtypes,
117
+ __array_namespace_info__.dtypes,
118
+ __array_namespace_info__.devices
119
+
120
+ Returns
121
+ -------
122
+ device : str
123
+ The default device used for new NumPy arrays.
124
+
125
+ Examples
126
+ --------
127
+ >>> info = np.__array_namespace_info__()
128
+ >>> info.default_device()
129
+ 'cpu'
130
+
131
+ """
132
+ return "cpu"
133
+
134
+ def default_dtypes(self, *, device=None):
135
+ """
136
+ The default data types used for new NumPy arrays.
137
+
138
+ For NumPy, this always returns the following dictionary:
139
+
140
+ - **"real floating"**: ``numpy.float64``
141
+ - **"complex floating"**: ``numpy.complex128``
142
+ - **"integral"**: ``numpy.intp``
143
+ - **"indexing"**: ``numpy.intp``
144
+
145
+ Parameters
146
+ ----------
147
+ device : str, optional
148
+ The device to get the default data types for. For NumPy, only
149
+ ``'cpu'`` is allowed.
150
+
151
+ Returns
152
+ -------
153
+ dtypes : dict
154
+ A dictionary describing the default data types used for new NumPy
155
+ arrays.
156
+
157
+ See Also
158
+ --------
159
+ __array_namespace_info__.capabilities,
160
+ __array_namespace_info__.default_device,
161
+ __array_namespace_info__.dtypes,
162
+ __array_namespace_info__.devices
163
+
164
+ Examples
165
+ --------
166
+ >>> info = np.__array_namespace_info__()
167
+ >>> info.default_dtypes()
168
+ {'real floating': numpy.float64,
169
+ 'complex floating': numpy.complex128,
170
+ 'integral': numpy.int64,
171
+ 'indexing': numpy.int64}
172
+
173
+ """
174
+ if device not in ["cpu", None]:
175
+ raise ValueError(
176
+ 'Device not understood. Only "cpu" is allowed, but received:'
177
+ f' {device}'
178
+ )
179
+ return {
180
+ "real floating": dtype(float64),
181
+ "complex floating": dtype(complex128),
182
+ "integral": dtype(intp),
183
+ "indexing": dtype(intp),
184
+ }
185
+
186
+ def dtypes(self, *, device=None, kind=None):
187
+ """
188
+ The array API data types supported by NumPy.
189
+
190
+ Note that this function only returns data types that are defined by
191
+ the array API.
192
+
193
+ Parameters
194
+ ----------
195
+ device : str, optional
196
+ The device to get the data types for. For NumPy, only ``'cpu'`` is
197
+ allowed.
198
+ kind : str or tuple of str, optional
199
+ The kind of data types to return. If ``None``, all data types are
200
+ returned. If a string, only data types of that kind are returned.
201
+ If a tuple, a dictionary containing the union of the given kinds
202
+ is returned. The following kinds are supported:
203
+
204
+ - ``'bool'``: boolean data types (i.e., ``bool``).
205
+ - ``'signed integer'``: signed integer data types (i.e., ``int8``,
206
+ ``int16``, ``int32``, ``int64``).
207
+ - ``'unsigned integer'``: unsigned integer data types (i.e.,
208
+ ``uint8``, ``uint16``, ``uint32``, ``uint64``).
209
+ - ``'integral'``: integer data types. Shorthand for ``('signed
210
+ integer', 'unsigned integer')``.
211
+ - ``'real floating'``: real-valued floating-point data types
212
+ (i.e., ``float32``, ``float64``).
213
+ - ``'complex floating'``: complex floating-point data types (i.e.,
214
+ ``complex64``, ``complex128``).
215
+ - ``'numeric'``: numeric data types. Shorthand for ``('integral',
216
+ 'real floating', 'complex floating')``.
217
+
218
+ Returns
219
+ -------
220
+ dtypes : dict
221
+ A dictionary mapping the names of data types to the corresponding
222
+ NumPy data types.
223
+
224
+ See Also
225
+ --------
226
+ __array_namespace_info__.capabilities,
227
+ __array_namespace_info__.default_device,
228
+ __array_namespace_info__.default_dtypes,
229
+ __array_namespace_info__.devices
230
+
231
+ Examples
232
+ --------
233
+ >>> info = np.__array_namespace_info__()
234
+ >>> info.dtypes(kind='signed integer')
235
+ {'int8': numpy.int8,
236
+ 'int16': numpy.int16,
237
+ 'int32': numpy.int32,
238
+ 'int64': numpy.int64}
239
+
240
+ """
241
+ if device not in ["cpu", None]:
242
+ raise ValueError(
243
+ 'Device not understood. Only "cpu" is allowed, but received:'
244
+ f' {device}'
245
+ )
246
+ if kind is None:
247
+ return {
248
+ "bool": dtype(bool),
249
+ "int8": dtype(int8),
250
+ "int16": dtype(int16),
251
+ "int32": dtype(int32),
252
+ "int64": dtype(int64),
253
+ "uint8": dtype(uint8),
254
+ "uint16": dtype(uint16),
255
+ "uint32": dtype(uint32),
256
+ "uint64": dtype(uint64),
257
+ "float32": dtype(float32),
258
+ "float64": dtype(float64),
259
+ "complex64": dtype(complex64),
260
+ "complex128": dtype(complex128),
261
+ }
262
+ if kind == "bool":
263
+ return {"bool": bool}
264
+ if kind == "signed integer":
265
+ return {
266
+ "int8": dtype(int8),
267
+ "int16": dtype(int16),
268
+ "int32": dtype(int32),
269
+ "int64": dtype(int64),
270
+ }
271
+ if kind == "unsigned integer":
272
+ return {
273
+ "uint8": dtype(uint8),
274
+ "uint16": dtype(uint16),
275
+ "uint32": dtype(uint32),
276
+ "uint64": dtype(uint64),
277
+ }
278
+ if kind == "integral":
279
+ return {
280
+ "int8": dtype(int8),
281
+ "int16": dtype(int16),
282
+ "int32": dtype(int32),
283
+ "int64": dtype(int64),
284
+ "uint8": dtype(uint8),
285
+ "uint16": dtype(uint16),
286
+ "uint32": dtype(uint32),
287
+ "uint64": dtype(uint64),
288
+ }
289
+ if kind == "real floating":
290
+ return {
291
+ "float32": dtype(float32),
292
+ "float64": dtype(float64),
293
+ }
294
+ if kind == "complex floating":
295
+ return {
296
+ "complex64": dtype(complex64),
297
+ "complex128": dtype(complex128),
298
+ }
299
+ if kind == "numeric":
300
+ return {
301
+ "int8": dtype(int8),
302
+ "int16": dtype(int16),
303
+ "int32": dtype(int32),
304
+ "int64": dtype(int64),
305
+ "uint8": dtype(uint8),
306
+ "uint16": dtype(uint16),
307
+ "uint32": dtype(uint32),
308
+ "uint64": dtype(uint64),
309
+ "float32": dtype(float32),
310
+ "float64": dtype(float64),
311
+ "complex64": dtype(complex64),
312
+ "complex128": dtype(complex128),
313
+ }
314
+ if isinstance(kind, tuple):
315
+ res = {}
316
+ for k in kind:
317
+ res.update(self.dtypes(kind=k))
318
+ return res
319
+ raise ValueError(f"unsupported kind: {kind!r}")
320
+
321
+ def devices(self):
322
+ """
323
+ The devices supported by NumPy.
324
+
325
+ For NumPy, this always returns ``['cpu']``.
326
+
327
+ Returns
328
+ -------
329
+ devices : list of str
330
+ The devices supported by NumPy.
331
+
332
+ See Also
333
+ --------
334
+ __array_namespace_info__.capabilities,
335
+ __array_namespace_info__.default_device,
336
+ __array_namespace_info__.default_dtypes,
337
+ __array_namespace_info__.dtypes
338
+
339
+ Examples
340
+ --------
341
+ >>> info = np.__array_namespace_info__()
342
+ >>> info.devices()
343
+ ['cpu']
344
+
345
+ """
346
+ return ["cpu"]
.venv_haddock/lib/python3.12/site-packages/numpy/_array_api_info.pyi ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import (
2
+ Literal,
3
+ Never,
4
+ TypeAlias,
5
+ TypedDict,
6
+ TypeVar,
7
+ final,
8
+ overload,
9
+ type_check_only,
10
+ )
11
+
12
+ import numpy as np
13
+
14
+ _Device: TypeAlias = Literal["cpu"]
15
+ _DeviceLike: TypeAlias = _Device | None
16
+
17
+ _Capabilities = TypedDict(
18
+ "_Capabilities",
19
+ {
20
+ "boolean indexing": Literal[True],
21
+ "data-dependent shapes": Literal[True],
22
+ },
23
+ )
24
+
25
+ _DefaultDTypes = TypedDict(
26
+ "_DefaultDTypes",
27
+ {
28
+ "real floating": np.dtype[np.float64],
29
+ "complex floating": np.dtype[np.complex128],
30
+ "integral": np.dtype[np.intp],
31
+ "indexing": np.dtype[np.intp],
32
+ },
33
+ )
34
+
35
+ _KindBool: TypeAlias = Literal["bool"]
36
+ _KindInt: TypeAlias = Literal["signed integer"]
37
+ _KindUInt: TypeAlias = Literal["unsigned integer"]
38
+ _KindInteger: TypeAlias = Literal["integral"]
39
+ _KindFloat: TypeAlias = Literal["real floating"]
40
+ _KindComplex: TypeAlias = Literal["complex floating"]
41
+ _KindNumber: TypeAlias = Literal["numeric"]
42
+ _Kind: TypeAlias = (
43
+ _KindBool
44
+ | _KindInt
45
+ | _KindUInt
46
+ | _KindInteger
47
+ | _KindFloat
48
+ | _KindComplex
49
+ | _KindNumber
50
+ )
51
+
52
+ _T1 = TypeVar("_T1")
53
+ _T2 = TypeVar("_T2")
54
+ _T3 = TypeVar("_T3")
55
+ _Permute1: TypeAlias = _T1 | tuple[_T1]
56
+ _Permute2: TypeAlias = tuple[_T1, _T2] | tuple[_T2, _T1]
57
+ _Permute3: TypeAlias = (
58
+ tuple[_T1, _T2, _T3] | tuple[_T1, _T3, _T2]
59
+ | tuple[_T2, _T1, _T3] | tuple[_T2, _T3, _T1]
60
+ | tuple[_T3, _T1, _T2] | tuple[_T3, _T2, _T1]
61
+ )
62
+
63
+ @type_check_only
64
+ class _DTypesBool(TypedDict):
65
+ bool: np.dtype[np.bool]
66
+
67
+ @type_check_only
68
+ class _DTypesInt(TypedDict):
69
+ int8: np.dtype[np.int8]
70
+ int16: np.dtype[np.int16]
71
+ int32: np.dtype[np.int32]
72
+ int64: np.dtype[np.int64]
73
+
74
+ @type_check_only
75
+ class _DTypesUInt(TypedDict):
76
+ uint8: np.dtype[np.uint8]
77
+ uint16: np.dtype[np.uint16]
78
+ uint32: np.dtype[np.uint32]
79
+ uint64: np.dtype[np.uint64]
80
+
81
+ @type_check_only
82
+ class _DTypesInteger(_DTypesInt, _DTypesUInt): ...
83
+
84
+ @type_check_only
85
+ class _DTypesFloat(TypedDict):
86
+ float32: np.dtype[np.float32]
87
+ float64: np.dtype[np.float64]
88
+
89
+ @type_check_only
90
+ class _DTypesComplex(TypedDict):
91
+ complex64: np.dtype[np.complex64]
92
+ complex128: np.dtype[np.complex128]
93
+
94
+ @type_check_only
95
+ class _DTypesNumber(_DTypesInteger, _DTypesFloat, _DTypesComplex): ...
96
+
97
+ @type_check_only
98
+ class _DTypes(_DTypesBool, _DTypesNumber): ...
99
+
100
+ @type_check_only
101
+ class _DTypesUnion(TypedDict, total=False):
102
+ bool: np.dtype[np.bool]
103
+ int8: np.dtype[np.int8]
104
+ int16: np.dtype[np.int16]
105
+ int32: np.dtype[np.int32]
106
+ int64: np.dtype[np.int64]
107
+ uint8: np.dtype[np.uint8]
108
+ uint16: np.dtype[np.uint16]
109
+ uint32: np.dtype[np.uint32]
110
+ uint64: np.dtype[np.uint64]
111
+ float32: np.dtype[np.float32]
112
+ float64: np.dtype[np.float64]
113
+ complex64: np.dtype[np.complex64]
114
+ complex128: np.dtype[np.complex128]
115
+
116
+ _EmptyDict: TypeAlias = dict[Never, Never]
117
+
118
+ @final
119
+ class __array_namespace_info__:
120
+ __module__: Literal["numpy"] = "numpy"
121
+
122
+ def capabilities(self) -> _Capabilities: ...
123
+ def default_device(self) -> _Device: ...
124
+ def default_dtypes(
125
+ self,
126
+ *,
127
+ device: _DeviceLike = None,
128
+ ) -> _DefaultDTypes: ...
129
+ def devices(self) -> list[_Device]: ...
130
+
131
+ @overload
132
+ def dtypes(
133
+ self,
134
+ *,
135
+ device: _DeviceLike = None,
136
+ kind: None = None,
137
+ ) -> _DTypes: ...
138
+ @overload
139
+ def dtypes(
140
+ self,
141
+ *,
142
+ device: _DeviceLike = None,
143
+ kind: _Permute1[_KindBool],
144
+ ) -> _DTypesBool: ...
145
+ @overload
146
+ def dtypes(
147
+ self,
148
+ *,
149
+ device: _DeviceLike = None,
150
+ kind: _Permute1[_KindInt],
151
+ ) -> _DTypesInt: ...
152
+ @overload
153
+ def dtypes(
154
+ self,
155
+ *,
156
+ device: _DeviceLike = None,
157
+ kind: _Permute1[_KindUInt],
158
+ ) -> _DTypesUInt: ...
159
+ @overload
160
+ def dtypes(
161
+ self,
162
+ *,
163
+ device: _DeviceLike = None,
164
+ kind: _Permute1[_KindFloat],
165
+ ) -> _DTypesFloat: ...
166
+ @overload
167
+ def dtypes(
168
+ self,
169
+ *,
170
+ device: _DeviceLike = None,
171
+ kind: _Permute1[_KindComplex],
172
+ ) -> _DTypesComplex: ...
173
+ @overload
174
+ def dtypes(
175
+ self,
176
+ *,
177
+ device: _DeviceLike = None,
178
+ kind: (
179
+ _Permute1[_KindInteger]
180
+ | _Permute2[_KindInt, _KindUInt]
181
+ ),
182
+ ) -> _DTypesInteger: ...
183
+ @overload
184
+ def dtypes(
185
+ self,
186
+ *,
187
+ device: _DeviceLike = None,
188
+ kind: (
189
+ _Permute1[_KindNumber]
190
+ | _Permute3[_KindInteger, _KindFloat, _KindComplex]
191
+ ),
192
+ ) -> _DTypesNumber: ...
193
+ @overload
194
+ def dtypes(
195
+ self,
196
+ *,
197
+ device: _DeviceLike = None,
198
+ kind: tuple[()],
199
+ ) -> _EmptyDict: ...
200
+ @overload
201
+ def dtypes(
202
+ self,
203
+ *,
204
+ device: _DeviceLike = None,
205
+ kind: tuple[_Kind, ...],
206
+ ) -> _DTypesUnion: ...
.venv_haddock/lib/python3.12/site-packages/numpy/_configtool.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import sys
3
+ from pathlib import Path
4
+
5
+ from .lib._utils_impl import get_include
6
+ from .version import __version__
7
+
8
+
9
+ def main() -> None:
10
+ parser = argparse.ArgumentParser()
11
+ parser.add_argument(
12
+ "--version",
13
+ action="version",
14
+ version=__version__,
15
+ help="Print the version and exit.",
16
+ )
17
+ parser.add_argument(
18
+ "--cflags",
19
+ action="store_true",
20
+ help="Compile flag needed when using the NumPy headers.",
21
+ )
22
+ parser.add_argument(
23
+ "--pkgconfigdir",
24
+ action="store_true",
25
+ help=("Print the pkgconfig directory in which `numpy.pc` is stored "
26
+ "(useful for setting $PKG_CONFIG_PATH)."),
27
+ )
28
+ args = parser.parse_args()
29
+ if not sys.argv[1:]:
30
+ parser.print_help()
31
+ if args.cflags:
32
+ print("-I" + get_include())
33
+ if args.pkgconfigdir:
34
+ _path = Path(get_include()) / '..' / 'lib' / 'pkgconfig'
35
+ print(_path.resolve())
36
+
37
+
38
+ if __name__ == "__main__":
39
+ main()
.venv_haddock/lib/python3.12/site-packages/numpy/_distributor_init.pyi ADDED
@@ -0,0 +1 @@
 
 
1
+ # intentionally left blank
.venv_haddock/lib/python3.12/site-packages/numpy/_globals.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module defining global singleton classes.
3
+
4
+ This module raises a RuntimeError if an attempt to reload it is made. In that
5
+ way the identities of the classes defined here are fixed and will remain so
6
+ even if numpy itself is reloaded. In particular, a function like the following
7
+ will still work correctly after numpy is reloaded::
8
+
9
+ def foo(arg=np._NoValue):
10
+ if arg is np._NoValue:
11
+ ...
12
+
13
+ That was not the case when the singleton classes were defined in the numpy
14
+ ``__init__.py`` file. See gh-7844 for a discussion of the reload problem that
15
+ motivated this module.
16
+
17
+ """
18
+ import enum
19
+
20
+ from ._utils import set_module as _set_module
21
+
22
+ __all__ = ['_NoValue', '_CopyMode']
23
+
24
+
25
+ # Disallow reloading this module so as to preserve the identities of the
26
+ # classes defined here.
27
+ if '_is_loaded' in globals():
28
+ raise RuntimeError('Reloading numpy._globals is not allowed')
29
+ _is_loaded = True
30
+
31
+
32
+ class _NoValueType:
33
+ """Special keyword value.
34
+
35
+ The instance of this class may be used as the default value assigned to a
36
+ keyword if no other obvious default (e.g., `None`) is suitable,
37
+
38
+ Common reasons for using this keyword are:
39
+
40
+ - A new keyword is added to a function, and that function forwards its
41
+ inputs to another function or method which can be defined outside of
42
+ NumPy. For example, ``np.std(x)`` calls ``x.std``, so when a ``keepdims``
43
+ keyword was added that could only be forwarded if the user explicitly
44
+ specified ``keepdims``; downstream array libraries may not have added
45
+ the same keyword, so adding ``x.std(..., keepdims=keepdims)``
46
+ unconditionally could have broken previously working code.
47
+ - A keyword is being deprecated, and a deprecation warning must only be
48
+ emitted when the keyword is used.
49
+
50
+ """
51
+ __instance = None
52
+
53
+ def __new__(cls):
54
+ # ensure that only one instance exists
55
+ if not cls.__instance:
56
+ cls.__instance = super().__new__(cls)
57
+ return cls.__instance
58
+
59
+ def __repr__(self):
60
+ return "<no value>"
61
+
62
+
63
+ _NoValue = _NoValueType()
64
+
65
+
66
+ @_set_module("numpy")
67
+ class _CopyMode(enum.Enum):
68
+ """
69
+ An enumeration for the copy modes supported
70
+ by numpy.copy() and numpy.array(). The following three modes are supported,
71
+
72
+ - ALWAYS: This means that a deep copy of the input
73
+ array will always be taken.
74
+ - IF_NEEDED: This means that a deep copy of the input
75
+ array will be taken only if necessary.
76
+ - NEVER: This means that the deep copy will never be taken.
77
+ If a copy cannot be avoided then a `ValueError` will be
78
+ raised.
79
+
80
+ Note that the buffer-protocol could in theory do copies. NumPy currently
81
+ assumes an object exporting the buffer protocol will never do this.
82
+ """
83
+
84
+ ALWAYS = True
85
+ NEVER = False
86
+ IF_NEEDED = 2
87
+
88
+ def __bool__(self):
89
+ # For backwards compatibility
90
+ if self == _CopyMode.ALWAYS:
91
+ return True
92
+
93
+ if self == _CopyMode.NEVER:
94
+ return False
95
+
96
+ raise ValueError(f"{self} is neither True nor False.")
97
+
98
+
99
+ class _SignatureDescriptor:
100
+ # A descriptor to store on the ufunc __dict__ that avoids definig a
101
+ # signature for the ufunc class/type but allows the instance to have one.
102
+ # This is needed because inspect.signature() chokes on normal properties
103
+ # (as of 3.14 at least).
104
+ # We could also set __signature__ on the instance but this allows deferred
105
+ # computation of the signature.
106
+ def __get__(self, obj, objtype=None):
107
+ # Delay import, not a critical path but need to avoid circular import.
108
+ from numpy._core._internal import _ufunc_inspect_signature_builder
109
+
110
+ if obj is None:
111
+ # could also return None, which is accepted as "not set" by
112
+ # inspect.signature().
113
+ raise AttributeError(
114
+ "type object 'numpy.ufunc' has no attribute '__signature__'")
115
+
116
+ # Store on the instance, after this the descriptor won't be used.
117
+ obj.__signature__ = _ufunc_inspect_signature_builder(obj)
118
+ return obj.__signature__
119
+
120
+
121
+ _signature_descriptor = _SignatureDescriptor()
.venv_haddock/lib/python3.12/site-packages/numpy/_globals.pyi ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = ["_CopyMode", "_NoValue"]
2
+
3
+ import enum
4
+ from typing import Final, final
5
+
6
+ @final
7
+ class _CopyMode(enum.Enum):
8
+ ALWAYS = True
9
+ NEVER = False
10
+ IF_NEEDED = 2
11
+
12
+ def __bool__(self, /) -> bool: ...
13
+
14
+ @final
15
+ class _NoValueType: ...
16
+
17
+ _NoValue: Final[_NoValueType] = ...
.venv_haddock/lib/python3.12/site-packages/numpy/_pytesttester.pyi ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Iterable
2
+ from typing import Literal as L
3
+
4
+ __all__ = ["PytestTester"]
5
+
6
+ class PytestTester:
7
+ module_name: str
8
+ def __init__(self, module_name: str) -> None: ...
9
+ def __call__(
10
+ self,
11
+ label: L["fast", "full"] = "fast",
12
+ verbose: int = 1,
13
+ extra_argv: Iterable[str] | None = None,
14
+ doctests: L[False] = False,
15
+ coverage: bool = False,
16
+ durations: int = -1,
17
+ tests: Iterable[str] | None = None,
18
+ ) -> bool: ...
.venv_haddock/lib/python3.12/site-packages/numpy/conftest.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pytest configuration and fixtures for the Numpy test suite.
3
+ """
4
+ import os
5
+ import sys
6
+ import tempfile
7
+ import warnings
8
+ from contextlib import contextmanager
9
+ from pathlib import Path
10
+
11
+ import hypothesis
12
+ import pytest
13
+
14
+ import numpy
15
+ from numpy._core._multiarray_tests import get_fpu_mode
16
+ from numpy.testing._private.utils import NOGIL_BUILD
17
+
18
+ try:
19
+ from scipy_doctest.conftest import dt_config
20
+ HAVE_SCPDT = True
21
+ except ModuleNotFoundError:
22
+ HAVE_SCPDT = False
23
+
24
+ try:
25
+ import pytest_run_parallel # noqa: F401
26
+ PARALLEL_RUN_AVALIABLE = True
27
+ except ModuleNotFoundError:
28
+ PARALLEL_RUN_AVALIABLE = False
29
+
30
+ _old_fpu_mode = None
31
+ _collect_results = {}
32
+
33
+ # Use a known and persistent tmpdir for hypothesis' caches, which
34
+ # can be automatically cleared by the OS or user.
35
+ hypothesis.configuration.set_hypothesis_home_dir(
36
+ os.path.join(tempfile.gettempdir(), ".hypothesis")
37
+ )
38
+
39
+ # We register two custom profiles for Numpy - for details see
40
+ # https://hypothesis.readthedocs.io/en/latest/settings.html
41
+ # The first is designed for our own CI runs; the latter also
42
+ # forces determinism and is designed for use via np.test()
43
+ hypothesis.settings.register_profile(
44
+ name="numpy-profile", deadline=None, print_blob=True,
45
+ )
46
+ hypothesis.settings.register_profile(
47
+ name="np.test() profile",
48
+ deadline=None, print_blob=True, database=None, derandomize=True,
49
+ suppress_health_check=list(hypothesis.HealthCheck),
50
+ )
51
+ # Note that the default profile is chosen based on the presence
52
+ # of pytest.ini, but can be overridden by passing the
53
+ # --hypothesis-profile=NAME argument to pytest.
54
+ _pytest_ini = os.path.join(os.path.dirname(__file__), "..", "pytest.ini")
55
+ hypothesis.settings.load_profile(
56
+ "numpy-profile" if os.path.isfile(_pytest_ini) else "np.test() profile"
57
+ )
58
+
59
+ # The experimentalAPI is used in _umath_tests
60
+ os.environ["NUMPY_EXPERIMENTAL_DTYPE_API"] = "1"
61
+
62
+ def pytest_configure(config):
63
+ config.addinivalue_line("markers",
64
+ "valgrind_error: Tests that are known to error under valgrind.")
65
+ config.addinivalue_line("markers",
66
+ "leaks_references: Tests that are known to leak references.")
67
+ config.addinivalue_line("markers",
68
+ "slow: Tests that are very slow.")
69
+ config.addinivalue_line("markers",
70
+ "slow_pypy: Tests that are very slow on pypy.")
71
+ if not PARALLEL_RUN_AVALIABLE:
72
+ config.addinivalue_line("markers",
73
+ "parallel_threads(n): run the given test function in parallel "
74
+ "using `n` threads.",
75
+ )
76
+ config.addinivalue_line("markers",
77
+ "iterations(n): run the given test function `n` times in each thread",
78
+ )
79
+ config.addinivalue_line("markers",
80
+ "thread_unsafe: mark the test function as single-threaded",
81
+ )
82
+
83
+
84
+ def pytest_addoption(parser):
85
+ parser.addoption("--available-memory", action="store", default=None,
86
+ help=("Set amount of memory available for running the "
87
+ "test suite. This can result to tests requiring "
88
+ "especially large amounts of memory to be skipped. "
89
+ "Equivalent to setting environment variable "
90
+ "NPY_AVAILABLE_MEM. Default: determined"
91
+ "automatically."))
92
+
93
+
94
+ gil_enabled_at_start = True
95
+ if NOGIL_BUILD:
96
+ gil_enabled_at_start = sys._is_gil_enabled()
97
+
98
+
99
+ def pytest_sessionstart(session):
100
+ available_mem = session.config.getoption('available_memory')
101
+ if available_mem is not None:
102
+ os.environ['NPY_AVAILABLE_MEM'] = available_mem
103
+
104
+
105
+ def pytest_terminal_summary(terminalreporter, exitstatus, config):
106
+ if NOGIL_BUILD and not gil_enabled_at_start and sys._is_gil_enabled():
107
+ tr = terminalreporter
108
+ tr.ensure_newline()
109
+ tr.section("GIL re-enabled", sep="=", red=True, bold=True)
110
+ tr.line("The GIL was re-enabled at runtime during the tests.")
111
+ tr.line("This can happen with no test failures if the RuntimeWarning")
112
+ tr.line("raised by Python when this happens is filtered by a test.")
113
+ tr.line("")
114
+ tr.line("Please ensure all new C modules declare support for running")
115
+ tr.line("without the GIL. Any new tests that intentionally imports ")
116
+ tr.line("code that re-enables the GIL should do so in a subprocess.")
117
+ pytest.exit("GIL re-enabled during tests", returncode=1)
118
+
119
+ # FIXME when yield tests are gone.
120
+ @pytest.hookimpl(tryfirst=True)
121
+ def pytest_itemcollected(item):
122
+ """
123
+ Check FPU precision mode was not changed during test collection.
124
+
125
+ The clumsy way we do it here is mainly necessary because numpy
126
+ still uses yield tests, which can execute code at test collection
127
+ time.
128
+ """
129
+ global _old_fpu_mode
130
+
131
+ mode = get_fpu_mode()
132
+
133
+ if _old_fpu_mode is None:
134
+ _old_fpu_mode = mode
135
+ elif mode != _old_fpu_mode:
136
+ _collect_results[item] = (_old_fpu_mode, mode)
137
+ _old_fpu_mode = mode
138
+
139
+ # mark f2py tests as thread unsafe
140
+ if Path(item.fspath).parent == Path(__file__).parent / 'f2py' / 'tests':
141
+ item.add_marker(pytest.mark.thread_unsafe(
142
+ reason="f2py tests are thread-unsafe"))
143
+
144
+
145
+ @pytest.fixture(scope="function", autouse=True)
146
+ def check_fpu_mode(request):
147
+ """
148
+ Check FPU precision mode was not changed during the test.
149
+ """
150
+ old_mode = get_fpu_mode()
151
+ yield
152
+ new_mode = get_fpu_mode()
153
+
154
+ if old_mode != new_mode:
155
+ raise AssertionError(f"FPU precision mode changed from {old_mode:#x} to "
156
+ f"{new_mode:#x} during the test")
157
+
158
+ collect_result = _collect_results.get(request.node)
159
+ if collect_result is not None:
160
+ old_mode, new_mode = collect_result
161
+ raise AssertionError(f"FPU precision mode changed from {old_mode:#x} to "
162
+ f"{new_mode:#x} when collecting the test")
163
+
164
+
165
+ @pytest.fixture(autouse=True)
166
+ def add_np(doctest_namespace):
167
+ doctest_namespace['np'] = numpy
168
+
169
+
170
+ if HAVE_SCPDT:
171
+
172
+ @contextmanager
173
+ def warnings_errors_and_rng(test=None):
174
+ """Filter out the wall of DeprecationWarnings.
175
+ """
176
+ msgs = ["The numpy.linalg.linalg",
177
+ "The numpy.fft.helper",
178
+ "dep_util",
179
+ "pkg_resources",
180
+ "numpy.core.umath",
181
+ "msvccompiler",
182
+ "Deprecated call",
183
+ "numpy.core",
184
+ "Importing from numpy.matlib",
185
+ "This function is deprecated.", # random_integers
186
+ "Data type alias 'a'", # numpy.rec.fromfile
187
+ "Arrays of 2-dimensional vectors", # matlib.cross
188
+ "NumPy warning suppression and assertion utilities are deprecated."
189
+ ]
190
+ msg = "|".join(msgs)
191
+
192
+ msgs_r = [
193
+ "invalid value encountered",
194
+ "divide by zero encountered"
195
+ ]
196
+ msg_r = "|".join(msgs_r)
197
+
198
+ with warnings.catch_warnings():
199
+ warnings.filterwarnings(
200
+ 'ignore', category=DeprecationWarning, message=msg
201
+ )
202
+ warnings.filterwarnings(
203
+ 'ignore', category=RuntimeWarning, message=msg_r
204
+ )
205
+ yield
206
+
207
+ # find and check doctests under this context manager
208
+ dt_config.user_context_mgr = warnings_errors_and_rng
209
+
210
+ # numpy specific tweaks from refguide-check
211
+ dt_config.rndm_markers.add('#uninitialized')
212
+ dt_config.rndm_markers.add('# uninitialized')
213
+
214
+ # make the checker pick on mismatched dtypes
215
+ dt_config.strict_check = True
216
+
217
+ import doctest
218
+ dt_config.optionflags = doctest.NORMALIZE_WHITESPACE | doctest.ELLIPSIS
219
+
220
+ # recognize the StringDType repr
221
+ dt_config.check_namespace['StringDType'] = numpy.dtypes.StringDType
222
+
223
+ # temporary skips
224
+ dt_config.skiplist = {
225
+ 'numpy.savez', # unclosed file
226
+ 'numpy.matlib.savez',
227
+ 'numpy.__array_namespace_info__',
228
+ 'numpy.matlib.__array_namespace_info__',
229
+ }
230
+
231
+ # xfail problematic tutorials
232
+ dt_config.pytest_extra_xfail = {
233
+ 'how-to-verify-bug.rst': '',
234
+ 'c-info.ufunc-tutorial.rst': '',
235
+ 'basics.interoperability.rst': 'needs pandas',
236
+ 'basics.dispatch.rst': 'errors out in /testing/overrides.py',
237
+ 'basics.subclassing.rst': '.. testcode:: admonitions not understood',
238
+ 'misc.rst': 'manipulates warnings',
239
+ }
240
+
241
+ # ignores are for things fail doctest collection (optionals etc)
242
+ dt_config.pytest_extra_ignore = [
243
+ 'numpy/distutils',
244
+ 'numpy/_core/cversions.py',
245
+ 'numpy/_pyinstaller',
246
+ 'numpy/random/_examples',
247
+ 'numpy/f2py/_backends/_distutils.py',
248
+ ]
.venv_haddock/lib/python3.12/site-packages/numpy/dtypes.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This module is home to specific dtypes related functionality and their classes.
3
+ For more general information about dtypes, also see `numpy.dtype` and
4
+ :ref:`arrays.dtypes`.
5
+
6
+ Similar to the builtin ``types`` module, this submodule defines types (classes)
7
+ that are not widely used directly.
8
+
9
+ .. versionadded:: NumPy 1.25
10
+
11
+ The dtypes module is new in NumPy 1.25. Previously DType classes were
12
+ only accessible indirectly.
13
+
14
+
15
+ DType classes
16
+ -------------
17
+
18
+ The following are the classes of the corresponding NumPy dtype instances and
19
+ NumPy scalar types. The classes can be used in ``isinstance`` checks and can
20
+ also be instantiated or used directly. Direct use of these classes is not
21
+ typical, since their scalar counterparts (e.g. ``np.float64``) or strings
22
+ like ``"float64"`` can be used.
23
+ """
24
+
25
+ # See doc/source/reference/routines.dtypes.rst for module-level docs
26
+
27
+ __all__ = []
28
+
29
+
30
+ def _add_dtype_helper(DType, alias):
31
+ # Function to add DTypes a bit more conveniently without channeling them
32
+ # through `numpy._core._multiarray_umath` namespace or similar.
33
+ from numpy import dtypes
34
+
35
+ setattr(dtypes, DType.__name__, DType)
36
+ __all__.append(DType.__name__)
37
+
38
+ if alias:
39
+ alias = alias.removeprefix("numpy.dtypes.")
40
+ setattr(dtypes, alias, DType)
41
+ __all__.append(alias)
.venv_haddock/lib/python3.12/site-packages/numpy/dtypes.pyi ADDED
@@ -0,0 +1,630 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # ruff: noqa: ANN401
2
+ from typing import (
3
+ Any,
4
+ Generic,
5
+ Literal as L,
6
+ LiteralString,
7
+ Never,
8
+ NoReturn,
9
+ Self,
10
+ TypeAlias,
11
+ final,
12
+ overload,
13
+ type_check_only,
14
+ )
15
+ from typing_extensions import TypeVar
16
+
17
+ import numpy as np
18
+
19
+ __all__ = [ # noqa: RUF022
20
+ "BoolDType",
21
+ "Int8DType",
22
+ "ByteDType",
23
+ "UInt8DType",
24
+ "UByteDType",
25
+ "Int16DType",
26
+ "ShortDType",
27
+ "UInt16DType",
28
+ "UShortDType",
29
+ "Int32DType",
30
+ "IntDType",
31
+ "UInt32DType",
32
+ "UIntDType",
33
+ "Int64DType",
34
+ "LongDType",
35
+ "UInt64DType",
36
+ "ULongDType",
37
+ "LongLongDType",
38
+ "ULongLongDType",
39
+ "Float16DType",
40
+ "Float32DType",
41
+ "Float64DType",
42
+ "LongDoubleDType",
43
+ "Complex64DType",
44
+ "Complex128DType",
45
+ "CLongDoubleDType",
46
+ "ObjectDType",
47
+ "BytesDType",
48
+ "StrDType",
49
+ "VoidDType",
50
+ "DateTime64DType",
51
+ "TimeDelta64DType",
52
+ "StringDType",
53
+ ]
54
+
55
+ # Helper base classes (typing-only)
56
+
57
+ _ScalarT_co = TypeVar("_ScalarT_co", bound=np.generic, covariant=True)
58
+
59
+ @type_check_only
60
+ class _SimpleDType(np.dtype[_ScalarT_co], Generic[_ScalarT_co]): # type: ignore[misc] # pyright: ignore[reportGeneralTypeIssues]
61
+ names: None # pyright: ignore[reportIncompatibleVariableOverride]
62
+ def __new__(cls, /) -> Self: ...
63
+ def __getitem__(self, key: Any, /) -> NoReturn: ...
64
+ @property
65
+ def base(self) -> np.dtype[_ScalarT_co]: ...
66
+ @property
67
+ def fields(self) -> None: ...
68
+ @property
69
+ def isalignedstruct(self) -> L[False]: ...
70
+ @property
71
+ def isnative(self) -> L[True]: ...
72
+ @property
73
+ def ndim(self) -> L[0]: ...
74
+ @property
75
+ def shape(self) -> tuple[()]: ...
76
+ @property
77
+ def subdtype(self) -> None: ...
78
+
79
+ @type_check_only
80
+ class _LiteralDType(_SimpleDType[_ScalarT_co], Generic[_ScalarT_co]): # type: ignore[misc]
81
+ @property
82
+ def flags(self) -> L[0]: ...
83
+ @property
84
+ def hasobject(self) -> L[False]: ...
85
+
86
+ # Helper mixins (typing-only):
87
+
88
+ _KindT_co = TypeVar("_KindT_co", bound=LiteralString, covariant=True)
89
+ _CharT_co = TypeVar("_CharT_co", bound=LiteralString, covariant=True)
90
+ _NumT_co = TypeVar("_NumT_co", bound=int, covariant=True)
91
+
92
+ @type_check_only
93
+ class _TypeCodes(Generic[_KindT_co, _CharT_co, _NumT_co]):
94
+ @final
95
+ @property
96
+ def kind(self) -> _KindT_co: ...
97
+ @final
98
+ @property
99
+ def char(self) -> _CharT_co: ...
100
+ @final
101
+ @property
102
+ def num(self) -> _NumT_co: ...
103
+
104
+ @type_check_only
105
+ class _NoOrder:
106
+ @final
107
+ @property
108
+ def byteorder(self) -> L["|"]: ...
109
+
110
+ @type_check_only
111
+ class _NativeOrder:
112
+ @final
113
+ @property
114
+ def byteorder(self) -> L["="]: ...
115
+
116
+ _DataSize_co = TypeVar("_DataSize_co", bound=int, covariant=True)
117
+ _ItemSize_co = TypeVar("_ItemSize_co", bound=int, covariant=True, default=int)
118
+
119
+ @type_check_only
120
+ class _NBit(Generic[_DataSize_co, _ItemSize_co]):
121
+ @final
122
+ @property
123
+ def alignment(self) -> _DataSize_co: ...
124
+ @final
125
+ @property
126
+ def itemsize(self) -> _ItemSize_co: ...
127
+
128
+ @type_check_only
129
+ class _8Bit(_NoOrder, _NBit[L[1], L[1]]): ...
130
+
131
+ # Boolean:
132
+
133
+ @final
134
+ class BoolDType( # type: ignore[misc]
135
+ _TypeCodes[L["b"], L["?"], L[0]],
136
+ _8Bit,
137
+ _LiteralDType[np.bool],
138
+ ):
139
+ @property
140
+ def name(self) -> L["bool"]: ...
141
+ @property
142
+ def str(self) -> L["|b1"]: ...
143
+
144
+ # Sized integers:
145
+
146
+ @final
147
+ class Int8DType( # type: ignore[misc]
148
+ _TypeCodes[L["i"], L["b"], L[1]],
149
+ _8Bit,
150
+ _LiteralDType[np.int8],
151
+ ):
152
+ @property
153
+ def name(self) -> L["int8"]: ...
154
+ @property
155
+ def str(self) -> L["|i1"]: ...
156
+
157
+ @final
158
+ class UInt8DType( # type: ignore[misc]
159
+ _TypeCodes[L["u"], L["B"], L[2]],
160
+ _8Bit,
161
+ _LiteralDType[np.uint8],
162
+ ):
163
+ @property
164
+ def name(self) -> L["uint8"]: ...
165
+ @property
166
+ def str(self) -> L["|u1"]: ...
167
+
168
+ @final
169
+ class Int16DType( # type: ignore[misc]
170
+ _TypeCodes[L["i"], L["h"], L[3]],
171
+ _NativeOrder,
172
+ _NBit[L[2], L[2]],
173
+ _LiteralDType[np.int16],
174
+ ):
175
+ @property
176
+ def name(self) -> L["int16"]: ...
177
+ @property
178
+ def str(self) -> L["<i2", ">i2"]: ...
179
+
180
+ @final
181
+ class UInt16DType( # type: ignore[misc]
182
+ _TypeCodes[L["u"], L["H"], L[4]],
183
+ _NativeOrder,
184
+ _NBit[L[2], L[2]],
185
+ _LiteralDType[np.uint16],
186
+ ):
187
+ @property
188
+ def name(self) -> L["uint16"]: ...
189
+ @property
190
+ def str(self) -> L["<u2", ">u2"]: ...
191
+
192
+ @final
193
+ class Int32DType( # type: ignore[misc]
194
+ _TypeCodes[L["i"], L["i", "l"], L[5, 7]],
195
+ _NativeOrder,
196
+ _NBit[L[4], L[4]],
197
+ _LiteralDType[np.int32],
198
+ ):
199
+ @property
200
+ def name(self) -> L["int32"]: ...
201
+ @property
202
+ def str(self) -> L["<i4", ">i4"]: ...
203
+
204
+ @final
205
+ class UInt32DType( # type: ignore[misc]
206
+ _TypeCodes[L["u"], L["I", "L"], L[6, 8]],
207
+ _NativeOrder,
208
+ _NBit[L[4], L[4]],
209
+ _LiteralDType[np.uint32],
210
+ ):
211
+ @property
212
+ def name(self) -> L["uint32"]: ...
213
+ @property
214
+ def str(self) -> L["<u4", ">u4"]: ...
215
+
216
+ @final
217
+ class Int64DType( # type: ignore[misc]
218
+ _TypeCodes[L["i"], L["l", "q"], L[7, 9]],
219
+ _NativeOrder,
220
+ _NBit[L[8], L[8]],
221
+ _LiteralDType[np.int64],
222
+ ):
223
+ @property
224
+ def name(self) -> L["int64"]: ...
225
+ @property
226
+ def str(self) -> L["<i8", ">i8"]: ...
227
+
228
+ @final
229
+ class UInt64DType( # type: ignore[misc]
230
+ _TypeCodes[L["u"], L["L", "Q"], L[8, 10]],
231
+ _NativeOrder,
232
+ _NBit[L[8], L[8]],
233
+ _LiteralDType[np.uint64],
234
+ ):
235
+ @property
236
+ def name(self) -> L["uint64"]: ...
237
+ @property
238
+ def str(self) -> L["<u8", ">u8"]: ...
239
+
240
+ # Standard C-named version/alias:
241
+ # NOTE: Don't make these `Final`: it will break stubtest
242
+ ByteDType = Int8DType
243
+ UByteDType = UInt8DType
244
+ ShortDType = Int16DType
245
+ UShortDType = UInt16DType
246
+
247
+ @final
248
+ class IntDType( # type: ignore[misc]
249
+ _TypeCodes[L["i"], L["i"], L[5]],
250
+ _NativeOrder,
251
+ _NBit[L[4], L[4]],
252
+ _LiteralDType[np.intc],
253
+ ):
254
+ @property
255
+ def name(self) -> L["int32"]: ...
256
+ @property
257
+ def str(self) -> L["<i4", ">i4"]: ...
258
+
259
+ @final
260
+ class UIntDType( # type: ignore[misc]
261
+ _TypeCodes[L["u"], L["I"], L[6]],
262
+ _NativeOrder,
263
+ _NBit[L[4], L[4]],
264
+ _LiteralDType[np.uintc],
265
+ ):
266
+ @property
267
+ def name(self) -> L["uint32"]: ...
268
+ @property
269
+ def str(self) -> L["<u4", ">u4"]: ...
270
+
271
+ @final
272
+ class LongDType( # type: ignore[misc]
273
+ _TypeCodes[L["i"], L["l"], L[7]],
274
+ _NativeOrder,
275
+ _NBit[L[4, 8], L[4, 8]],
276
+ _LiteralDType[np.long],
277
+ ):
278
+ @property
279
+ def name(self) -> L["int32", "int64"]: ...
280
+ @property
281
+ def str(self) -> L["<i4", ">i4", "<i8", ">i8"]: ...
282
+
283
+ @final
284
+ class ULongDType( # type: ignore[misc]
285
+ _TypeCodes[L["u"], L["L"], L[8]],
286
+ _NativeOrder,
287
+ _NBit[L[4, 8], L[4, 8]],
288
+ _LiteralDType[np.ulong],
289
+ ):
290
+ @property
291
+ def name(self) -> L["uint32", "uint64"]: ...
292
+ @property
293
+ def str(self) -> L["<u4", ">u4", "<u8", ">u8"]: ...
294
+
295
+ @final
296
+ class LongLongDType( # type: ignore[misc]
297
+ _TypeCodes[L["i"], L["q"], L[9]],
298
+ _NativeOrder,
299
+ _NBit[L[8], L[8]],
300
+ _LiteralDType[np.longlong],
301
+ ):
302
+ @property
303
+ def name(self) -> L["int64"]: ...
304
+ @property
305
+ def str(self) -> L["<i8", ">i8"]: ...
306
+
307
+ @final
308
+ class ULongLongDType( # type: ignore[misc]
309
+ _TypeCodes[L["u"], L["Q"], L[10]],
310
+ _NativeOrder,
311
+ _NBit[L[8], L[8]],
312
+ _LiteralDType[np.ulonglong],
313
+ ):
314
+ @property
315
+ def name(self) -> L["uint64"]: ...
316
+ @property
317
+ def str(self) -> L["<u8", ">u8"]: ...
318
+
319
+ # Floats:
320
+
321
+ @final
322
+ class Float16DType( # type: ignore[misc]
323
+ _TypeCodes[L["f"], L["e"], L[23]],
324
+ _NativeOrder,
325
+ _NBit[L[2], L[2]],
326
+ _LiteralDType[np.float16],
327
+ ):
328
+ @property
329
+ def name(self) -> L["float16"]: ...
330
+ @property
331
+ def str(self) -> L["<f2", ">f2"]: ...
332
+
333
+ @final
334
+ class Float32DType( # type: ignore[misc]
335
+ _TypeCodes[L["f"], L["f"], L[11]],
336
+ _NativeOrder,
337
+ _NBit[L[4], L[4]],
338
+ _LiteralDType[np.float32],
339
+ ):
340
+ @property
341
+ def name(self) -> L["float32"]: ...
342
+ @property
343
+ def str(self) -> L["<f4", ">f4"]: ...
344
+
345
+ @final
346
+ class Float64DType( # type: ignore[misc]
347
+ _TypeCodes[L["f"], L["d"], L[12]],
348
+ _NativeOrder,
349
+ _NBit[L[8], L[8]],
350
+ _LiteralDType[np.float64],
351
+ ):
352
+ @property
353
+ def name(self) -> L["float64"]: ...
354
+ @property
355
+ def str(self) -> L["<f8", ">f8"]: ...
356
+
357
+ @final
358
+ class LongDoubleDType( # type: ignore[misc]
359
+ _TypeCodes[L["f"], L["g"], L[13]],
360
+ _NativeOrder,
361
+ _NBit[L[8, 12, 16], L[8, 12, 16]],
362
+ _LiteralDType[np.longdouble],
363
+ ):
364
+ @property
365
+ def name(self) -> L["float64", "float96", "float128"]: ...
366
+ @property
367
+ def str(self) -> L["<f8", ">f8", "<f12", ">f12", "<f16", ">f16"]: ...
368
+
369
+ # Complex:
370
+
371
+ @final
372
+ class Complex64DType( # type: ignore[misc]
373
+ _TypeCodes[L["c"], L["F"], L[14]],
374
+ _NativeOrder,
375
+ _NBit[L[4], L[8]],
376
+ _LiteralDType[np.complex64],
377
+ ):
378
+ @property
379
+ def name(self) -> L["complex64"]: ...
380
+ @property
381
+ def str(self) -> L["<c8", ">c8"]: ...
382
+
383
+ @final
384
+ class Complex128DType( # type: ignore[misc]
385
+ _TypeCodes[L["c"], L["D"], L[15]],
386
+ _NativeOrder,
387
+ _NBit[L[8], L[16]],
388
+ _LiteralDType[np.complex128],
389
+ ):
390
+ @property
391
+ def name(self) -> L["complex128"]: ...
392
+ @property
393
+ def str(self) -> L["<c16", ">c16"]: ...
394
+
395
+ @final
396
+ class CLongDoubleDType( # type: ignore[misc]
397
+ _TypeCodes[L["c"], L["G"], L[16]],
398
+ _NativeOrder,
399
+ _NBit[L[8, 12, 16], L[16, 24, 32]],
400
+ _LiteralDType[np.clongdouble],
401
+ ):
402
+ @property
403
+ def name(self) -> L["complex128", "complex192", "complex256"]: ...
404
+ @property
405
+ def str(self) -> L["<c16", ">c16", "<c24", ">c24", "<c32", ">c32"]: ...
406
+
407
+ # Python objects:
408
+
409
+ @final
410
+ class ObjectDType( # type: ignore[misc]
411
+ _TypeCodes[L["O"], L["O"], L[17]],
412
+ _NoOrder,
413
+ _NBit[L[8], L[8]],
414
+ _SimpleDType[np.object_],
415
+ ):
416
+ @property
417
+ def hasobject(self) -> L[True]: ...
418
+ @property
419
+ def name(self) -> L["object"]: ...
420
+ @property
421
+ def str(self) -> L["|O"]: ...
422
+
423
+ # Flexible:
424
+
425
+ @final
426
+ class BytesDType( # type: ignore[misc]
427
+ _TypeCodes[L["S"], L["S"], L[18]],
428
+ _NoOrder,
429
+ _NBit[L[1], _ItemSize_co],
430
+ _SimpleDType[np.bytes_],
431
+ Generic[_ItemSize_co],
432
+ ):
433
+ def __new__(cls, size: _ItemSize_co, /) -> BytesDType[_ItemSize_co]: ...
434
+ @property
435
+ def hasobject(self) -> L[False]: ...
436
+ @property
437
+ def name(self) -> LiteralString: ...
438
+ @property
439
+ def str(self) -> LiteralString: ...
440
+
441
+ @final
442
+ class StrDType( # type: ignore[misc]
443
+ _TypeCodes[L["U"], L["U"], L[19]],
444
+ _NativeOrder,
445
+ _NBit[L[4], _ItemSize_co],
446
+ _SimpleDType[np.str_],
447
+ Generic[_ItemSize_co],
448
+ ):
449
+ def __new__(cls, size: _ItemSize_co, /) -> StrDType[_ItemSize_co]: ...
450
+ @property
451
+ def hasobject(self) -> L[False]: ...
452
+ @property
453
+ def name(self) -> LiteralString: ...
454
+ @property
455
+ def str(self) -> LiteralString: ...
456
+
457
+ @final
458
+ class VoidDType( # type: ignore[misc]
459
+ _TypeCodes[L["V"], L["V"], L[20]],
460
+ _NoOrder,
461
+ _NBit[L[1], _ItemSize_co],
462
+ np.dtype[np.void], # pyright: ignore[reportGeneralTypeIssues]
463
+ Generic[_ItemSize_co],
464
+ ):
465
+ # NOTE: `VoidDType(...)` raises a `TypeError` at the moment
466
+ def __new__(cls, length: _ItemSize_co, /) -> NoReturn: ...
467
+ @property
468
+ def base(self) -> Self: ...
469
+ @property
470
+ def isalignedstruct(self) -> L[False]: ...
471
+ @property
472
+ def isnative(self) -> L[True]: ...
473
+ @property
474
+ def ndim(self) -> L[0]: ...
475
+ @property
476
+ def shape(self) -> tuple[()]: ...
477
+ @property
478
+ def subdtype(self) -> None: ...
479
+ @property
480
+ def name(self) -> LiteralString: ...
481
+ @property
482
+ def str(self) -> LiteralString: ...
483
+
484
+ # Other:
485
+
486
+ _DateUnit: TypeAlias = L["Y", "M", "W", "D"]
487
+ _TimeUnit: TypeAlias = L["h", "m", "s", "ms", "us", "ns", "ps", "fs", "as"]
488
+ _DateTimeUnit: TypeAlias = _DateUnit | _TimeUnit
489
+
490
+ @final
491
+ class DateTime64DType( # type: ignore[misc]
492
+ _TypeCodes[L["M"], L["M"], L[21]],
493
+ _NativeOrder,
494
+ _NBit[L[8], L[8]],
495
+ _LiteralDType[np.datetime64],
496
+ ):
497
+ # NOTE: `DateTime64DType(...)` raises a `TypeError` at the moment
498
+ # TODO: Once implemented, don't forget the`unit: L["μs"]` overload.
499
+ def __new__(cls, unit: _DateTimeUnit, /) -> NoReturn: ...
500
+ @property
501
+ def name(self) -> L[
502
+ "datetime64",
503
+ "datetime64[Y]",
504
+ "datetime64[M]",
505
+ "datetime64[W]",
506
+ "datetime64[D]",
507
+ "datetime64[h]",
508
+ "datetime64[m]",
509
+ "datetime64[s]",
510
+ "datetime64[ms]",
511
+ "datetime64[us]",
512
+ "datetime64[ns]",
513
+ "datetime64[ps]",
514
+ "datetime64[fs]",
515
+ "datetime64[as]",
516
+ ]: ...
517
+ @property
518
+ def str(self) -> L[
519
+ "<M8", ">M8",
520
+ "<M8[Y]", ">M8[Y]",
521
+ "<M8[M]", ">M8[M]",
522
+ "<M8[W]", ">M8[W]",
523
+ "<M8[D]", ">M8[D]",
524
+ "<M8[h]", ">M8[h]",
525
+ "<M8[m]", ">M8[m]",
526
+ "<M8[s]", ">M8[s]",
527
+ "<M8[ms]", ">M8[ms]",
528
+ "<M8[us]", ">M8[us]",
529
+ "<M8[ns]", ">M8[ns]",
530
+ "<M8[ps]", ">M8[ps]",
531
+ "<M8[fs]", ">M8[fs]",
532
+ "<M8[as]", ">M8[as]",
533
+ ]: ...
534
+
535
+ @final
536
+ class TimeDelta64DType( # type: ignore[misc]
537
+ _TypeCodes[L["m"], L["m"], L[22]],
538
+ _NativeOrder,
539
+ _NBit[L[8], L[8]],
540
+ _LiteralDType[np.timedelta64],
541
+ ):
542
+ # NOTE: `TimeDelta64DType(...)` raises a `TypeError` at the moment
543
+ # TODO: Once implemented, don't forget to overload on `unit: L["μs"]`.
544
+ def __new__(cls, unit: _DateTimeUnit, /) -> NoReturn: ...
545
+ @property
546
+ def name(self) -> L[
547
+ "timedelta64",
548
+ "timedelta64[Y]",
549
+ "timedelta64[M]",
550
+ "timedelta64[W]",
551
+ "timedelta64[D]",
552
+ "timedelta64[h]",
553
+ "timedelta64[m]",
554
+ "timedelta64[s]",
555
+ "timedelta64[ms]",
556
+ "timedelta64[us]",
557
+ "timedelta64[ns]",
558
+ "timedelta64[ps]",
559
+ "timedelta64[fs]",
560
+ "timedelta64[as]",
561
+ ]: ...
562
+ @property
563
+ def str(self) -> L[
564
+ "<m8", ">m8",
565
+ "<m8[Y]", ">m8[Y]",
566
+ "<m8[M]", ">m8[M]",
567
+ "<m8[W]", ">m8[W]",
568
+ "<m8[D]", ">m8[D]",
569
+ "<m8[h]", ">m8[h]",
570
+ "<m8[m]", ">m8[m]",
571
+ "<m8[s]", ">m8[s]",
572
+ "<m8[ms]", ">m8[ms]",
573
+ "<m8[us]", ">m8[us]",
574
+ "<m8[ns]", ">m8[ns]",
575
+ "<m8[ps]", ">m8[ps]",
576
+ "<m8[fs]", ">m8[fs]",
577
+ "<m8[as]", ">m8[as]",
578
+ ]: ...
579
+
580
+ _NaObjectT_co = TypeVar("_NaObjectT_co", default=Never, covariant=True)
581
+
582
+ @final
583
+ class StringDType( # type: ignore[misc]
584
+ _TypeCodes[L["T"], L["T"], L[2056]],
585
+ _NativeOrder,
586
+ _NBit[L[8], L[16]],
587
+ # TODO(jorenham): change once we have a string scalar type:
588
+ # https://github.com/numpy/numpy/issues/28165
589
+ np.dtype[str], # type: ignore[type-var] # pyright: ignore[reportGeneralTypeIssues, reportInvalidTypeArguments]
590
+ Generic[_NaObjectT_co],
591
+ ):
592
+ @property
593
+ def na_object(self) -> _NaObjectT_co: ...
594
+ @property
595
+ def coerce(self) -> L[True]: ...
596
+
597
+ #
598
+ @overload
599
+ def __new__(cls, /, *, coerce: bool = True) -> Self: ...
600
+ @overload
601
+ def __new__(cls, /, *, na_object: _NaObjectT_co, coerce: bool = True) -> Self: ...
602
+
603
+ #
604
+ def __getitem__(self, key: Never, /) -> NoReturn: ... # type: ignore[override] # pyright: ignore[reportIncompatibleMethodOverride]
605
+ @property
606
+ def fields(self) -> None: ...
607
+ @property
608
+ def base(self) -> Self: ...
609
+ @property
610
+ def ndim(self) -> L[0]: ...
611
+ @property
612
+ def shape(self) -> tuple[()]: ...
613
+
614
+ #
615
+ @property
616
+ def name(self) -> L["StringDType64", "StringDType128"]: ...
617
+ @property
618
+ def subdtype(self) -> None: ...
619
+ @property
620
+ def type(self) -> type[str]: ...
621
+ @property
622
+ def str(self) -> L["|T8", "|T16"]: ...
623
+
624
+ #
625
+ @property
626
+ def hasobject(self) -> L[True]: ...
627
+ @property
628
+ def isalignedstruct(self) -> L[False]: ...
629
+ @property
630
+ def isnative(self) -> L[True]: ...
.venv_haddock/lib/python3.12/site-packages/numpy/exceptions.pyi ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import overload
2
+
3
+ __all__ = [
4
+ "ComplexWarning",
5
+ "VisibleDeprecationWarning",
6
+ "ModuleDeprecationWarning",
7
+ "TooHardError",
8
+ "AxisError",
9
+ "DTypePromotionError",
10
+ ]
11
+
12
+ class ComplexWarning(RuntimeWarning): ...
13
+ class ModuleDeprecationWarning(DeprecationWarning): ...
14
+ class VisibleDeprecationWarning(UserWarning): ...
15
+ class RankWarning(RuntimeWarning): ...
16
+ class TooHardError(RuntimeError): ...
17
+ class DTypePromotionError(TypeError): ...
18
+
19
+ class AxisError(ValueError, IndexError):
20
+ __slots__ = "_msg", "axis", "ndim"
21
+
22
+ axis: int | None
23
+ ndim: int | None
24
+ @overload
25
+ def __init__(self, axis: str, ndim: None = None, msg_prefix: None = None) -> None: ...
26
+ @overload
27
+ def __init__(self, axis: int, ndim: int, msg_prefix: str | None = None) -> None: ...
.venv_haddock/lib/python3.12/site-packages/numpy/matlib.pyi ADDED
@@ -0,0 +1,582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Literal, TypeAlias, TypeVar, overload
2
+
3
+ import numpy as np
4
+ import numpy.typing as npt
5
+ from numpy import ( # noqa: F401
6
+ False_,
7
+ ScalarType,
8
+ True_,
9
+ __array_namespace_info__,
10
+ __version__,
11
+ abs,
12
+ absolute,
13
+ acos,
14
+ acosh,
15
+ add,
16
+ all,
17
+ allclose,
18
+ amax,
19
+ amin,
20
+ angle,
21
+ any,
22
+ append,
23
+ apply_along_axis,
24
+ apply_over_axes,
25
+ arange,
26
+ arccos,
27
+ arccosh,
28
+ arcsin,
29
+ arcsinh,
30
+ arctan,
31
+ arctan2,
32
+ arctanh,
33
+ argmax,
34
+ argmin,
35
+ argpartition,
36
+ argsort,
37
+ argwhere,
38
+ around,
39
+ array,
40
+ array2string,
41
+ array_equal,
42
+ array_equiv,
43
+ array_repr,
44
+ array_split,
45
+ array_str,
46
+ asanyarray,
47
+ asarray,
48
+ asarray_chkfinite,
49
+ ascontiguousarray,
50
+ asfortranarray,
51
+ asin,
52
+ asinh,
53
+ asmatrix,
54
+ astype,
55
+ atan,
56
+ atan2,
57
+ atanh,
58
+ atleast_1d,
59
+ atleast_2d,
60
+ atleast_3d,
61
+ average,
62
+ bartlett,
63
+ base_repr,
64
+ binary_repr,
65
+ bincount,
66
+ bitwise_and,
67
+ bitwise_count,
68
+ bitwise_invert,
69
+ bitwise_left_shift,
70
+ bitwise_not,
71
+ bitwise_or,
72
+ bitwise_right_shift,
73
+ bitwise_xor,
74
+ blackman,
75
+ block,
76
+ bmat,
77
+ bool,
78
+ bool_,
79
+ broadcast,
80
+ broadcast_arrays,
81
+ broadcast_shapes,
82
+ broadcast_to,
83
+ busday_count,
84
+ busday_offset,
85
+ busdaycalendar,
86
+ byte,
87
+ bytes_,
88
+ c_,
89
+ can_cast,
90
+ cbrt,
91
+ cdouble,
92
+ ceil,
93
+ char,
94
+ character,
95
+ choose,
96
+ clip,
97
+ clongdouble,
98
+ column_stack,
99
+ common_type,
100
+ complex64,
101
+ complex128,
102
+ complex192,
103
+ complex256,
104
+ complexfloating,
105
+ compress,
106
+ concat,
107
+ concatenate,
108
+ conj,
109
+ conjugate,
110
+ convolve,
111
+ copy,
112
+ copysign,
113
+ copyto,
114
+ core,
115
+ corrcoef,
116
+ correlate,
117
+ cos,
118
+ cosh,
119
+ count_nonzero,
120
+ cov,
121
+ cross,
122
+ csingle,
123
+ ctypeslib,
124
+ cumprod,
125
+ cumsum,
126
+ cumulative_prod,
127
+ cumulative_sum,
128
+ datetime64,
129
+ datetime_as_string,
130
+ datetime_data,
131
+ deg2rad,
132
+ degrees,
133
+ delete,
134
+ diag,
135
+ diag_indices,
136
+ diag_indices_from,
137
+ diagflat,
138
+ diagonal,
139
+ diff,
140
+ digitize,
141
+ divide,
142
+ divmod,
143
+ dot,
144
+ double,
145
+ dsplit,
146
+ dstack,
147
+ dtype,
148
+ dtypes,
149
+ e,
150
+ ediff1d,
151
+ einsum,
152
+ einsum_path,
153
+ emath,
154
+ empty_like,
155
+ equal,
156
+ errstate,
157
+ euler_gamma,
158
+ exceptions,
159
+ exp,
160
+ exp2,
161
+ expand_dims,
162
+ expm1,
163
+ extract,
164
+ f2py,
165
+ fabs,
166
+ fft,
167
+ fill_diagonal,
168
+ finfo,
169
+ fix,
170
+ flatiter,
171
+ flatnonzero,
172
+ flexible,
173
+ flip,
174
+ fliplr,
175
+ flipud,
176
+ float16,
177
+ float32,
178
+ float64,
179
+ float96,
180
+ float128,
181
+ float_power,
182
+ floating,
183
+ floor,
184
+ floor_divide,
185
+ fmax,
186
+ fmin,
187
+ fmod,
188
+ format_float_positional,
189
+ format_float_scientific,
190
+ frexp,
191
+ from_dlpack,
192
+ frombuffer,
193
+ fromfile,
194
+ fromfunction,
195
+ fromiter,
196
+ frompyfunc,
197
+ fromregex,
198
+ fromstring,
199
+ full,
200
+ full_like,
201
+ gcd,
202
+ generic,
203
+ genfromtxt,
204
+ geomspace,
205
+ get_include,
206
+ get_printoptions,
207
+ getbufsize,
208
+ geterr,
209
+ geterrcall,
210
+ gradient,
211
+ greater,
212
+ greater_equal,
213
+ half,
214
+ hamming,
215
+ hanning,
216
+ heaviside,
217
+ histogram,
218
+ histogram2d,
219
+ histogram_bin_edges,
220
+ histogramdd,
221
+ hsplit,
222
+ hstack,
223
+ hypot,
224
+ i0,
225
+ iinfo,
226
+ imag,
227
+ index_exp,
228
+ indices,
229
+ inexact,
230
+ inf,
231
+ info,
232
+ inner,
233
+ insert,
234
+ int8,
235
+ int16,
236
+ int32,
237
+ int64,
238
+ int_,
239
+ intc,
240
+ integer,
241
+ interp,
242
+ intersect1d,
243
+ intp,
244
+ invert,
245
+ is_busday,
246
+ isclose,
247
+ iscomplex,
248
+ iscomplexobj,
249
+ isdtype,
250
+ isfinite,
251
+ isfortran,
252
+ isin,
253
+ isinf,
254
+ isnan,
255
+ isnat,
256
+ isneginf,
257
+ isposinf,
258
+ isreal,
259
+ isrealobj,
260
+ isscalar,
261
+ issubdtype,
262
+ iterable,
263
+ ix_,
264
+ kaiser,
265
+ kron,
266
+ lcm,
267
+ ldexp,
268
+ left_shift,
269
+ less,
270
+ less_equal,
271
+ lexsort,
272
+ lib,
273
+ linalg,
274
+ linspace,
275
+ little_endian,
276
+ load,
277
+ loadtxt,
278
+ log,
279
+ log1p,
280
+ log2,
281
+ log10,
282
+ logaddexp,
283
+ logaddexp2,
284
+ logical_and,
285
+ logical_not,
286
+ logical_or,
287
+ logical_xor,
288
+ logspace,
289
+ long,
290
+ longdouble,
291
+ longlong,
292
+ ma,
293
+ mask_indices,
294
+ matmul,
295
+ matrix,
296
+ matrix_transpose,
297
+ matvec,
298
+ max,
299
+ maximum,
300
+ may_share_memory,
301
+ mean,
302
+ median,
303
+ memmap,
304
+ meshgrid,
305
+ mgrid,
306
+ min,
307
+ min_scalar_type,
308
+ minimum,
309
+ mintypecode,
310
+ mod,
311
+ modf,
312
+ moveaxis,
313
+ multiply,
314
+ nan,
315
+ nan_to_num,
316
+ nanargmax,
317
+ nanargmin,
318
+ nancumprod,
319
+ nancumsum,
320
+ nanmax,
321
+ nanmean,
322
+ nanmedian,
323
+ nanmin,
324
+ nanpercentile,
325
+ nanprod,
326
+ nanquantile,
327
+ nanstd,
328
+ nansum,
329
+ nanvar,
330
+ ndarray,
331
+ ndenumerate,
332
+ ndim,
333
+ ndindex,
334
+ nditer,
335
+ negative,
336
+ nested_iters,
337
+ newaxis,
338
+ nextafter,
339
+ nonzero,
340
+ not_equal,
341
+ number,
342
+ object_,
343
+ ogrid,
344
+ ones_like,
345
+ outer,
346
+ packbits,
347
+ pad,
348
+ partition,
349
+ percentile,
350
+ permute_dims,
351
+ pi,
352
+ piecewise,
353
+ place,
354
+ poly,
355
+ poly1d,
356
+ polyadd,
357
+ polyder,
358
+ polydiv,
359
+ polyfit,
360
+ polyint,
361
+ polymul,
362
+ polynomial,
363
+ polysub,
364
+ polyval,
365
+ positive,
366
+ pow,
367
+ power,
368
+ printoptions,
369
+ prod,
370
+ promote_types,
371
+ ptp,
372
+ put,
373
+ put_along_axis,
374
+ putmask,
375
+ quantile,
376
+ r_,
377
+ rad2deg,
378
+ radians,
379
+ random,
380
+ ravel,
381
+ ravel_multi_index,
382
+ real,
383
+ real_if_close,
384
+ rec,
385
+ recarray,
386
+ reciprocal,
387
+ record,
388
+ remainder,
389
+ repeat,
390
+ require,
391
+ reshape,
392
+ resize,
393
+ result_type,
394
+ right_shift,
395
+ rint,
396
+ roll,
397
+ rollaxis,
398
+ roots,
399
+ rot90,
400
+ round,
401
+ row_stack,
402
+ s_,
403
+ save,
404
+ savetxt,
405
+ savez,
406
+ savez_compressed,
407
+ sctypeDict,
408
+ searchsorted,
409
+ select,
410
+ set_printoptions,
411
+ setbufsize,
412
+ setdiff1d,
413
+ seterr,
414
+ seterrcall,
415
+ setxor1d,
416
+ shape,
417
+ shares_memory,
418
+ short,
419
+ show_config,
420
+ show_runtime,
421
+ sign,
422
+ signbit,
423
+ signedinteger,
424
+ sin,
425
+ sinc,
426
+ single,
427
+ sinh,
428
+ size,
429
+ sort,
430
+ sort_complex,
431
+ spacing,
432
+ split,
433
+ sqrt,
434
+ square,
435
+ squeeze,
436
+ stack,
437
+ std,
438
+ str_,
439
+ strings,
440
+ subtract,
441
+ sum,
442
+ swapaxes,
443
+ take,
444
+ take_along_axis,
445
+ tan,
446
+ tanh,
447
+ tensordot,
448
+ test,
449
+ testing,
450
+ tile,
451
+ timedelta64,
452
+ trace,
453
+ transpose,
454
+ trapezoid,
455
+ tri,
456
+ tril,
457
+ tril_indices,
458
+ tril_indices_from,
459
+ trim_zeros,
460
+ triu,
461
+ triu_indices,
462
+ triu_indices_from,
463
+ true_divide,
464
+ trunc,
465
+ typecodes,
466
+ typename,
467
+ typing,
468
+ ubyte,
469
+ ufunc,
470
+ uint,
471
+ uint8,
472
+ uint16,
473
+ uint32,
474
+ uint64,
475
+ uintc,
476
+ uintp,
477
+ ulong,
478
+ ulonglong,
479
+ union1d,
480
+ unique,
481
+ unique_all,
482
+ unique_counts,
483
+ unique_inverse,
484
+ unique_values,
485
+ unpackbits,
486
+ unravel_index,
487
+ unsignedinteger,
488
+ unstack,
489
+ unwrap,
490
+ ushort,
491
+ vander,
492
+ var,
493
+ vdot,
494
+ vecdot,
495
+ vecmat,
496
+ vectorize,
497
+ void,
498
+ vsplit,
499
+ vstack,
500
+ where,
501
+ zeros_like,
502
+ )
503
+ from numpy._typing import _ArrayLike, _DTypeLike
504
+
505
+ __all__ = ["rand", "randn", "repmat"]
506
+ __all__ += np.__all__
507
+
508
+ ###
509
+
510
+ _ScalarT = TypeVar("_ScalarT", bound=np.generic)
511
+ _Matrix: TypeAlias = np.matrix[tuple[int, int], np.dtype[_ScalarT]]
512
+ _Order: TypeAlias = Literal["C", "F"]
513
+
514
+ ###
515
+
516
+ #
517
+ @overload
518
+ def empty(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ...
519
+ @overload
520
+ def empty(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ...
521
+ @overload
522
+ def empty(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ...
523
+
524
+ #
525
+ @overload
526
+ def ones(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ...
527
+ @overload
528
+ def ones(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ...
529
+ @overload
530
+ def ones(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ...
531
+
532
+ #
533
+ @overload
534
+ def zeros(shape: int | tuple[int, int], dtype: None = None, order: _Order = "C") -> _Matrix[np.float64]: ...
535
+ @overload
536
+ def zeros(shape: int | tuple[int, int], dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ...
537
+ @overload
538
+ def zeros(shape: int | tuple[int, int], dtype: npt.DTypeLike, order: _Order = "C") -> _Matrix[Any]: ...
539
+
540
+ #
541
+ @overload
542
+ def identity(n: int, dtype: None = None) -> _Matrix[np.float64]: ...
543
+ @overload
544
+ def identity(n: int, dtype: _DTypeLike[_ScalarT]) -> _Matrix[_ScalarT]: ...
545
+ @overload
546
+ def identity(n: int, dtype: npt.DTypeLike | None = None) -> _Matrix[Any]: ...
547
+
548
+ #
549
+ @overload
550
+ def eye(
551
+ n: int,
552
+ M: int | None = None,
553
+ k: int = 0,
554
+ dtype: type[np.float64] | None = ...,
555
+ order: _Order = "C",
556
+ ) -> _Matrix[np.float64]: ...
557
+ @overload
558
+ def eye(n: int, M: int | None, k: int, dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ...
559
+ @overload
560
+ def eye(n: int, M: int | None = None, k: int = 0, *, dtype: _DTypeLike[_ScalarT], order: _Order = "C") -> _Matrix[_ScalarT]: ...
561
+ @overload
562
+ def eye(n: int, M: int | None = None, k: int = 0, dtype: npt.DTypeLike | None = ..., order: _Order = "C") -> _Matrix[Any]: ...
563
+
564
+ #
565
+ @overload
566
+ def rand(arg: int | tuple[()] | tuple[int] | tuple[int, int], /) -> _Matrix[np.float64]: ...
567
+ @overload
568
+ def rand(arg: int, /, *args: int) -> _Matrix[np.float64]: ...
569
+
570
+ #
571
+ @overload
572
+ def randn(arg: int | tuple[()] | tuple[int] | tuple[int, int], /) -> _Matrix[np.float64]: ...
573
+ @overload
574
+ def randn(arg: int, /, *args: int) -> _Matrix[np.float64]: ...
575
+
576
+ #
577
+ @overload
578
+ def repmat(a: _Matrix[_ScalarT], m: int, n: int) -> _Matrix[_ScalarT]: ...
579
+ @overload
580
+ def repmat(a: _ArrayLike[_ScalarT], m: int, n: int) -> npt.NDArray[_ScalarT]: ...
581
+ @overload
582
+ def repmat(a: npt.ArrayLike, m: int, n: int) -> npt.NDArray[Any]: ...
.venv_haddock/lib/python3.12/site-packages/numpy/version.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ """
3
+ Module to expose more detailed version info for the installed `numpy`
4
+ """
5
+ version = "2.4.4"
6
+ __version__ = version
7
+ full_version = version
8
+
9
+ git_revision = "be93fe2960dbf49b4647f5783c66d967fb2c65b5"
10
+ release = 'dev' not in version and '+' not in version
11
+ short_version = version.split("+")[0]
.venv_haddock/lib/python3.12/site-packages/numpy/version.pyi ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Final, LiteralString
2
+
3
+ version: Final[LiteralString] = ...
4
+ __version__: Final[LiteralString] = ...
5
+ full_version: Final[LiteralString] = ...
6
+
7
+ git_revision: Final[LiteralString] = ...
8
+ release: Final[bool] = ...
9
+ short_version: Final[LiteralString] = ...
.venv_haddock/lib/python3.12/site-packages/packaging/__init__.py ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This file is dual licensed under the terms of the Apache License, Version
2
+ # 2.0, and the BSD License. See the LICENSE file in the root of this repository
3
+ # for complete details.
4
+
5
+ __title__ = "packaging"
6
+ __summary__ = "Core utilities for Python packages"
7
+ __uri__ = "https://github.com/pypa/packaging"
8
+
9
+ __version__ = "26.1"
10
+
11
+ __author__ = "Donald Stufft and individual contributors"
12
+ __email__ = "donald@stufft.io"
13
+
14
+ __license__ = "BSD-2-Clause or Apache-2.0"
15
+ __copyright__ = f"2014 {__author__}"
.venv_haddock/lib/python3.12/site-packages/packaging/_elffile.py ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ ELF file parser.
3
+
4
+ This provides a class ``ELFFile`` that parses an ELF executable in a similar
5
+ interface to ``ZipFile``. Only the read interface is implemented.
6
+
7
+ ELF header: https://refspecs.linuxfoundation.org/elf/gabi4+/ch4.eheader.html
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import enum
13
+ import os
14
+ import struct
15
+ from typing import IO
16
+
17
+
18
+ class ELFInvalid(ValueError):
19
+ pass
20
+
21
+
22
+ class EIClass(enum.IntEnum):
23
+ C32 = 1
24
+ C64 = 2
25
+
26
+
27
+ class EIData(enum.IntEnum):
28
+ Lsb = 1
29
+ Msb = 2
30
+
31
+
32
+ class EMachine(enum.IntEnum):
33
+ I386 = 3
34
+ S390 = 22
35
+ Arm = 40
36
+ X8664 = 62
37
+ AArc64 = 183
38
+
39
+
40
+ class ELFFile:
41
+ """
42
+ Representation of an ELF executable.
43
+ """
44
+
45
+ def __init__(self, f: IO[bytes]) -> None:
46
+ self._f = f
47
+
48
+ try:
49
+ ident = self._read("16B")
50
+ except struct.error as e:
51
+ raise ELFInvalid("unable to parse identification") from e
52
+ magic = bytes(ident[:4])
53
+ if magic != b"\x7fELF":
54
+ raise ELFInvalid(f"invalid magic: {magic!r}")
55
+
56
+ self.capacity = ident[4] # Format for program header (bitness).
57
+ self.encoding = ident[5] # Data structure encoding (endianness).
58
+
59
+ try:
60
+ # e_fmt: Format for program header.
61
+ # p_fmt: Format for section header.
62
+ # p_idx: Indexes to find p_type, p_offset, and p_filesz.
63
+ e_fmt, self._p_fmt, self._p_idx = {
64
+ (1, 1): ("<HHIIIIIHHH", "<IIIIIIII", (0, 1, 4)), # 32-bit LSB.
65
+ (1, 2): (">HHIIIIIHHH", ">IIIIIIII", (0, 1, 4)), # 32-bit MSB.
66
+ (2, 1): ("<HHIQQQIHHH", "<IIQQQQQQ", (0, 2, 5)), # 64-bit LSB.
67
+ (2, 2): (">HHIQQQIHHH", ">IIQQQQQQ", (0, 2, 5)), # 64-bit MSB.
68
+ }[(self.capacity, self.encoding)]
69
+ except KeyError as e:
70
+ raise ELFInvalid(
71
+ f"unrecognized capacity ({self.capacity}) or encoding ({self.encoding})"
72
+ ) from e
73
+
74
+ try:
75
+ (
76
+ _,
77
+ self.machine, # Architecture type.
78
+ _,
79
+ _,
80
+ self._e_phoff, # Offset of program header.
81
+ _,
82
+ self.flags, # Processor-specific flags.
83
+ _,
84
+ self._e_phentsize, # Size of section.
85
+ self._e_phnum, # Number of sections.
86
+ ) = self._read(e_fmt)
87
+ except struct.error as e:
88
+ raise ELFInvalid("unable to parse machine and section information") from e
89
+
90
+ def _read(self, fmt: str) -> tuple[int, ...]:
91
+ return struct.unpack(fmt, self._f.read(struct.calcsize(fmt)))
92
+
93
+ @property
94
+ def interpreter(self) -> str | None:
95
+ """
96
+ The path recorded in the ``PT_INTERP`` section header.
97
+ """
98
+ for index in range(self._e_phnum):
99
+ self._f.seek(self._e_phoff + self._e_phentsize * index)
100
+ try:
101
+ data = self._read(self._p_fmt)
102
+ except struct.error:
103
+ continue
104
+ if data[self._p_idx[0]] != 3: # Not PT_INTERP.
105
+ continue
106
+ self._f.seek(data[self._p_idx[1]])
107
+ return os.fsdecode(self._f.read(data[self._p_idx[2]])).strip("\0")
108
+ return None
.venv_haddock/lib/python3.12/site-packages/packaging/_manylinux.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import collections
4
+ import contextlib
5
+ import functools
6
+ import os
7
+ import re
8
+ import sys
9
+ import warnings
10
+ from typing import Generator, Iterator, NamedTuple, Sequence
11
+
12
+ from ._elffile import EIClass, EIData, ELFFile, EMachine
13
+
14
+ EF_ARM_ABIMASK = 0xFF000000
15
+ EF_ARM_ABI_VER5 = 0x05000000
16
+ EF_ARM_ABI_FLOAT_HARD = 0x00000400
17
+
18
+ _ALLOWED_ARCHS = {
19
+ "x86_64",
20
+ "aarch64",
21
+ "ppc64",
22
+ "ppc64le",
23
+ "s390x",
24
+ "loongarch64",
25
+ "riscv64",
26
+ }
27
+
28
+
29
+ # `os.PathLike` not a generic type until Python 3.9, so sticking with `str`
30
+ # as the type for `path` until then.
31
+ @contextlib.contextmanager
32
+ def _parse_elf(path: str) -> Generator[ELFFile | None, None, None]:
33
+ try:
34
+ with open(path, "rb") as f:
35
+ yield ELFFile(f)
36
+ except (OSError, TypeError, ValueError):
37
+ yield None
38
+
39
+
40
+ def _is_linux_armhf(executable: str) -> bool:
41
+ # hard-float ABI can be detected from the ELF header of the running
42
+ # process
43
+ # https://static.docs.arm.com/ihi0044/g/aaelf32.pdf
44
+ with _parse_elf(executable) as f:
45
+ return (
46
+ f is not None
47
+ and f.capacity == EIClass.C32
48
+ and f.encoding == EIData.Lsb
49
+ and f.machine == EMachine.Arm
50
+ and f.flags & EF_ARM_ABIMASK == EF_ARM_ABI_VER5
51
+ and f.flags & EF_ARM_ABI_FLOAT_HARD == EF_ARM_ABI_FLOAT_HARD
52
+ )
53
+
54
+
55
+ def _is_linux_i686(executable: str) -> bool:
56
+ with _parse_elf(executable) as f:
57
+ return (
58
+ f is not None
59
+ and f.capacity == EIClass.C32
60
+ and f.encoding == EIData.Lsb
61
+ and f.machine == EMachine.I386
62
+ )
63
+
64
+
65
+ def _have_compatible_abi(executable: str, archs: Sequence[str]) -> bool:
66
+ if "armv7l" in archs:
67
+ return _is_linux_armhf(executable)
68
+ if "i686" in archs:
69
+ return _is_linux_i686(executable)
70
+ return any(arch in _ALLOWED_ARCHS for arch in archs)
71
+
72
+
73
+ # If glibc ever changes its major version, we need to know what the last
74
+ # minor version was, so we can build the complete list of all versions.
75
+ # For now, guess what the highest minor version might be, assume it will
76
+ # be 50 for testing. Once this actually happens, update the dictionary
77
+ # with the actual value.
78
+ _LAST_GLIBC_MINOR: dict[int, int] = collections.defaultdict(lambda: 50)
79
+
80
+
81
+ class _GLibCVersion(NamedTuple):
82
+ major: int
83
+ minor: int
84
+
85
+
86
+ def _glibc_version_string_confstr() -> str | None:
87
+ """
88
+ Primary implementation of glibc_version_string using os.confstr.
89
+ """
90
+ # os.confstr is quite a bit faster than ctypes.DLL. It's also less likely
91
+ # to be broken or missing. This strategy is used in the standard library
92
+ # platform module.
93
+ # https://github.com/python/cpython/blob/fcf1d003bf4f0100c/Lib/platform.py#L175-L183
94
+ try:
95
+ # Should be a string like "glibc 2.17".
96
+ version_string: str | None = os.confstr("CS_GNU_LIBC_VERSION")
97
+ assert version_string is not None
98
+ _, version = version_string.rsplit()
99
+ except (AssertionError, AttributeError, OSError, ValueError):
100
+ # os.confstr() or CS_GNU_LIBC_VERSION not available (or a bad value)...
101
+ return None
102
+ return version
103
+
104
+
105
+ def _glibc_version_string_ctypes() -> str | None:
106
+ """
107
+ Fallback implementation of glibc_version_string using ctypes.
108
+ """
109
+ try:
110
+ import ctypes # noqa: PLC0415
111
+ except ImportError:
112
+ return None
113
+
114
+ # ctypes.CDLL(None) internally calls dlopen(NULL), and as the dlopen
115
+ # manpage says, "If filename is NULL, then the returned handle is for the
116
+ # main program". This way we can let the linker do the work to figure out
117
+ # which libc our process is actually using.
118
+ #
119
+ # We must also handle the special case where the executable is not a
120
+ # dynamically linked executable. This can occur when using musl libc,
121
+ # for example. In this situation, dlopen() will error, leading to an
122
+ # OSError. Interestingly, at least in the case of musl, there is no
123
+ # errno set on the OSError. The single string argument used to construct
124
+ # OSError comes from libc itself and is therefore not portable to
125
+ # hard code here. In any case, failure to call dlopen() means we
126
+ # can proceed, so we bail on our attempt.
127
+ try:
128
+ process_namespace = ctypes.CDLL(None)
129
+ except OSError:
130
+ return None
131
+
132
+ try:
133
+ gnu_get_libc_version = process_namespace.gnu_get_libc_version
134
+ except AttributeError:
135
+ # Symbol doesn't exist -> therefore, we are not linked to
136
+ # glibc.
137
+ return None
138
+
139
+ # Call gnu_get_libc_version, which returns a string like "2.5"
140
+ gnu_get_libc_version.restype = ctypes.c_char_p
141
+ version_str: str = gnu_get_libc_version()
142
+ # py2 / py3 compatibility:
143
+ if not isinstance(version_str, str):
144
+ version_str = version_str.decode("ascii")
145
+
146
+ return version_str
147
+
148
+
149
+ def _glibc_version_string() -> str | None:
150
+ """Returns glibc version string, or None if not using glibc."""
151
+ return _glibc_version_string_confstr() or _glibc_version_string_ctypes()
152
+
153
+
154
+ def _parse_glibc_version(version_str: str) -> _GLibCVersion:
155
+ """Parse glibc version.
156
+
157
+ We use a regexp instead of str.split because we want to discard any
158
+ random junk that might come after the minor version -- this might happen
159
+ in patched/forked versions of glibc (e.g. Linaro's version of glibc
160
+ uses version strings like "2.20-2014.11"). See gh-3588.
161
+ """
162
+ m = re.match(r"(?P<major>[0-9]+)\.(?P<minor>[0-9]+)", version_str)
163
+ if not m:
164
+ warnings.warn(
165
+ f"Expected glibc version with 2 components major.minor, got: {version_str}",
166
+ RuntimeWarning,
167
+ stacklevel=2,
168
+ )
169
+ return _GLibCVersion(-1, -1)
170
+ return _GLibCVersion(int(m.group("major")), int(m.group("minor")))
171
+
172
+
173
+ @functools.lru_cache
174
+ def _get_glibc_version() -> _GLibCVersion:
175
+ version_str = _glibc_version_string()
176
+ if version_str is None:
177
+ return _GLibCVersion(-1, -1)
178
+ return _parse_glibc_version(version_str)
179
+
180
+
181
+ # From PEP 513, PEP 600
182
+ def _is_compatible(arch: str, version: _GLibCVersion) -> bool:
183
+ sys_glibc = _get_glibc_version()
184
+ if sys_glibc < version:
185
+ return False
186
+ # Check for presence of _manylinux module.
187
+ try:
188
+ import _manylinux # noqa: PLC0415
189
+ except ImportError:
190
+ return True
191
+ if hasattr(_manylinux, "manylinux_compatible"):
192
+ result = _manylinux.manylinux_compatible(version[0], version[1], arch)
193
+ if result is not None:
194
+ return bool(result)
195
+ return True
196
+ if version == _GLibCVersion(2, 5) and hasattr(_manylinux, "manylinux1_compatible"):
197
+ return bool(_manylinux.manylinux1_compatible)
198
+ if version == _GLibCVersion(2, 12) and hasattr(
199
+ _manylinux, "manylinux2010_compatible"
200
+ ):
201
+ return bool(_manylinux.manylinux2010_compatible)
202
+ if version == _GLibCVersion(2, 17) and hasattr(
203
+ _manylinux, "manylinux2014_compatible"
204
+ ):
205
+ return bool(_manylinux.manylinux2014_compatible)
206
+ return True
207
+
208
+
209
+ _LEGACY_MANYLINUX_MAP: dict[_GLibCVersion, str] = {
210
+ # CentOS 7 w/ glibc 2.17 (PEP 599)
211
+ _GLibCVersion(2, 17): "manylinux2014",
212
+ # CentOS 6 w/ glibc 2.12 (PEP 571)
213
+ _GLibCVersion(2, 12): "manylinux2010",
214
+ # CentOS 5 w/ glibc 2.5 (PEP 513)
215
+ _GLibCVersion(2, 5): "manylinux1",
216
+ }
217
+
218
+
219
+ def platform_tags(archs: Sequence[str]) -> Iterator[str]:
220
+ """Generate manylinux tags compatible to the current platform.
221
+
222
+ :param archs: Sequence of compatible architectures.
223
+ The first one shall be the closest to the actual architecture and be the part of
224
+ platform tag after the ``linux_`` prefix, e.g. ``x86_64``.
225
+ The ``linux_`` prefix is assumed as a prerequisite for the current platform to
226
+ be manylinux-compatible.
227
+
228
+ :returns: An iterator of compatible manylinux tags.
229
+ """
230
+ if not _have_compatible_abi(sys.executable, archs):
231
+ return
232
+ # Oldest glibc to be supported regardless of architecture is (2, 17).
233
+ too_old_glibc2 = _GLibCVersion(2, 16)
234
+ if set(archs) & {"x86_64", "i686"}:
235
+ # On x86/i686 also oldest glibc to be supported is (2, 5).
236
+ too_old_glibc2 = _GLibCVersion(2, 4)
237
+ current_glibc = _GLibCVersion(*_get_glibc_version())
238
+ glibc_max_list = [current_glibc]
239
+ # We can assume compatibility across glibc major versions.
240
+ # https://sourceware.org/bugzilla/show_bug.cgi?id=24636
241
+ #
242
+ # Build a list of maximum glibc versions so that we can
243
+ # output the canonical list of all glibc from current_glibc
244
+ # down to too_old_glibc2, including all intermediary versions.
245
+ for glibc_major in range(current_glibc.major - 1, 1, -1):
246
+ glibc_minor = _LAST_GLIBC_MINOR[glibc_major]
247
+ glibc_max_list.append(_GLibCVersion(glibc_major, glibc_minor))
248
+ for arch in archs:
249
+ for glibc_max in glibc_max_list:
250
+ if glibc_max.major == too_old_glibc2.major:
251
+ min_minor = too_old_glibc2.minor
252
+ else:
253
+ # For other glibc major versions oldest supported is (x, 0).
254
+ min_minor = -1
255
+ for glibc_minor in range(glibc_max.minor, min_minor, -1):
256
+ glibc_version = _GLibCVersion(glibc_max.major, glibc_minor)
257
+ if _is_compatible(arch, glibc_version):
258
+ yield "manylinux_{}_{}_{}".format(*glibc_version, arch)
259
+
260
+ # Handle the legacy manylinux1, manylinux2010, manylinux2014 tags.
261
+ if legacy_tag := _LEGACY_MANYLINUX_MAP.get(glibc_version):
262
+ yield f"{legacy_tag}_{arch}"
.venv_haddock/lib/python3.12/site-packages/packaging/_parser.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Handwritten parser of dependency specifiers.
2
+
3
+ The docstring for each __parse_* function contains EBNF-inspired grammar representing
4
+ the implementation.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ast
10
+ from typing import List, Literal, NamedTuple, Sequence, Tuple, Union
11
+
12
+ from ._tokenizer import DEFAULT_RULES, Tokenizer
13
+
14
+
15
+ class Node:
16
+ __slots__ = ("value",)
17
+
18
+ def __init__(self, value: str) -> None:
19
+ self.value = value
20
+
21
+ def __str__(self) -> str:
22
+ return self.value
23
+
24
+ def __repr__(self) -> str:
25
+ return f"<{self.__class__.__name__}({self.value!r})>"
26
+
27
+ def serialize(self) -> str:
28
+ raise NotImplementedError
29
+
30
+
31
+ class Variable(Node):
32
+ __slots__ = ()
33
+
34
+ def serialize(self) -> str:
35
+ return str(self)
36
+
37
+
38
+ class Value(Node):
39
+ __slots__ = ()
40
+
41
+ def serialize(self) -> str:
42
+ return f'"{self}"'
43
+
44
+
45
+ class Op(Node):
46
+ __slots__ = ()
47
+
48
+ def serialize(self) -> str:
49
+ return str(self)
50
+
51
+
52
+ MarkerLogical = Literal["and", "or"]
53
+ MarkerVar = Union[Variable, Value]
54
+ MarkerItem = Tuple[MarkerVar, Op, MarkerVar]
55
+ MarkerAtom = Union[MarkerItem, Sequence["MarkerAtom"]]
56
+ MarkerList = List[Union["MarkerList", MarkerAtom, MarkerLogical]]
57
+
58
+
59
+ class ParsedRequirement(NamedTuple):
60
+ name: str
61
+ url: str
62
+ extras: list[str]
63
+ specifier: str
64
+ marker: MarkerList | None
65
+
66
+
67
+ # --------------------------------------------------------------------------------------
68
+ # Recursive descent parser for dependency specifier
69
+ # --------------------------------------------------------------------------------------
70
+ def parse_requirement(source: str) -> ParsedRequirement:
71
+ return _parse_requirement(Tokenizer(source, rules=DEFAULT_RULES))
72
+
73
+
74
+ def _parse_requirement(tokenizer: Tokenizer) -> ParsedRequirement:
75
+ """
76
+ requirement = WS? IDENTIFIER WS? extras WS? requirement_details
77
+ """
78
+ tokenizer.consume("WS")
79
+
80
+ name_token = tokenizer.expect(
81
+ "IDENTIFIER", expected="package name at the start of dependency specifier"
82
+ )
83
+ name = name_token.text
84
+ tokenizer.consume("WS")
85
+
86
+ extras = _parse_extras(tokenizer)
87
+ tokenizer.consume("WS")
88
+
89
+ url, specifier, marker = _parse_requirement_details(tokenizer)
90
+ tokenizer.expect("END", expected="end of dependency specifier")
91
+
92
+ return ParsedRequirement(name, url, extras, specifier, marker)
93
+
94
+
95
+ def _parse_requirement_details(
96
+ tokenizer: Tokenizer,
97
+ ) -> tuple[str, str, MarkerList | None]:
98
+ """
99
+ requirement_details = AT URL (WS requirement_marker?)?
100
+ | specifier WS? (requirement_marker)?
101
+ """
102
+
103
+ specifier = ""
104
+ url = ""
105
+ marker = None
106
+
107
+ if tokenizer.check("AT"):
108
+ tokenizer.read()
109
+ tokenizer.consume("WS")
110
+
111
+ url_start = tokenizer.position
112
+ url = tokenizer.expect("URL", expected="URL after @").text
113
+ if tokenizer.check("END", peek=True):
114
+ return (url, specifier, marker)
115
+
116
+ tokenizer.expect("WS", expected="whitespace after URL")
117
+
118
+ # The input might end after whitespace.
119
+ if tokenizer.check("END", peek=True):
120
+ return (url, specifier, marker)
121
+
122
+ marker = _parse_requirement_marker(
123
+ tokenizer,
124
+ span_start=url_start,
125
+ expected="semicolon (after URL and whitespace)",
126
+ )
127
+ else:
128
+ specifier_start = tokenizer.position
129
+ specifier = _parse_specifier(tokenizer)
130
+ tokenizer.consume("WS")
131
+
132
+ if tokenizer.check("END", peek=True):
133
+ return (url, specifier, marker)
134
+
135
+ marker = _parse_requirement_marker(
136
+ tokenizer,
137
+ span_start=specifier_start,
138
+ expected=(
139
+ "comma (within version specifier), semicolon (after version specifier)"
140
+ if specifier
141
+ else "semicolon (after name with no version specifier)"
142
+ ),
143
+ )
144
+
145
+ return (url, specifier, marker)
146
+
147
+
148
+ def _parse_requirement_marker(
149
+ tokenizer: Tokenizer, *, span_start: int, expected: str
150
+ ) -> MarkerList:
151
+ """
152
+ requirement_marker = SEMICOLON marker WS?
153
+ """
154
+
155
+ if not tokenizer.check("SEMICOLON"):
156
+ tokenizer.raise_syntax_error(
157
+ f"Expected {expected} or end",
158
+ span_start=span_start,
159
+ span_end=None,
160
+ )
161
+ tokenizer.read()
162
+
163
+ marker = _parse_marker(tokenizer)
164
+ tokenizer.consume("WS")
165
+
166
+ return marker
167
+
168
+
169
+ def _parse_extras(tokenizer: Tokenizer) -> list[str]:
170
+ """
171
+ extras = (LEFT_BRACKET wsp* extras_list? wsp* RIGHT_BRACKET)?
172
+ """
173
+ if not tokenizer.check("LEFT_BRACKET", peek=True):
174
+ return []
175
+
176
+ with tokenizer.enclosing_tokens(
177
+ "LEFT_BRACKET",
178
+ "RIGHT_BRACKET",
179
+ around="extras",
180
+ ):
181
+ tokenizer.consume("WS")
182
+ extras = _parse_extras_list(tokenizer)
183
+ tokenizer.consume("WS")
184
+
185
+ return extras
186
+
187
+
188
+ def _parse_extras_list(tokenizer: Tokenizer) -> list[str]:
189
+ """
190
+ extras_list = identifier (wsp* ',' wsp* identifier)*
191
+ """
192
+ extras: list[str] = []
193
+
194
+ if not tokenizer.check("IDENTIFIER"):
195
+ return extras
196
+
197
+ extras.append(tokenizer.read().text)
198
+
199
+ while True:
200
+ tokenizer.consume("WS")
201
+ if tokenizer.check("IDENTIFIER", peek=True):
202
+ tokenizer.raise_syntax_error("Expected comma between extra names")
203
+ elif not tokenizer.check("COMMA"):
204
+ break
205
+
206
+ tokenizer.read()
207
+ tokenizer.consume("WS")
208
+
209
+ extra_token = tokenizer.expect("IDENTIFIER", expected="extra name after comma")
210
+ extras.append(extra_token.text)
211
+
212
+ return extras
213
+
214
+
215
+ def _parse_specifier(tokenizer: Tokenizer) -> str:
216
+ """
217
+ specifier = LEFT_PARENTHESIS WS? version_many WS? RIGHT_PARENTHESIS
218
+ | WS? version_many WS?
219
+ """
220
+ with tokenizer.enclosing_tokens(
221
+ "LEFT_PARENTHESIS",
222
+ "RIGHT_PARENTHESIS",
223
+ around="version specifier",
224
+ ):
225
+ tokenizer.consume("WS")
226
+ parsed_specifiers = _parse_version_many(tokenizer)
227
+ tokenizer.consume("WS")
228
+
229
+ return parsed_specifiers
230
+
231
+
232
+ def _parse_version_many(tokenizer: Tokenizer) -> str:
233
+ """
234
+ version_many = (SPECIFIER (WS? COMMA WS? SPECIFIER)*)?
235
+ """
236
+ parsed_specifiers = ""
237
+ while tokenizer.check("SPECIFIER"):
238
+ span_start = tokenizer.position
239
+ parsed_specifiers += tokenizer.read().text
240
+ if tokenizer.check("VERSION_PREFIX_TRAIL", peek=True):
241
+ tokenizer.raise_syntax_error(
242
+ ".* suffix can only be used with `==` or `!=` operators",
243
+ span_start=span_start,
244
+ span_end=tokenizer.position + 1,
245
+ )
246
+ if tokenizer.check("VERSION_LOCAL_LABEL_TRAIL", peek=True):
247
+ tokenizer.raise_syntax_error(
248
+ "Local version label can only be used with `==` or `!=` operators",
249
+ span_start=span_start,
250
+ span_end=tokenizer.position,
251
+ )
252
+ tokenizer.consume("WS")
253
+ if not tokenizer.check("COMMA"):
254
+ break
255
+ parsed_specifiers += tokenizer.read().text
256
+ tokenizer.consume("WS")
257
+
258
+ return parsed_specifiers
259
+
260
+
261
+ # --------------------------------------------------------------------------------------
262
+ # Recursive descent parser for marker expression
263
+ # --------------------------------------------------------------------------------------
264
+ def parse_marker(source: str) -> MarkerList:
265
+ return _parse_full_marker(Tokenizer(source, rules=DEFAULT_RULES))
266
+
267
+
268
+ def _parse_full_marker(tokenizer: Tokenizer) -> MarkerList:
269
+ retval = _parse_marker(tokenizer)
270
+ tokenizer.expect("END", expected="end of marker expression")
271
+ return retval
272
+
273
+
274
+ def _parse_marker(tokenizer: Tokenizer) -> MarkerList:
275
+ """
276
+ marker = marker_atom (BOOLOP marker_atom)+
277
+ """
278
+ expression = [_parse_marker_atom(tokenizer)]
279
+ while tokenizer.check("BOOLOP"):
280
+ token = tokenizer.read()
281
+ expr_right = _parse_marker_atom(tokenizer)
282
+ expression.extend((token.text, expr_right))
283
+ return expression
284
+
285
+
286
+ def _parse_marker_atom(tokenizer: Tokenizer) -> MarkerAtom:
287
+ """
288
+ marker_atom = WS? LEFT_PARENTHESIS WS? marker WS? RIGHT_PARENTHESIS WS?
289
+ | WS? marker_item WS?
290
+ """
291
+
292
+ tokenizer.consume("WS")
293
+ if tokenizer.check("LEFT_PARENTHESIS", peek=True):
294
+ with tokenizer.enclosing_tokens(
295
+ "LEFT_PARENTHESIS",
296
+ "RIGHT_PARENTHESIS",
297
+ around="marker expression",
298
+ ):
299
+ tokenizer.consume("WS")
300
+ marker: MarkerAtom = _parse_marker(tokenizer)
301
+ tokenizer.consume("WS")
302
+ else:
303
+ marker = _parse_marker_item(tokenizer)
304
+ tokenizer.consume("WS")
305
+ return marker
306
+
307
+
308
+ def _parse_marker_item(tokenizer: Tokenizer) -> MarkerItem:
309
+ """
310
+ marker_item = WS? marker_var WS? marker_op WS? marker_var WS?
311
+ """
312
+ tokenizer.consume("WS")
313
+ marker_var_left = _parse_marker_var(tokenizer)
314
+ tokenizer.consume("WS")
315
+ marker_op = _parse_marker_op(tokenizer)
316
+ tokenizer.consume("WS")
317
+ marker_var_right = _parse_marker_var(tokenizer)
318
+ tokenizer.consume("WS")
319
+ return (marker_var_left, marker_op, marker_var_right)
320
+
321
+
322
+ def _parse_marker_var(tokenizer: Tokenizer) -> MarkerVar: # noqa: RET503
323
+ """
324
+ marker_var = VARIABLE | QUOTED_STRING
325
+ """
326
+ if tokenizer.check("VARIABLE"):
327
+ return process_env_var(tokenizer.read().text.replace(".", "_"))
328
+ elif tokenizer.check("QUOTED_STRING"):
329
+ return process_python_str(tokenizer.read().text)
330
+ else:
331
+ tokenizer.raise_syntax_error(
332
+ message="Expected a marker variable or quoted string"
333
+ )
334
+
335
+
336
+ def process_env_var(env_var: str) -> Variable:
337
+ if env_var in ("platform_python_implementation", "python_implementation"):
338
+ return Variable("platform_python_implementation")
339
+ else:
340
+ return Variable(env_var)
341
+
342
+
343
+ def process_python_str(python_str: str) -> Value:
344
+ value = ast.literal_eval(python_str)
345
+ return Value(str(value))
346
+
347
+
348
+ def _parse_marker_op(tokenizer: Tokenizer) -> Op:
349
+ """
350
+ marker_op = IN | NOT IN | OP
351
+ """
352
+ if tokenizer.check("IN"):
353
+ tokenizer.read()
354
+ return Op("in")
355
+ elif tokenizer.check("NOT"):
356
+ tokenizer.read()
357
+ tokenizer.expect("WS", expected="whitespace after 'not'")
358
+ tokenizer.expect("IN", expected="'in' after 'not'")
359
+ return Op("not in")
360
+ elif tokenizer.check("OP"):
361
+ return Op(tokenizer.read().text)
362
+ else:
363
+ return tokenizer.raise_syntax_error(
364
+ "Expected marker operator, one of <=, <, !=, ==, >=, >, ~=, ===, in, not in"
365
+ )