1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313
|
# -*- Mode: python; tab-width: 4; indent-tabs-mode:nil; coding:utf-8 -*-
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
# MDAnalysis --- https://www.mdanalysis.org
# Copyright (c) 2006-2017 The MDAnalysis Development Team and contributors
# (see the file AUTHORS for the full list of names)
#
# Released under the Lesser GNU Public Licence, v2.1 or any higher version
#
# Please cite your use of MDAnalysis in published work:
#
# R. J. Gowers, M. Linke, J. Barnoud, T. J. E. Reddy, M. N. Melo, S. L. Seyler,
# D. L. Dotson, J. Domanski, S. Buchoux, I. M. Kenney, and O. Beckstein.
# MDAnalysis: A Python package for the rapid analysis of molecular dynamics
# simulations. In S. Benthall and S. Rostrup editors, Proceedings of the 15th
# Python in Science Conference, pages 102-109, Austin, TX, 2016. SciPy.
# doi: 10.25080/majora-629e541a-00e
#
# N. Michaud-Agrawal, E. J. Denning, T. B. Woolf, and O. Beckstein.
# MDAnalysis: A Toolkit for the Analysis of Molecular Dynamics Simulations.
# J. Comput. Chem. 32 (2011), 2319--2327, doi:10.1002/jcc.21787
#
"""\
Base classes --- :mod:`MDAnalysis.coordinates.base`
===================================================
Derive, FrameIterator, Reader and Writer classes from the classes
in this module. The derived classes must follow the :ref:`Trajectory API`.
.. _FrameIterators:
FrameIterators
--------------
FrameIterators are "sliced trajectories" (a trajectory is a
:ref:`Reader <Readers>`) that can be iterated over. They are typically
created by slicing a trajectory or by fancy-indexing of a trajectory
with an array of frame numbers or a boolean mask of all frames.
Iterator classes used by the by the :class:`ProtoReader`:
.. autoclass:: FrameIteratorBase
.. autoclass:: FrameIteratorSliced
.. autoclass:: FrameIteratorAll
.. autoclass:: FrameIteratorIndices
.. autoclass:: StreamFrameIteratorSliced
.. _ReadersBase:
Readers
-------
Readers know how to take trajectory data in a given format and present it in a
common API to the user in MDAnalysis. There are two types of readers:
1. Readers for *multi frame trajectories*, i.e., file formats that typically
contain many frames. These readers are typically derived from
:class:`ReaderBase`.
2. Readers for *single frame formats*: These file formats only contain a single
coordinate set. These readers are derived from
:class:`SingleFrameReaderBase`.
The underlying low-level readers handle closing of files in different
ways. Typically, the MDAnalysis readers try to ensure that files are always
closed when a reader instance is garbage collected, which relies on
implementing a :meth:`~ReaderBase.__del__` method. However, in some cases, this
is not necessary (for instance, for the single frame formats) and then such a
method can lead to undesirable side effects (such as memory leaks). In this
case, :class:`ProtoReader` should be used.
.. autoclass:: ReaderBase
:members:
:inherited-members:
.. autoclass:: SingleFrameReaderBase
:members:
:inherited-members:
.. autoclass:: ProtoReader
:members:
.. autoclass:: StreamReaderBase
:members:
.. _WritersBase:
Writers
-------
Writers know how to write information in a :class:`Timestep` to a trajectory
file.
.. autoclass:: WriterBase
:members:
:inherited-members:
Converters
----------
Converters output information to other libraries.
.. deprecated:: 2.7.0
All converter code has been moved to :mod:`MDAnalysis.converters` and will
be removed from the :mod:`MDAnalysis.coordinates.base` module in 3.0.0.
.. autoclass:: ConverterBase
:members:
:inherited-members:
Helper classes
--------------
The following classes contain basic functionality that all readers and
writers share.
.. autoclass:: IOBase
:members:
"""
import abc
import numpy as np
import numbers
import warnings
from typing import Any, Union, Optional, List, Dict
from .timestep import Timestep
from . import core
from .. import (
_READERS, _READER_HINTS,
_SINGLEFRAME_WRITERS,
_MULTIFRAME_WRITERS,
_CONVERTERS, # remove in 3.0.0 (Issue #3404)
)
from .. import units
from ..auxiliary.base import AuxReader
from ..auxiliary.core import auxreader
from ..auxiliary.core import get_auxreader_for
from ..auxiliary import _AUXREADERS
from ..lib.util import asiterable, Namespace, store_init_arguments
from ..lib.util import NamedStream
class FrameIteratorBase(object):
"""
Base iterable over the frames of a trajectory.
A frame iterable has a length that can be accessed with the :func:`len`
function, and can be indexed similarly to a full trajectory. When indexed,
indices are resolved relative to the iterable and not relative to the
trajectory.
.. versionadded:: 0.19.0
"""
def __init__(self, trajectory):
self._trajectory = trajectory
def __len__(self):
raise NotImplementedError()
@staticmethod
def _avoid_bool_list(frames):
if isinstance(frames, list) and frames and isinstance(frames[0], bool):
return np.array(frames, dtype=bool)
return frames
@property
def trajectory(self):
return self._trajectory
class FrameIteratorSliced(FrameIteratorBase):
"""
Iterable over the frames of a trajectory on the basis of a slice.
Parameters
----------
trajectory: ProtoReader
The trajectory over which to iterate.
frames: slice
A slice to select the frames of interest.
See Also
--------
FrameIteratorBase
.. versionadded:: 0.19.0
"""
def __init__(self, trajectory, frames):
# It would be easier to store directly a range object, as it would
# store its parameters in a single place, calculate its length, and
# take care of most the indexing. Though, doing so is not compatible
# with python 2 where xrange (or range with six) is only an iterator.
super(FrameIteratorSliced, self).__init__(trajectory)
self._start, self._stop, self._step = trajectory.check_slice_indices(
frames.start, frames.stop, frames.step,
)
def __len__(self):
return range_length(self.start, self.stop, self.step)
def __iter__(self):
for i in range(self.start, self.stop, self.step):
yield self.trajectory[i]
self.trajectory.rewind()
def __getitem__(self, frame):
if isinstance(frame, numbers.Integral):
length = len(self)
if not -length < frame < length:
raise IndexError('Index {} is out of range of the range of length {}.'
.format(frame, length))
if frame < 0:
frame = len(self) + frame
frame = self.start + frame * self.step
return self.trajectory._read_frame_with_aux(frame)
elif isinstance(frame, slice):
step = (frame.step or 1) * self.step
if frame.start is None:
if frame.step is None or frame.step > 0:
start = self.start
else:
start = self.start + (len(self) - 1) * self.step
else:
start = self.start + (frame.start or 0) * self.step
if frame.stop is None:
if frame.step is None or frame.step > 0:
last = start + (range_length(start, self.stop, step) - 1) * step
else:
last = self.start
stop = last + np.sign(step)
else:
stop = self.start + (frame.stop or 0) * self.step
new_slice = slice(start, stop, step)
frame_iterator = FrameIteratorSliced(self.trajectory, new_slice)
# The __init__ of FrameIteratorSliced does some conversion between
# the way indices are handled in slices and the way they are
# handled by range. We need to overwrite this conversion as we
# already use the logic for range.
frame_iterator._start = start
frame_iterator._stop = stop
frame_iterator._step = step
return frame_iterator
else:
# Indexing with a lists of bools does not behave the same in all
# version of numpy.
frame = self._avoid_bool_list(frame)
frames = np.array(list(range(self.start, self.stop, self.step)))[frame]
return FrameIteratorIndices(self.trajectory, frames)
@property
def start(self):
return self._start
@property
def stop(self):
return self._stop
@property
def step(self):
return self._step
class FrameIteratorAll(FrameIteratorBase):
"""
Iterable over all the frames of a trajectory.
Parameters
----------
trajectory: ProtoReader
The trajectory over which to iterate.
See Also
--------
FrameIteratorBase
.. versionadded:: 0.19.0
"""
def __init__(self, trajectory):
super(FrameIteratorAll, self).__init__(trajectory)
def __len__(self):
return self.trajectory.n_frames
def __iter__(self):
return iter(self.trajectory)
def __getitem__(self, frame):
return self.trajectory[frame]
class FrameIteratorIndices(FrameIteratorBase):
"""
Iterable over the frames of a trajectory listed in a sequence of indices.
Parameters
----------
trajectory: ProtoReader
The trajectory over which to iterate.
frames: sequence
A sequence of indices.
See Also
--------
FrameIteratorBase
"""
def __init__(self, trajectory, frames):
super(FrameIteratorIndices, self).__init__(trajectory)
self._frames = []
for frame in frames:
if not isinstance(frame, numbers.Integral):
raise TypeError("Frames indices must be integers.")
frame = trajectory._apply_limits(frame)
self._frames.append(frame)
self._frames = tuple(self._frames)
def __len__(self):
return len(self.frames)
def __iter__(self):
for frame in self.frames:
yield self.trajectory._read_frame_with_aux(frame)
self.trajectory.rewind()
def __getitem__(self, frame):
if isinstance(frame, numbers.Integral):
frame = self.frames[frame]
return self.trajectory._read_frame_with_aux(frame)
else:
frame = self._avoid_bool_list(frame)
frames = np.array(self.frames)[frame]
return FrameIteratorIndices(self.trajectory, frames)
@property
def frames(self):
return self._frames
class IOBase(object):
"""Base class bundling common functionality for trajectory I/O.
.. versionchanged:: 0.8
Added context manager protocol.
"""
#: dict with units of of *time* and *length* (and *velocity*, *force*,
#: ... for formats that support it)
units = {'time': None, 'length': None, 'velocity': None}
def convert_pos_from_native(self, x, inplace=True):
"""Conversion of coordinate array x from native units to base units.
Parameters
----------
x : array_like
Positions to transform
inplace : bool (optional)
Whether to modify the array inplace, overwriting previous data
Note
----
By default, the input `x` is modified in place and also returned.
In-place operations improve performance because allocating new arrays
is avoided.
.. versionchanged:: 0.7.5
Keyword `inplace` can be set to ``False`` so that a
modified copy is returned *unless* no conversion takes
place, in which case the reference to the unmodified `x` is
returned.
"""
f = units.get_conversion_factor('length',
self.units['length'], 'Angstrom')
if f == 1.:
return x
if not inplace:
return f * x
x *= f
return x
def convert_velocities_from_native(self, v, inplace=True):
"""Conversion of velocities array *v* from native to base units
Parameters
----------
v : array_like
Velocities to transform
inplace : bool (optional)
Whether to modify the array inplace, overwriting previous data
Note
----
By default, the input *v* is modified in place and also returned.
In-place operations improve performance because allocating new arrays
is avoided.
.. versionadded:: 0.7.5
"""
f = units.get_conversion_factor(
'speed', self.units['velocity'], 'Angstrom/ps')
if f == 1.:
return v
if not inplace:
return f * v
v *= f
return v
def convert_forces_from_native(self, force, inplace=True):
"""Conversion of forces array *force* from native to base units
Parameters
----------
force : array_like
Forces to transform
inplace : bool (optional)
Whether to modify the array inplace, overwriting previous data
Note
----
By default, the input *force* is modified in place and also returned.
In-place operations improve performance because allocating new arrays
is avoided.
.. versionadded:: 0.7.7
"""
f = units.get_conversion_factor(
'force', self.units['force'], 'kJ/(mol*Angstrom)')
if f == 1.:
return force
if not inplace:
return f * force
force *= f
return force
def convert_time_from_native(self, t, inplace=True):
"""Convert time *t* from native units to base units.
Parameters
----------
t : array_like
Time values to transform
inplace : bool (optional)
Whether to modify the array inplace, overwriting previous data
Note
----
By default, the input `t` is modified in place and also returned
(although note that scalar values `t` are passed by value in Python and
hence an in-place modification has no effect on the caller.) In-place
operations improve performance because allocating new arrays is
avoided.
.. versionchanged:: 0.7.5
Keyword `inplace` can be set to ``False`` so that a
modified copy is returned *unless* no conversion takes
place, in which case the reference to the unmodified `x` is
returned.
"""
f = units.get_conversion_factor(
'time', self.units['time'], 'ps')
if f == 1.:
return t
if not inplace:
return f * t
t *= f
return t
def convert_pos_to_native(self, x, inplace=True):
"""Conversion of coordinate array `x` from base units to native units.
Parameters
----------
x : array_like
Positions to transform
inplace : bool (optional)
Whether to modify the array inplace, overwriting previous data
Note
----
By default, the input `x` is modified in place and also returned.
In-place operations improve performance because allocating new arrays
is avoided.
.. versionchanged:: 0.7.5
Keyword `inplace` can be set to ``False`` so that a
modified copy is returned *unless* no conversion takes
place, in which case the reference to the unmodified `x` is
returned.
"""
f = units.get_conversion_factor(
'length', 'Angstrom', self.units['length'])
if f == 1.:
return x
if not inplace:
return f * x
x *= f
return x
def convert_velocities_to_native(self, v, inplace=True):
"""Conversion of coordinate array `v` from base to native units
Parameters
----------
v : array_like
Velocities to transform
inplace : bool (optional)
Whether to modify the array inplace, overwriting previous data
Note
----
By default, the input `v` is modified in place and also returned.
In-place operations improve performance because allocating new arrays
is avoided.
.. versionadded:: 0.7.5
"""
f = units.get_conversion_factor(
'speed', 'Angstrom/ps', self.units['velocity'])
if f == 1.:
return v
if not inplace:
return f * v
v *= f
return v
def convert_forces_to_native(self, force, inplace=True):
"""Conversion of force array *force* from base to native units.
Parameters
----------
force : array_like
Forces to transform
inplace : bool (optional)
Whether to modify the array inplace, overwriting previous data
Note
----
By default, the input `force` is modified in place and also returned.
In-place operations improve performance because allocating new arrays
is avoided.
.. versionadded:: 0.7.7
"""
f = units.get_conversion_factor(
'force', 'kJ/(mol*Angstrom)', self.units['force'])
if f == 1.:
return force
if not inplace:
return f * force
force *= f
return force
def convert_time_to_native(self, t, inplace=True):
"""Convert time *t* from base units to native units.
Parameters
----------
t : array_like
Time values to transform
inplace : bool, optional
Whether to modify the array inplace, overwriting previous data
Note
----
By default, the input *t* is modified in place and also
returned. (Also note that scalar values *t* are passed by
value in Python and hence an in-place modification has no
effect on the caller.)
.. versionchanged:: 0.7.5
Keyword *inplace* can be set to ``False`` so that a
modified copy is returned *unless* no conversion takes
place, in which case the reference to the unmodified *x* is
returned.
"""
f = units.get_conversion_factor(
'time', 'ps', self.units['time'])
if f == 1.:
return t
if not inplace:
return f * t
t *= f
return t
def close(self):
"""Close the trajectory file."""
pass # pylint: disable=unnecessary-pass
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
# see http://docs.python.org/2/library/stdtypes.html#typecontextmanager
self.close()
return False # do not suppress exceptions
class _Readermeta(abc.ABCMeta):
"""Automatic Reader registration metaclass
.. versionchanged:: 1.0.0
Added _format_hint functionality
"""
# Auto register upon class creation
def __init__(cls, name, bases, classdict):
type.__init__(type, name, bases, classdict) # pylint: disable=non-parent-init-called
try:
fmt = asiterable(classdict['format'])
except KeyError:
pass
else:
for fmt_name in fmt:
fmt_name = fmt_name.upper()
_READERS[fmt_name] = cls
if '_format_hint' in classdict:
# isn't bound yet, so access __func__
_READER_HINTS[fmt_name] = classdict['_format_hint'].__func__
class ProtoReader(IOBase, metaclass=_Readermeta):
"""Base class for Readers, without a :meth:`__del__` method.
Extends :class:`IOBase` with most attributes and methods of a generic
Reader, with the exception of a :meth:`__del__` method. It should be used
as base for Readers that do not need :meth:`__del__`, especially since
having even an empty :meth:`__del__` might lead to memory leaks.
See the :ref:`Trajectory API` definition in
:mod:`MDAnalysis.coordinates.__init__` for the required attributes and
methods.
See Also
--------
:class:`ReaderBase`
.. versionchanged:: 0.11.0
Frames now 0-based instead of 1-based
.. versionchanged:: 2.0.0
Now supports (un)pickle. Upon unpickling,
the current timestep is retained by reconstrunction.
.. versionchanged:: 2.8.0
the modification of coordinates was preserved
after serialization.
"""
#: The appropriate Timestep class, e.g.
#: :class:`MDAnalysis.coordinates.xdrfile.XTC.Timestep` for XTC.
_Timestep = Timestep
_transformations: list
_auxs: dict
_filename: Any
n_frames: int
def __init__(self):
# initialise list to store added auxiliary readers in
# subclasses should now call super
self._auxs = {}
self._transformations=[]
def __len__(self) -> int:
return self.n_frames
@classmethod
def parse_n_atoms(cls, filename, **kwargs):
"""Read the coordinate file and deduce the number of atoms
Returns
-------
n_atoms : int
the number of atoms in the coordinate file
Raises
------
NotImplementedError
when the number of atoms can't be deduced
"""
raise NotImplementedError("{} cannot deduce the number of atoms"
"".format(cls.__name__))
def next(self) -> Timestep:
"""Forward one step to next frame."""
try:
ts = self._read_next_timestep()
except (EOFError, IOError):
self.rewind()
raise StopIteration from None
else:
for auxname, reader in self._auxs.items():
ts = self._auxs[auxname].update_ts(ts)
ts = self._apply_transformations(ts)
return ts
def __next__(self) -> Timestep:
"""Forward one step to next frame when using the `next` builtin."""
return self.next()
def rewind(self) -> Timestep:
"""Position at beginning of trajectory"""
self._reopen()
self.next()
@property
def dt(self) -> float:
"""Time between two trajectory frames in picoseconds."""
return self.ts.dt
@property
def totaltime(self) -> float:
"""Total length of the trajectory
The time is calculated as ``(n_frames - 1) * dt``, i.e., we assume that
the first frame no time as elapsed. Thus, a trajectory with two frames will
be considered to have a length of a single time step `dt` and a
"trajectory" with a single frame will be reported as length 0.
"""
return (self.n_frames - 1) * self.dt
@property
def frame(self) -> int:
"""Frame number of the current time step.
This is a simple short cut to :attr:`Timestep.frame`.
"""
return self.ts.frame
@property
def time(self):
"""Time of the current frame in MDAnalysis time units (typically ps).
This is either read straight from the Timestep, or calculated as
time = :attr:`Timestep.frame` * :attr:`Timestep.dt`
"""
return self.ts.time
@property
def trajectory(self):
# Makes a reader effectively commpatible with a FrameIteratorBase
return self
def Writer(self, filename, **kwargs):
"""A trajectory writer with the same properties as this trajectory."""
raise NotImplementedError(
"Sorry, there is no Writer for this format in MDAnalysis. "
"Please file an enhancement request at "
"https://github.com/MDAnalysis/mdanalysis/issues")
def OtherWriter(self, filename, **kwargs):
"""Returns a writer appropriate for *filename*.
Sets the default keywords *start*, *step* and *dt* (if
available). *n_atoms* is always set from :attr:`Reader.n_atoms`.
See Also
--------
:meth:`Reader.Writer` and :func:`MDAnalysis.Writer`
"""
kwargs['n_atoms'] = self.n_atoms # essential
kwargs.setdefault('start', self.frame)
try:
kwargs.setdefault('dt', self.dt)
except KeyError:
pass
return core.writer(filename, **kwargs)
@abc.abstractmethod
def _read_next_timestep(self, ts=None):
# Example from DCDReader:
# if ts is None:
# ts = self.ts
# ts.frame = self._read_next_frame(etc)
# return ts
...
def __iter__(self):
""" Iterate over trajectory frames. """
self._reopen()
return self
@abc.abstractmethod
def _reopen(self):
"""Should position Reader to just before first frame
Calling next after this should return the first frame
"""
pass # pylint: disable=unnecessary-pass
def _apply_limits(self, frame):
if frame < 0:
frame += len(self)
if frame < 0 or frame >= len(self):
raise IndexError("Index {} exceeds length of trajectory ({})."
"".format(frame, len(self)))
return frame
def __getitem__(self, frame):
"""Return the Timestep corresponding to *frame*.
If `frame` is a integer then the corresponding frame is
returned. Negative numbers are counted from the end.
If frame is a :class:`slice` then an iterator is returned that
allows iteration over that part of the trajectory.
Note
----
*frame* is a 0-based frame index.
"""
if isinstance(frame, numbers.Integral):
frame = self._apply_limits(frame)
return self._read_frame_with_aux(frame)
elif isinstance(frame, (list, np.ndarray)):
if len(frame) != 0 and isinstance(frame[0], (bool, np.bool_)):
# Avoid having list of bools
frame = np.asarray(frame, dtype=bool)
# Convert bool array to int array
frame = np.arange(len(self))[frame]
return FrameIteratorIndices(self, frame)
elif isinstance(frame, slice):
start, stop, step = self.check_slice_indices(
frame.start, frame.stop, frame.step)
if start == 0 and stop == len(self) and step == 1:
return FrameIteratorAll(self)
else:
return FrameIteratorSliced(self, frame)
else:
raise TypeError("Trajectories must be an indexed using an integer,"
" slice or list of indices")
def _read_frame(self, frame):
"""Move to *frame* and fill timestep with data."""
raise TypeError("{0} does not support direct frame indexing."
"".format(self.__class__.__name__))
# Example implementation in the DCDReader:
# self._jump_to_frame(frame)
# ts = self.ts
# ts.frame = self._read_next_frame(ts._x, ts._y, ts._z,
# ts.dimensions, 1)
# return ts
def _read_frame_with_aux(self, frame):
"""Move to *frame*, updating ts with trajectory, transformations and auxiliary data."""
ts = self._read_frame(frame) # pylint: disable=assignment-from-no-return
for aux in self.aux_list:
ts = self._auxs[aux].update_ts(ts)
ts = self._apply_transformations(ts)
return ts
def _sliced_iter(self, start, stop, step):
"""Generator for slicing a trajectory.
*start* *stop* and *step* are 3 integers describing the slice.
Error checking is not done past this point.
A :exc:`NotImplementedError` is raised if random access to
frames is not implemented.
"""
# override with an appropriate implementation e.g. using self[i] might
# be much slower than skipping steps in a next() loop
try:
for i in range(start, stop, step):
yield self._read_frame_with_aux(i)
self.rewind()
except TypeError: # if _read_frame not implemented
errmsg = f"{self.__class__.__name__} does not support slicing."
raise TypeError(errmsg) from None
def check_slice_indices(self, start, stop, step):
"""Check frame indices are valid and clip to fit trajectory.
The usage follows standard Python conventions for :func:`range` but see
the warning below.
Parameters
----------
start : int or None
Starting frame index (inclusive). ``None`` corresponds to the default
of 0, i.e., the initial frame.
stop : int or None
Last frame index (exclusive). ``None`` corresponds to the default
of n_frames, i.e., it includes the last frame of the trajectory.
step : int or None
step size of the slice, ``None`` corresponds to the default of 1, i.e,
include every frame in the range `start`, `stop`.
Returns
-------
start, stop, step : tuple (int, int, int)
Integers representing the slice
Warning
-------
The returned values `start`, `stop` and `step` give the expected result
when passed in :func:`range` but gives unexpected behavior when passed
in a :class:`slice` when ``stop=None`` and ``step=-1``
This can be a problem for downstream processing of the output from this
method. For example, slicing of trajectories is implemented by passing
the values returned by :meth:`check_slice_indices` to :func:`range` ::
range(start, stop, step)
and using them as the indices to randomly seek to. On the other hand,
in :class:`MDAnalysis.analysis.base.AnalysisBase` the values returned
by :meth:`check_slice_indices` are used to splice the trajectory by
creating a :class:`slice` instance ::
slice(start, stop, step)
This creates a discrepancy because these two lines are not equivalent::
range(10, -1, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
range(10)[slice(10, -1, -1)] # []
"""
slice_dict = {'start': start, 'stop': stop, 'step': step}
for varname, var in slice_dict.items():
if isinstance(var, numbers.Integral):
slice_dict[varname] = int(var)
elif (var is None):
pass
else:
raise TypeError("{0} is not an integer".format(varname))
start = slice_dict['start']
stop = slice_dict['stop']
step = slice_dict['step']
if step == 0:
raise ValueError("Step size is zero")
nframes = len(self)
step = step or 1
if start is None:
start = 0 if step > 0 else nframes - 1
elif start < 0:
start += nframes
if start < 0:
start = 0
if step < 0 and start >= nframes:
start = nframes - 1
if stop is None:
stop = nframes if step > 0 else -1
elif stop < 0:
stop += nframes
if step > 0 and stop > nframes:
stop = nframes
return start, stop, step
def __repr__(self):
return ("<{cls} {fname} with {nframes} frames of {natoms} atoms>"
"".format(
cls=self.__class__.__name__,
fname=self.filename,
nframes=self.n_frames,
natoms=self.n_atoms
))
def timeseries(self, asel: Optional['AtomGroup']=None,
atomgroup: Optional['Atomgroup']=None,
start: Optional[int]=None, stop: Optional[int]=None,
step: Optional[int]=None,
order: Optional[str]='fac') -> np.ndarray:
"""Return a subset of coordinate data for an AtomGroup
Parameters
----------
asel : AtomGroup (optional)
The :class:`~MDAnalysis.core.groups.AtomGroup` to read the
coordinates from. Defaults to ``None``, in which case the full set
of coordinate data is returned.
.. deprecated:: 2.7.0
asel argument will be renamed to atomgroup in 3.0.0
atomgroup: AtomGroup (optional)
Same as `asel`, will replace `asel` in 3.0.0
start : int (optional)
Begin reading the trajectory at frame index `start` (where 0 is the
index of the first frame in the trajectory); the default
``None`` starts at the beginning.
stop : int (optional)
End reading the trajectory at frame index `stop`-1, i.e, `stop` is
excluded. The trajectory is read to the end with the default
``None``.
step : int (optional)
Step size for reading; the default ``None`` is equivalent to 1 and
means to read every frame.
order : str (optional)
the order/shape of the return data array, corresponding
to (a)tom, (f)rame, (c)oordinates all six combinations
of 'a', 'f', 'c' are allowed ie "fac" - return array
where the shape is (frame, number of atoms,
coordinates)
See Also
--------
:class:`MDAnalysis.coordinates.memory`
.. versionadded:: 2.4.0
"""
if asel is not None:
warnings.warn(
"asel argument to timeseries will be renamed to"
"'atomgroup' in 3.0, see #3911",
category=DeprecationWarning)
if atomgroup:
raise ValueError("Cannot provide both asel and atomgroup kwargs")
atomgroup = asel
start, stop, step = self.check_slice_indices(start, stop, step)
nframes = len(range(start, stop, step))
if atomgroup is not None:
if len(atomgroup) == 0:
raise ValueError(
"Timeseries requires at least one atom to analyze")
atom_numbers = atomgroup.indices
natoms = len(atom_numbers)
else:
natoms = self.n_atoms
atom_numbers = np.arange(natoms)
# allocate output array in 'fac' order
coordinates = np.empty((nframes, natoms, 3), dtype=np.float32)
for i, ts in enumerate(self[start:stop:step]):
coordinates[i, :] = ts.positions[atom_numbers]
# switch axes around
default_order = 'fac'
if order != default_order:
try:
newidx = [default_order.index(i) for i in order]
except ValueError:
raise ValueError(f"Unrecognized order key in {order}, "
"must be permutation of 'fac'")
try:
coordinates = np.moveaxis(coordinates, newidx, [0, 1, 2])
except ValueError:
errmsg = ("Repeated or missing keys passed to argument "
f"`order`: {order}, each key must be used once")
raise ValueError(errmsg)
return coordinates
# TODO: Change order of aux_spec and auxdata for 3.0 release, cf. Issue #3811
def add_auxiliary(self,
aux_spec: Union[str, Dict[str, str]] = None,
auxdata: Union[str, AuxReader] = None,
format: str = None,
**kwargs) -> None:
"""Add auxiliary data to be read alongside trajectory.
Auxiliary data may be any data timeseries from the trajectory
additional to that read in by the trajectory reader. *auxdata* can
be an :class:`~MDAnalysis.auxiliary.base.AuxReader` instance, or the
data itself as e.g. a filename; in the latter case an appropriate
:class:`~MDAnalysis.auxiliary.base.AuxReader` is guessed from the
data/file format. An appropriate `format` may also be directly provided
as a key word argument.
On adding, the AuxReader is initially matched to the current timestep
of the trajectory, and will be updated when the trajectory timestep
changes (through a call to :meth:`next()` or jumping timesteps with
``trajectory[i]``).
The representative value(s) of the auxiliary data for each timestep (as
calculated by the :class:`~MDAnalysis.auxiliary.base.AuxReader`) are
stored in the current timestep in the ``ts.aux`` namespace under
*aux_spec*; e.g. to add additional pull force data stored in
pull-force.xvg::
u = MDAnalysis.Universe(PDB, XTC)
u.trajectory.add_auxiliary('pull', 'pull-force.xvg')
The representative value for the current timestep may then be accessed
as ``u.trajectory.ts.aux.pull`` or ``u.trajectory.ts.aux['pull']``.
The following applies to energy readers like the
:class:`~MDAnalysis.auxiliary.EDR.EDRReader`.
All data that is present in the (energy) file can be added by omitting
`aux_spec` like so::
u.trajectory.add_auxiliary(auxdata="ener.edr")
*aux_spec* is expected to be a dictionary that maps the desired
attribute name in the ``ts.aux`` namespace to the precise data to be
added as identified by a :attr:`data_selector`::
term_dict = {"temp": "Temperature", "epot": "Potential"}
u.trajectory.add_auxiliary(term_dict, "ener.edr")
Adding this data can be useful, for example, to filter trajectory
frames based on non-coordinate data like the potential energy of each
time step. Trajectory slicing allows working on a subset of frames::
selected_frames = np.array([ts.frame for ts in u.trajectory
if ts.aux.epot < some_threshold])
subset = u.trajectory[selected_frames]
See Also
--------
:meth:`remove_auxiliary`
Note
----
Auxiliary data is assumed to be time-ordered, with no duplicates. See
the :ref:`Auxiliary API`.
"""
if auxdata is None:
raise ValueError("No input `auxdata` specified, but it needs "
"to be provided.")
if type(auxdata) not in list(_AUXREADERS.values()):
# i.e. if auxdata is a file, not an instance of an AuxReader
reader_type = get_auxreader_for(auxdata)
auxreader = reader_type(auxdata)
else:
auxreader = auxdata
auxreader.attach_auxiliary(self, aux_spec, format, **kwargs)
def remove_auxiliary(self, auxname):
"""Clear data and close the :class:`~MDAnalysis.auxiliary.base.AuxReader`
for the auxiliary *auxname*.
See Also
--------
:meth:`add_auxiliary`
"""
aux = self._check_for_aux(auxname)
aux.close()
del aux
delattr(self.ts.aux, auxname)
@property
def aux_list(self):
""" Lists the names of added auxiliary data. """
return self._auxs.keys()
def _check_for_aux(self, auxname):
""" Check for the existance of an auxiliary *auxname*. If present,
return the AuxReader; if not, raise ValueError
"""
if auxname in self.aux_list:
return self._auxs[auxname]
else:
raise ValueError("No auxiliary named {name}".format(name=auxname))
def next_as_aux(self, auxname):
""" Move to the next timestep for which there is at least one step from
the auxiliary *auxname* within the cutoff specified in *auxname*.
This allows progression through the trajectory without encountering
``NaN`` representative values (unless these are specifically part of the
auxiliary data).
If the auxiliary cutoff is not set, where auxiliary steps are less frequent
(``auxiliary.dt > trajectory.dt``), this allows progression at the
auxiliary pace (rounded to nearest timestep); while if the auxiliary
steps are more frequent, this will work the same as calling
:meth:`next()`.
See the :ref:`Auxiliary API`.
See Also
--------
:meth:`iter_as_aux`
"""
aux = self._check_for_aux(auxname)
ts = self.ts
# catch up auxiliary if it starts earlier than trajectory
while aux.step_to_frame(aux.step + 1, ts) is None:
next(aux)
# find the next frame that'll have a representative value
next_frame = aux.next_nonempty_frame(ts)
if next_frame is None:
# no more frames with corresponding auxiliary values; stop iteration
raise StopIteration
# some readers set self._frame to -1, rather than self.frame, on
# _reopen; catch here or doesn't read first frame
while self.frame != next_frame or getattr(self, '_frame', 0) == -1:
# iterate trajectory until frame is reached
ts = self.next()
return ts
def iter_as_aux(self, auxname):
"""Iterate through timesteps for which there is at least one assigned
step from the auxiliary *auxname* within the cutoff specified in *auxname*.
See Also
--------
:meth:`next_as_aux`
:meth:`iter_auxiliary`
"""
aux = self._check_for_aux(auxname)
self._reopen()
aux._restart()
while True:
try:
yield self.next_as_aux(auxname)
except StopIteration:
return
def iter_auxiliary(self, auxname, start=None, stop=None, step=None,
selected=None):
""" Iterate through the auxiliary *auxname* independently of the trajectory.
Will iterate over the specified steps of the auxiliary (defaults to all
steps). Allows to access all values in an auxiliary, including those out
of the time range of the trajectory, without having to also iterate
through the trajectory.
After interation, the auxiliary will be repositioned at the current step.
Parameters
----------
auxname : str
Name of the auxiliary to iterate over.
(start, stop, step) : optional
Options for iterating over a slice of the auxiliary.
selected : lst | ndarray, optional
List of steps to iterate over.
Yields
------
:class:`~MDAnalysis.auxiliary.base.AuxStep` object
See Also
--------
:meth:`iter_as_aux`
"""
aux = self._check_for_aux(auxname)
if selected is not None:
selection = selected
else:
selection = slice(start, stop, step)
for i in aux[selection]:
yield i
aux.read_ts(self.ts)
def get_aux_attribute(self, auxname, attrname):
"""Get the value of *attrname* from the auxiliary *auxname*
Parameters
----------
auxname : str
Name of the auxiliary to get value for
attrname : str
Name of gettable attribute in the auxiliary reader
See Also
--------
:meth:`set_aux_attribute`
"""
aux = self._check_for_aux(auxname)
return getattr(aux, attrname)
def set_aux_attribute(self, auxname, attrname, new):
""" Set the value of *attrname* in the auxiliary *auxname*.
Parameters
----------
auxname : str
Name of the auxiliary to alter
attrname : str
Name of settable attribute in the auxiliary reader
new
New value to try set *attrname* to
See Also
--------
:meth:`get_aux_attribute`
:meth:`rename_aux` - to change the *auxname* attribute
"""
aux = self._check_for_aux(auxname)
if attrname == 'auxname':
self.rename_aux(auxname, new)
else:
setattr(aux, attrname, new)
def rename_aux(self, auxname, new):
""" Change the name of the auxiliary *auxname* to *new*.
Provided there is not already an auxiliary named *new*, the auxiliary
name will be changed in ts.aux namespace, the trajectory's
list of added auxiliaries, and in the auxiliary reader itself.
Parameters
----------
auxname : str
Name of the auxiliary to rename
new : str
New name to try set
Raises
------
ValueError
If the name *new* is already in use by an existing auxiliary.
"""
aux = self._check_for_aux(auxname)
if new in self.aux_list:
raise ValueError("Auxiliary data with name {name} already "
"exists".format(name=new))
aux.auxname = new
self._auxs[new] = self._auxs.pop(auxname)
setattr(self.ts.aux, new, self.ts.aux[auxname])
delattr(self.ts.aux, auxname)
def get_aux_descriptions(self, auxnames=None):
"""Get descriptions to allow reloading the specified auxiliaries.
If no auxnames are provided, defaults to the full list of added
auxiliaries.
Passing the resultant description to ``add_auxiliary()`` will allow
recreation of the auxiliary. e.g., to duplicate all auxiliaries into a
second trajectory::
descriptions = trajectory_1.get_aux_descriptions()
for aux in descriptions:
trajectory_2.add_auxiliary(**aux)
Returns
-------
list
List of dictionaries of the args/kwargs describing each auxiliary.
See Also
--------
:meth:`MDAnalysis.auxiliary.base.AuxReader.get_description`
"""
if not auxnames:
auxnames = self.aux_list
descriptions = [self._auxs[aux].get_description() for aux in auxnames]
return descriptions
@property
def transformations(self):
""" Returns the list of transformations"""
return self._transformations
@transformations.setter
def transformations(self, transformations):
if not self._transformations:
self._transformations = transformations
else:
raise ValueError("Transformations are already set")
def add_transformations(self, *transformations):
"""Add all transformations to be applied to the trajectory.
This function take as list of transformations as an argument. These
transformations are functions that will be called by the Reader and given
a :class:`Timestep` object as argument, which will be transformed and returned
to the Reader.
The transformations can be part of the :mod:`~MDAnalysis.transformations`
module, or created by the user, and are stored as a list `transformations`.
This list can only be modified once, and further calls of this function will
raise an exception.
.. code-block:: python
u = MDAnalysis.Universe(topology, coordinates)
workflow = [some_transform, another_transform, this_transform]
u.trajectory.add_transformations(*workflow)
The transformations are applied in the order given in the list
`transformations`, i.e., the first transformation is the first
or innermost one to be applied to the :class:`Timestep`. The
example above would be equivalent to
.. code-block:: python
for ts in u.trajectory:
ts = this_transform(another_transform(some_transform(ts)))
Parameters
----------
transform_list : list
list of all the transformations that will be applied to the coordinates
in the order given in the list
See Also
--------
:mod:`MDAnalysis.transformations`
"""
try:
self.transformations = transformations
except ValueError:
errmsg = ("Can't add transformations again. Please create a new "
"Universe object")
raise ValueError(errmsg) from None
else:
self.ts = self._apply_transformations(self.ts)
# call reader here to apply the newly added transformation on the
# current loaded frame?
def _apply_transformations(self, ts):
"""Applies all the transformations given by the user """
for transform in self.transformations:
ts = transform(ts)
return ts
class ReaderBase(ProtoReader):
"""Base class for trajectory readers that extends :class:`ProtoReader` with a
:meth:`__del__` method.
New Readers should subclass :class:`ReaderBase` and properly implement a
:meth:`close` method, to ensure proper release of resources (mainly file
handles). Readers that are inherently safe in this regard should subclass
:class:`ProtoReader` instead.
See the :ref:`Trajectory API` definition in for the required attributes and
methods.
See Also
--------
:class:`ProtoReader`
.. versionchanged:: 0.11.0
Most of the base Reader class definitions were offloaded to
:class:`ProtoReader` so as to allow the subclassing of ReaderBases without a
:meth:`__del__` method. Created init method to create common
functionality, all ReaderBase subclasses must now :func:`super` through this
class. Added attribute :attr:`_ts_kwargs`, which is created in init.
Provides kwargs to be passed to :class:`Timestep`
.. versionchanged:: 1.0
Removed deprecated flags functionality, use convert_units kwarg instead
"""
@store_init_arguments
def __init__(self, filename, convert_units=True, **kwargs):
super(ReaderBase, self).__init__()
if isinstance(filename, NamedStream):
self.filename = filename
else:
self.filename = str(filename)
self.convert_units = convert_units
ts_kwargs = {}
for att in ('dt', 'time_offset'):
try:
val = kwargs[att]
except KeyError:
pass
else:
ts_kwargs[att] = val
self._ts_kwargs = ts_kwargs
def copy(self):
"""Return independent copy of this Reader.
New Reader will have its own file handle and can seek/iterate
independently of the original.
Will also copy the current state of the Timestep held in the original
Reader.
.. versionchanged:: 2.2.0
Arguments used to construct the reader are correctly captured and
passed to the creation of the new class. Previously the only
``n_atoms`` was passed to class copies, leading to a class created
with default parameters which may differ from the original class.
"""
new = self.__class__(**self._kwargs)
if self.transformations:
new.add_transformations(*self.transformations)
# seek the new reader to the same frame we started with
new[self.ts.frame]
# then copy over the current Timestep in case it has
# been modified since initial load
new.ts = self.ts.copy()
for auxname, auxread in self._auxs.items():
new.add_auxiliary(auxname, auxread.copy())
return new
def __del__(self):
for aux in self.aux_list:
self._auxs[aux].close()
self.close()
class _Writermeta(type):
# Auto register this format upon class creation
def __init__(cls, name, bases, classdict):
type.__init__(type, name, bases, classdict)
try:
# grab the string which describes this format
# could be either 'PDB' or ['PDB', 'ENT'] for multiple formats
fmt = asiterable(classdict['format'])
except KeyError:
# not required however
pass
else:
# does the Writer support single and multiframe writing?
single = classdict.get('singleframe', True)
multi = classdict.get('multiframe', False)
if single:
for f in fmt:
f = f.upper()
_SINGLEFRAME_WRITERS[f] = cls
if multi:
for f in fmt:
f = f.upper()
_MULTIFRAME_WRITERS[f] = cls
class WriterBase(IOBase, metaclass=_Writermeta):
"""Base class for trajectory writers.
See :ref:`Trajectory API` definition in for the required attributes and
methods.
.. versionchanged:: 2.0.0
Deprecated :func:`write_next_timestep` has now been removed, please use
:func:`write` instead.
"""
def convert_dimensions_to_unitcell(self, ts, inplace=True):
"""Read dimensions from timestep *ts* and return appropriate unitcell.
The default is to return ``[A,B,C,alpha,beta,gamma]``; if this
is not appropriate then this method has to be overriden.
"""
# override if the native trajectory format does NOT use
# [A,B,C,alpha,beta,gamma]
if ts.dimensions is None:
lengths, angles = np.zeros(3), np.zeros(3)
else:
lengths, angles = ts.dimensions[:3], ts.dimensions[3:]
if not inplace:
lengths = lengths.copy()
lengths = self.convert_pos_to_native(lengths)
return np.concatenate([lengths, angles])
def write(self, obj):
"""Write current timestep, using the supplied `obj`.
Parameters
----------
obj : :class:`~MDAnalysis.core.groups.AtomGroup` or :class:`~MDAnalysis.core.universe.Universe`
write coordinate information associate with `obj`
Note
----
The size of the `obj` must be the same as the number of atoms provided
when setting up the trajectory.
.. versionchanged:: 2.0.0
Deprecated support for Timestep argument to write has now been
removed. Use AtomGroup or Universe as an input instead.
"""
return self._write_next_frame(obj)
def __del__(self):
self.close()
def __repr__(self):
try:
return "< {0!s} {1!r} for {2:d} atoms >".format(self.__class__.__name__, self.filename, self.n_atoms)
except (TypeError, AttributeError):
# no trajectory loaded yet or a Writer that does not need e.g.
# self.n_atoms
return "< {0!s} {1!r} >".format(self.__class__.__name__, self.filename)
def has_valid_coordinates(self, criteria, x):
"""Returns ``True`` if all values are within limit values of their formats.
Due to rounding, the test is asymmetric (and *min* is supposed to be negative)::
min < x <= max
Parameters
----------
criteria : dict
dictionary containing the *max* and *min* values in native units
x : numpy.ndarray
``(x, y, z)`` coordinates of atoms selected to be written out
Returns
-------
bool
"""
x = np.ravel(x)
return np.all(criteria["min"] < x) and np.all(x <= criteria["max"])
class SingleFrameReaderBase(ProtoReader):
"""Base class for Readers that only have one frame.
To use this base class, define the method :meth:`_read_first_frame` to
read from file `self.filename`. This should populate the attribute
`self.ts` with a :class:`Timestep` object.
.. versionadded:: 0.10.0
.. versionchanged:: 0.11.0
Added attribute "_ts_kwargs" for subclasses
Keywords "dt" and "time_offset" read into _ts_kwargs
.. versionchanged:: 2.2.0
Calling `__iter__` now rewinds the reader before yielding a
:class:`Timestep` object (fixing behavior that was not
well defined previously).
.. versionchanged:: 2.10.0
Fixed a typo in the attribute assignment (`self.atom` → `self.atoms`),
which may affect subclasses relying on this value.
"""
_err = "{0} only contains a single frame"
@store_init_arguments
def __init__(self, filename, convert_units=True, n_atoms=None, **kwargs):
super(SingleFrameReaderBase, self).__init__()
self.filename = filename
self.convert_units = convert_units
self.n_frames = 1
self.n_atoms = n_atoms
ts_kwargs = {}
for att in ('dt', 'time_offset'):
try:
val = kwargs[att]
except KeyError:
pass
else:
ts_kwargs[att] = val
self._ts_kwargs = ts_kwargs
self._read_first_frame()
def copy(self):
"""Return independent copy of this Reader.
New Reader will have its own file handle and can seek/iterate
independently of the original.
Will also copy the current state of the Timestep held in the original
Reader.
.. versionchanged:: 2.2.0
Arguments used to construct the reader are correctly captured and
passed to the creation of the new class. Previously the only
``n_atoms`` was passed to class copies, leading to a class created
with default parameters which may differ from the original class.
"""
new = self.__class__(**self._kwargs)
new.ts = self.ts.copy()
for auxname, auxread in self._auxs.items():
new.add_auxiliary(auxname, auxread.copy())
# since the transformations have already been applied to the frame
# simply copy the property
new.transformations = self.transformations
return new
def _read_first_frame(self): # pragma: no cover
# Override this in subclasses to create and fill a Timestep
pass
def rewind(self):
self._read_first_frame()
for auxname, auxread in self._auxs.items():
self.ts = auxread.update_ts(self.ts)
super(SingleFrameReaderBase, self)._apply_transformations(self.ts)
def _reopen(self):
pass
def next(self):
raise StopIteration(self._err.format(self.__class__.__name__))
def _read_next_timestep(self, ts=None):
raise NotImplementedError(self._err.format(self.__class__.__name__))
def __iter__(self):
self.rewind()
yield self.ts
return
def _read_frame(self, frame):
if frame != 0:
raise IndexError(self._err.format(self.__class__.__name__))
return self.ts
def close(self):
# all single frame readers should use context managers to access
# self.filename. Explicitly setting it to the null action in case
# the IOBase.close method is ever changed from that.
pass
def add_transformations(self, *transformations):
""" Add all transformations to be applied to the trajectory.
This function take as list of transformations as an argument. These
transformations are functions that will be called by the Reader and given
a :class:`Timestep` object as argument, which will be transformed and returned
to the Reader.
The transformations can be part of the :mod:`~MDAnalysis.transformations`
module, or created by the user, and are stored as a list `transformations`.
This list can only be modified once, and further calls of this function will
raise an exception.
.. code-block:: python
u = MDAnalysis.Universe(topology, coordinates)
workflow = [some_transform, another_transform, this_transform]
u.trajectory.add_transformations(*workflow)
Parameters
----------
transform_list : list
list of all the transformations that will be applied to the coordinates
See Also
--------
:mod:`MDAnalysis.transformations`
"""
#Overrides :meth:`~MDAnalysis.coordinates.base.ProtoReader.add_transformations`
#to avoid unintended behaviour where the coordinates of each frame are transformed
#multiple times when iterating over the trajectory.
#In this method, the trajectory is modified all at once and once only.
super(SingleFrameReaderBase, self).add_transformations(*transformations)
for transform in self.transformations:
self.ts = transform(self.ts)
def _apply_transformations(self, ts):
""" Applies the transformations to the timestep."""
# Overrides :meth:`~MDAnalysis.coordinates.base.ProtoReader.add_transformations`
# to avoid applying the same transformations multiple times on each frame
return ts
def range_length(start, stop, step):
if (step > 0 and start < stop):
# We go from a lesser number to a larger one.
return int(1 + (stop - 1 - start) // step)
elif (step < 0 and start > stop):
# We count backward from a larger number to a lesser one.
return int(1 + (start - 1 - stop) // (-step))
else:
# The range is empty.
return 0
# Verbatim copy of code from converters/base.py
# Needed to avoid circular imports before removal in
# MDAnalysis 3.0.0
# Remove in 3.0.0
class _Convertermeta(type):
# Auto register upon class creation
def __init__(cls, name, bases, classdict):
type.__init__(type, name, bases, classdict)
try:
fmt = asiterable(classdict['lib'])
except KeyError:
pass
else:
for f in fmt:
f = f.upper()
_CONVERTERS[f] = cls
# Verbatim copy of code from converters/base.py
# Needed to avoid circular imports before removal in
# MDAnalysis 3.0.0
# Remove in 3.0.0
class ConverterBase(IOBase, metaclass=_Convertermeta):
"""Base class for converting to other libraries.
.. deprecated:: 2.7.0
This class has been moved to
:class:`MDAnalysis.converters.base.ConverterBase` and will be removed
from :mod:`MDAnalysis.coordinates.base` in 3.0.0.
"""
def __init_subclass__(cls):
wmsg = ("ConverterBase moved from coordinates.base."
"ConverterBase to converters.base.ConverterBase "
"and will be removed from coordinates.base "
"in MDAnalysis release 3.0.0")
warnings.warn(wmsg, DeprecationWarning, stacklevel=2)
def __repr__(self):
return "<{cls}>".format(cls=self.__class__.__name__)
def convert(self, obj):
raise NotImplementedError
class StreamReaderBase(ReaderBase):
"""Base class for readers that read a continuous stream of data.
This class is designed for readers that process continuous data streams,
such as live feeds from simulations. Unlike traditional trajectory readers
that can randomly access frames, streaming readers have fundamental constraints:
- **No random access**: Cannot seek to arbitrary frames (no ``traj[5]``)
- **Forward-only**: Can only iterate sequentially through frames
- **No length**: Total number of frames is unknown until stream ends
- **No rewinding**: Cannot restart or rewind the stream
- **No copying**: Cannot create independent copies of the reader
- **No reopening**: Cannot restart iteration once stream is consumed
- **No timeseries**: Cannot use ``timeseries()`` or bulk data extraction
- **No writers**: Cannot create ``Writer()`` or ``OtherWriter()`` instances
- **No pickling**: Cannot serialize reader instances (limits multiprocessing)
- **No StreamWriterBase**: No complementary Writer class available for streaming data
The reader raises :exc:`RuntimeError` for operations that require random
access or rewinding, including ``rewind()``, ``copy()``, ``timeseries()``,
``Writer()``, ``OtherWriter()``, and ``len()``. Only slice notation is supported for iteration.
Parameters
----------
filename : str or file-like
Source of the streaming data
convert_units : bool, optional
Whether to convert units from native to MDAnalysis units (default: True)
**kwargs
Additional keyword arguments passed to the parent ReaderBase
See Also
--------
StreamFrameIteratorSliced : Iterator for stepped streaming access
ReaderBase : Base class for standard trajectory readers
.. versionadded:: 2.10.0
"""
def __init__(self, filename, convert_units=True, **kwargs):
super(StreamReaderBase, self).__init__(
filename, convert_units=convert_units, **kwargs
)
self._init_scope = True
self._reopen_called = False
self._first_ts = None
self._frame = -1
def _read_next_timestep(self):
# No rewinding- to both load the first frame after __init__
# and access it again during iteration, we need to store first ts in mem
if not self._init_scope and self._frame == -1:
self._frame += 1
# can't simply return the same ts again- transformations would be applied twice
# instead, return the pre-transformed copy
return self._first_ts
ts = self._read_frame(self._frame + 1)
if self._init_scope:
self._first_ts = self.ts.copy()
self._init_scope = False
return ts
@property
def n_frames(self):
"""Changes as stream is processed unlike other readers"""
raise RuntimeError(
"{}: n_frames is unknown".format(self.__class__.__name__)
)
def __len__(self):
raise RuntimeError(
"{} has unknown length".format(self.__class__.__name__)
)
def next(self):
"""Advance to the next timestep in the streaming trajectory.
Streaming readers process frames sequentially and cannot rewind
once iteration completes. Use ``for ts in trajectory`` for iteration.
Returns
-------
Timestep
The next timestep in the stream
Raises
------
StopIteration
When the stream ends or no more frames are available
"""
try:
ts = self._read_next_timestep()
except (EOFError, IOError):
# Don't rewind here like we normally would
raise StopIteration from None
else:
for auxname, reader in self._auxs.items():
ts = self._auxs[auxname].update_ts(ts)
ts = self._apply_transformations(ts)
return ts
def rewind(self):
"""Rewinding is not supported for streaming trajectories.
Streaming readers process data continuously from streams
and cannot restart or go backward in the stream once consumed.
Raises
------
RuntimeError
Always raised, as rewinding is not supported for streaming trajectories
"""
raise RuntimeError(
"{}: Stream-based readers can't be rewound".format(
self.__class__.__name__
)
)
# Incompatible methods
def copy(self):
"""Reader copying is not supported for streaming trajectories.
Streaming readers maintain internal state and connection resources
that cannot be duplicated. Each stream connection is unique and
cannot be copied.
Raises
------
RuntimeError
Always raised, as copying is not supported for streaming trajectories
"""
raise RuntimeError(
"{} does not support copying".format(self.__class__.__name__)
)
def _reopen(self):
"""Prepare stream for iteration - can only be called once.
Streaming readers cannot be reopened once iteration begins.
This method is called internally during iteration setup and
will raise an error if called multiple times.
Raises
------
RuntimeError
If the stream has already been opened for iteration
"""
if self._reopen_called:
raise RuntimeError(
"{}: Cannot reopen stream".format(self.__class__.__name__)
)
self._frame = -1
self._reopen_called = True
def timeseries(self, **kwargs):
"""Timeseries extraction is not supported for streaming trajectories.
Streaming readers cannot randomly access frames or store bulk coordinate
data in memory, which ``timeseries()`` requires. Use sequential frame
iteration instead.
Parameters
----------
**kwargs
Any keyword arguments (ignored, as method is not supported)
Raises
------
RuntimeError
Always raised, as timeseries extraction is not supported for
streaming trajectories
"""
raise RuntimeError(
"{}: cannot access timeseries for streamed trajectories".format(self.__class__.__name__)
)
def __getitem__(self, frame):
"""Return an iterator for slicing a streaming trajectory.
Parameters
----------
frame : slice
Slice object. Only the step parameter is meaningful for streams.
Returns
-------
FrameIteratorAll or StreamFrameIteratorSliced
Iterator for the requested slice.
Raises
------
TypeError
If frame is not a slice object.
ValueError
If slice contains start or stop values.
Examples
--------
>>> for ts in traj[:]: # All frames sequentially
... process(ts)
>>> for ts in traj[::5]: # Every 5th frame
... process(ts)
See Also
--------
StreamFrameIteratorSliced
"""
if isinstance(frame, slice):
_, _, step = self.check_slice_indices(
frame.start, frame.stop, frame.step
)
if step is None:
return FrameIteratorAll(self)
else:
return StreamFrameIteratorSliced(self, step)
else:
raise TypeError(
"Streamed trajectories must be an indexed using a slice"
)
def check_slice_indices(self, start, stop, step):
"""Check and validate slice indices for streaming trajectories.
Streaming trajectories have fundamental constraints that differ from
traditional trajectory files:
* **No start/stop indices**: Since streams process data continuously
without knowing the total length, ``start`` and ``stop`` must be ``None``
* **Step-only slicing**: Only the ``step`` parameter is meaningful,
controlling how many frames to skip during iteration
* **Forward-only**: ``step`` must be positive (> 0) as streams cannot
be processed backward in time
Parameters
----------
start : int or None
Starting frame index. Must be ``None`` for streaming readers.
stop : int or None
Ending frame index. Must be ``None`` for streaming readers.
step : int or None
Step size for iteration. Must be positive integer or ``None``
(equivalent to 1).
Returns
-------
tuple
(start, stop, step) with validated values
Raises
------
ValueError
If ``start`` or ``stop`` are not ``None``, or if ``step`` is
not a positive integer.
Examples
--------
Valid streaming slices::
traj[:] # All frames (step=None, equivalent to step=1)
traj[::2] # Every 2nd frame
traj[::10] # Every 10th frame
Invalid streaming slices::
traj[5:] # Cannot specify start index
traj[:100] # Cannot specify stop index
traj[5:100:2] # Cannot specify start or stop indices
traj[::-1] # Cannot go backwards (negative step)
See Also
--------
__getitem__
StreamFrameIteratorSliced
.. versionadded:: 2.10.0
"""
if start is not None:
raise ValueError(
"{}: Cannot expect a start index from a stream, 'start' must be None".format(
self.__class__.__name__
)
)
if stop is not None:
raise ValueError(
"{}: Cannot expect a stop index from a stream, 'stop' must be None".format(
self.__class__.__name__
)
)
if step is not None:
if isinstance(step, numbers.Integral):
if step < 1:
raise ValueError(
"{}: Cannot go backwards in a stream, 'step' must be > 0".format(
self.__class__.__name__
)
)
else:
raise ValueError(
"{}: 'step' must be an integer".format(
self.__class__.__name__
)
)
return start, stop, step
def Writer(self, filename, **kwargs):
"""Writer creation is not supported for streaming trajectories.
Writer creation requires trajectory metadata that streaming readers
cannot provide due to their sequential processing nature.
Parameters
----------
filename : str
Output filename (ignored, as method is not supported)
**kwargs
Additional keyword arguments (ignored, as method is not supported)
Raises
------
RuntimeError
Always raised, as writer creation is not supported for streaming trajectories
"""
raise RuntimeError(
"{}: cannot create Writer for streamed trajectories".format(
self.__class__.__name__
)
)
def OtherWriter(self, filename, **kwargs):
"""Writer creation is not supported for streaming trajectories.
OtherWriter initialization requires frame-based parameters and trajectory
indexing information. Streaming readers process data sequentially
without meaningful frame indexing, making writer setup impossible.
Parameters
----------
filename : str
Output filename (ignored, as method is not supported)
**kwargs
Additional keyword arguments (ignored, as method is not supported)
Raises
------
RuntimeError
Always raised, as writer creation is not supported for streaming trajectories
"""
raise RuntimeError(
"{}: cannot create OtherWriter for streamed trajectories".format(
self.__class__.__name__
)
)
def __getstate__(self):
raise NotImplementedError(
"{} does not support pickling".format(self.__class__.__name__)
)
def __setstate__(self, state: object):
raise NotImplementedError(
"{} does not support pickling".format(self.__class__.__name__)
)
def __repr__(self):
return (
"<{cls} {fname} with continuous stream of {natoms} atoms>"
"".format(
cls=self.__class__.__name__,
fname=self.filename,
natoms=self.n_atoms,
)
)
class StreamFrameIteratorSliced(FrameIteratorBase):
"""Iterator for sliced frames in a streamed trajectory.
Created when slicing a streaming trajectory with a step parameter
(e.g., ``trajectory[::n]``). Reads every nth frame from the continuous
stream, discarding intermediate frames for performance.
This differs from iterating over all frames (``trajectory[:]``) which uses
:class:`FrameIteratorAll` and processes every frame sequentially without
skipping.
Streaming constraints apply to the sliced iterator:
- Frames cannot be accessed randomly (no indexing support)
- The total number of frames is unknown until streaming ends
- Rewinding or restarting iteration is not possible
- Only forward iteration with a fixed step size is supported
Parameters
----------
trajectory : StreamReaderBase
The streaming trajectory reader to iterate over. Must be a
stream-based reader that supports continuous data reading.
step : int
Step size for iteration. Must be a positive integer. A step
of 1 reads every frame, step of 2 reads every other frame, etc.
See Also
--------
StreamReaderBase
FrameIteratorBase
.. versionadded:: 2.10.0
"""
def __init__(self, trajectory, step):
super().__init__(trajectory)
self._step = step
def __iter__(self):
# Calling reopen tells reader
# it can't be reopened again
self.trajectory._reopen()
return self
def __next__(self):
try:
# Burn the timesteps until we reach the desired step
# Don't use next() to avoid unnecessary transformations
while (self.trajectory._frame + 1) % self._step != 0:
self.trajectory._read_next_timestep()
except (EOFError, IOError):
# Don't rewind here like we normally would
raise StopIteration from None
return self.trajectory.next()
def __len__(self):
raise RuntimeError(
"{} has unknown length".format(self.__class__.__name__)
)
def __getitem__(self, frame):
raise RuntimeError("Sliced iterator does not support indexing")
@property
def step(self):
"""The step size for sliced frame iteration.
Returns the step interval used when iterating through frames in a
streaming trajectory. For example, a step of 2 means every second
frame is processed, while a step of 1 processes every frame.
Returns
-------
int
Step size for iteration. Always a positive integer greater than 0.
"""
return self._step
|