/
util.py
2331 lines (1893 loc) · 75.1 KB
/
util.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
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
# -*- 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 GNU Public Licence, v2 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
#
"""
Helper functions --- :mod:`MDAnalysis.lib.util`
====================================================
Small helper functions that don't fit anywhere else.
.. versionchanged:: 0.11.0
Moved mathematical functions into lib.mdamath
Files and directories
---------------------
.. autofunction:: filename
.. autofunction:: openany
.. autofunction:: anyopen
.. autofunction:: greedy_splitext
.. autofunction:: which
.. autofunction:: realpath
.. autofunction:: get_ext
.. autofunction:: check_compressed_format
.. autofunction:: format_from_filename_extension
.. autofunction:: guess_format
Streams
-------
Many of the readers are not restricted to just reading files. They can
also use gzip-compressed or bzip2-compressed files (through the
internal use of :func:`openany`). It is also possible to provide more
general streams as inputs, such as a :func:`cStringIO.StringIO`
instances (essentially, a memory buffer) by wrapping these instances
into a :class:`NamedStream`. This :class:`NamedStream` can then be
used in place of an ordinary file name (typically, with a
class:`~MDAnalysis.core.universe.Universe` but it is also possible to
*write* to such a stream using :func:`MDAnalysis.Writer`).
.. rubric: Examples
In the following example, we use a PDB stored as a string ``pdb_s``::
import MDAnalysis
from MDAnalysis.lib.util import NamedStream
import cStringIO
pdb_s = "TITLE Lonely Ion\\nATOM 1 NA NA+ 1 81.260 64.982 10.926 1.00 0.00\\n"
u = MDAnalysis.Universe(NamedStream(cStringIO.StringIO(pdb_s), "ion.pdb"))
print(u)
# <Universe with 1 atoms>
print(u.atoms.positions)
# [[ 81.26000214 64.98200226 10.92599964]]
It is important to provide a proper pseudo file name with the correct extension
(".pdb") to :class:`NamedStream` because the file type recognition uses the
extension of the file name to determine the file format or alternatively
provide the ``format="pdb"`` keyword argument to the
:class:`~MDAnalysis.core.universe.Universe`.
The use of streams becomes more interesting when MDAnalysis is used as glue
between different analysis packages and when one can arrange things so that
intermediate frames (typically in the PDB format) are not written to disk but
remain in memory via e.g. :mod:`cStringIO` buffers.
.. The following does *not* work because most readers need to
.. reopen files, which is not possible with http streams. Might
.. need to implement a buffer.
..
.. Read a test LAMMPS data file from the MDAnalysis repository::
..
.. import MDAnalysis
.. from MDAnalysis.lib.util import NamedStream
.. import urllib2
.. URI = "https://mdanalysis.googlecode.com/git-history/develop/testsuite/MDAnalysisTests/data/mini.data"
.. urldata = NamedStream(urllib2.urlopen(URI), "mini.data")
.. u = MDAnalysis.Universe(urldata)
.. Note:: A remote connection created by :func:`urllib2.urlopen` is not seekable
and therefore will often not work as an input. But try it...
.. autoclass:: NamedStream
:members:
.. autofunction:: isstream
Containers and lists
--------------------
.. autofunction:: iterable
.. autofunction:: asiterable
.. autofunction:: hasmethod
.. autoclass:: Namespace
Arrays
------
.. autofunction:: unique_int_1d(values)
.. autofunction:: unique_rows
.. autofunction:: blocks_of
File parsing
------------
.. autoclass:: FORTRANReader
:members:
.. autodata:: FORTRAN_format_regex
Data manipulation and handling
------------------------------
.. autofunction:: fixedwidth_bins
.. autofunction:: get_weights
.. autofunction:: ltruncate_int
.. autofunction:: flatten_dict
Strings
-------
.. autofunction:: convert_aa_code
.. autofunction:: parse_residue
.. autofunction:: conv_float
Class decorators
----------------
.. autofunction:: cached
Function decorators
-------------------
.. autofunction:: static_variables
.. autofunction:: warn_if_not_unique
.. autofunction:: check_coords
Code management
---------------
.. autofunction:: deprecate
.. autoclass:: _Deprecate
.. autofunction:: dedent_docstring
Data format checks
------------------
.. autofunction:: check_box
.. Rubric:: Footnotes
.. [#NamedStreamClose] The reason why :meth:`NamedStream.close` does
not close a stream by default (but just rewinds it to the
beginning) is so that one can use the class :class:`NamedStream` as
a drop-in replacement for file names, which are often re-opened
(e.g. when the same file is used as a topology and coordinate file
or when repeatedly iterating through a trajectory in some
implementations). The ``close=True`` keyword can be supplied in
order to make :meth:`NamedStream.close` actually close the
underlying stream and ``NamedStream.close(force=True)`` will also
close it.
"""
from __future__ import division, absolute_import
import six
from six.moves import range, map
import sys
__docformat__ = "restructuredtext en"
import os
import os.path
import errno
from contextlib import contextmanager
import bz2
import gzip
import re
import io
import warnings
import collections
import functools
from functools import wraps
import textwrap
import mmtf
import numpy as np
from numpy.testing import assert_equal
import inspect
from ..exceptions import StreamWarning, DuplicateWarning
from ._cutil import unique_int_1d
# Python 3.0, 3.1 do not have the builtin callable()
try:
callable(list)
except NameError:
# http://bugs.python.org/issue10518
import collections
def callable(obj):
return isinstance(obj, collections.Callable)
try:
from os import PathLike
except ImportError:
class PathLike(object):
pass
def filename(name, ext=None, keep=False):
"""Return a new name that has suffix attached; replaces other extensions.
Parameters
----------
name : str or NamedStream
filename; extension is replaced unless ``keep=True``;
`name` can also be a :class:`NamedStream` (and its
:attr:`NamedStream.name` will be changed accordingly)
ext : None or str
extension to use in the new filename
keep : bool
- ``False``: replace existing extension with `ext`;
- ``True``: keep old extension if one existed
.. versionchanged:: 0.9.0
Also permits :class:`NamedStream` to pass through.
"""
if ext is not None:
if not ext.startswith(os.path.extsep):
ext = os.path.extsep + ext
root, origext = os.path.splitext(name)
if not keep or len(origext) == 0:
newname = root + ext
if isstream(name):
name.name = newname
else:
name = newname
return name if isstream(name) else str(name)
@contextmanager
def openany(datasource, mode='rt', reset=True):
"""Context manager for :func:`anyopen`.
Open the `datasource` and close it when the context of the :keyword:`with`
statement exits.
`datasource` can be a filename or a stream (see :func:`isstream`). A stream
is reset to its start if possible (via :meth:`~io.IOBase.seek` or
:meth:`~cString.StringIO.reset`).
The advantage of this function is that very different input sources
("streams") can be used for a "file", ranging from files on disk (including
compressed files) to open file objects to sockets and strings---as long as
they have a file-like interface.
Parameters
----------
datasource : a file or a stream
mode : {'r', 'w'} (optional)
open in r(ead) or w(rite) mode
reset : bool (optional)
try to read (`mode` 'r') the stream from the start [``True``]
Examples
--------
Open a gzipped file and process it line by line::
with openany("input.pdb.gz") as pdb:
for line in pdb:
if line.startswith('ATOM'):
print(line)
Open a URL and read it::
import urllib2
with openany(urllib2.urlopen("https://www.mdanalysis.org/")) as html:
print(html.read())
See Also
--------
:func:`anyopen`
"""
stream = anyopen(datasource, mode=mode, reset=reset)
try:
yield stream
finally:
stream.close()
# On python 3, we want to use bz2.open to open and uncompress bz2 files. That
# function allows to specify the type of the uncompressed file (bytes ot text).
# The function does not exist in python 2, thus we must use bz2.BZFile to
# which we cannot tell if the uncompressed file contains bytes or text.
# Therefore, on python 2 we use a proxy function that removes the type of the
# uncompressed file from the `mode` argument.
try:
bz2.open
except AttributeError:
# We are on python 2 and bz2.open is not available
def bz2_open(filename, mode):
"""Open and uncompress a BZ2 file"""
mode = mode.replace('t', '').replace('b', '')
return bz2.BZ2File(filename, mode)
else:
# We are on python 3 so we can use bz2.open
bz2_open = bz2.open
def anyopen(datasource, mode='rt', reset=True):
"""Open datasource (gzipped, bzipped, uncompressed) and return a stream.
`datasource` can be a filename or a stream (see :func:`isstream`). By
default, a stream is reset to its start if possible (via
:meth:`~io.IOBase.seek` or :meth:`~cString.StringIO.reset`).
If possible, the attribute ``stream.name`` is set to the filename or
"<stream>" if no filename could be associated with the *datasource*.
Parameters
----------
datasource
a file (from :class:`file` or :func:`open`) or a stream (e.g. from
:func:`urllib2.urlopen` or :class:`cStringIO.StringIO`)
mode: {'r', 'w', 'a'} (optional)
Open in r(ead), w(rite) or a(ppen) mode. More complicated
modes ('r+', 'w+', ...) are not supported; only the first letter of
`mode` is used and thus any additional modifiers are silently ignored.
reset: bool (optional)
try to read (`mode` 'r') the stream from the start
Returns
-------
file-like object
See Also
--------
:func:`openany`
to be used with the :keyword:`with` statement.
.. versionchanged:: 0.9.0
Only returns the ``stream`` and tries to set ``stream.name = filename`` instead of the previous
behavior to return a tuple ``(stream, filename)``.
"""
handlers = {'bz2': bz2_open, 'gz': gzip.open, '': open}
if mode.startswith('r'):
if isstream(datasource):
stream = datasource
try:
filename = str(stream.name) # maybe that does not always work?
except AttributeError:
filename = "<stream>"
if reset:
try:
stream.reset()
except (AttributeError, IOError):
try:
stream.seek(0)
except (AttributeError, IOError):
warnings.warn("Stream {0}: not guaranteed to be at the beginning."
"".format(filename),
category=StreamWarning)
else:
stream = None
filename = datasource
for ext in ('bz2', 'gz', ''): # file == '' should be last
openfunc = handlers[ext]
stream = _get_stream(datasource, openfunc, mode=mode)
if stream is not None:
break
if stream is None:
raise IOError(errno.EIO, "Cannot open file or stream in mode={mode!r}.".format(**vars()), repr(filename))
elif mode.startswith('w') or mode.startswith('a'): # append 'a' not tested...
if isstream(datasource):
stream = datasource
try:
filename = str(stream.name) # maybe that does not always work?
except AttributeError:
filename = "<stream>"
else:
stream = None
filename = datasource
name, ext = os.path.splitext(filename)
if ext.startswith('.'):
ext = ext[1:]
if not ext in ('bz2', 'gz'):
ext = '' # anything else but bz2 or gz is just a normal file
openfunc = handlers[ext]
stream = openfunc(datasource, mode=mode)
if stream is None:
raise IOError(errno.EIO, "Cannot open file or stream in mode={mode!r}.".format(**vars()), repr(filename))
else:
raise NotImplementedError("Sorry, mode={mode!r} is not implemented for {datasource!r}".format(**vars()))
try:
stream.name = filename
except (AttributeError, TypeError):
pass # can't set name (e.g. cStringIO.StringIO)
return stream
def _get_stream(filename, openfunction=open, mode='r'):
"""Return open stream if *filename* can be opened with *openfunction* or else ``None``."""
try:
stream = openfunction(filename, mode=mode)
except (IOError, OSError) as err:
# An exception might be raised due to two reasons, first the openfunction is unable to open the file, in this
# case we have to ignore the error and return None. Second is when openfunction can't open the file because
# either the file isn't there or the permissions don't allow access.
if errno.errorcode[err.errno] in ['ENOENT', 'EACCES']:
six.reraise(*sys.exc_info())
return None
if mode.startswith('r'):
# additional check for reading (eg can we uncompress) --- is this needed?
try:
stream.readline()
except IOError:
stream.close()
stream = None
except:
stream.close()
raise
else:
stream.close()
stream = openfunction(filename, mode=mode)
return stream
def greedy_splitext(p):
"""Split extension in path *p* at the left-most separator.
Extensions are taken to be separated from the filename with the
separator :data:`os.extsep` (as used by :func:`os.path.splitext`).
Arguments
---------
p : str
path
Returns
-------
(root, extension) : tuple
where ``root`` is the full path and filename with all
extensions removed whereas ``extension`` is the string of
all extensions.
Example
-------
>>> greedy_splitext("/home/joe/protein.pdb.bz2")
('/home/joe/protein', '.pdb.bz2')
"""
path, root = os.path.split(p)
extension = ''
while True:
root, ext = os.path.splitext(root)
extension = ext + extension
if not ext:
break
return os.path.join(path, root), extension
def hasmethod(obj, m):
"""Return ``True`` if object *obj* contains the method *m*."""
return hasattr(obj, m) and callable(getattr(obj, m))
def isstream(obj):
"""Detect if `obj` is a stream.
We consider anything a stream that has the methods
- ``close()``
and either set of the following
- ``read()``, ``readline()``, ``readlines()``
- ``write()``, ``writeline()``, ``writelines()``
Parameters
----------
obj : stream or str
Returns
-------
bool
``True`` if `obj` is a stream, ``False`` otherwise
See Also
--------
:mod:`io`
.. versionadded:: 0.9.0
"""
signature_methods = ("close",)
alternative_methods = (
("read", "readline", "readlines"),
("write", "writeline", "writelines"))
# Must have ALL the signature methods
for m in signature_methods:
if not hasmethod(obj, m):
return False
# Must have at least one complete set of alternative_methods
alternative_results = [
np.all([hasmethod(obj, m) for m in alternatives])
for alternatives in alternative_methods]
return np.any(alternative_results)
def which(program):
"""Determine full path of executable `program` on :envvar:`PATH`.
(Jay at http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python)
Parameters
----------
programe : str
name of the executable
Returns
-------
path : str or None
absolute path to the executable if it can be found, else ``None``
"""
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
fpath, fname = os.path.split(program)
if fpath:
real_program = realpath(program)
if is_exe(real_program):
return real_program
else:
for path in os.environ["PATH"].split(os.pathsep):
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
@functools.total_ordering
class NamedStream(io.IOBase, PathLike):
"""Stream that also provides a (fake) name.
By wrapping a stream `stream` in this class, it can be passed to
code that uses inspection of the filename to make decisions. For
instance. :func:`os.path.split` will work correctly on a
:class:`NamedStream`.
The class can be used as a context manager.
:class:`NamedStream` is derived from :class:`io.IOBase` (to indicate that
it is a stream). Many operations that normally expect a string will also
work with a :class:`NamedStream`; for instance, most of the functions in
:mod:`os.path` will work with the exception of :func:`os.path.expandvars`
and :func:`os.path.expanduser`, which will return the :class:`NamedStream`
itself instead of a string if no substitutions were made.
Example
-------
Wrap a :func:`cStringIO.StringIO` instance to write to::
import cStringIO
import os.path
stream = cStringIO.StringIO()
f = NamedStream(stream, "output.pdb")
print(os.path.splitext(f))
Wrap a :class:`file` instance to read from::
stream = open("input.pdb")
f = NamedStream(stream, stream.name)
Use as a context manager (closes stream automatically when the
:keyword:`with` block is left)::
with NamedStream(open("input.pdb"), "input.pdb") as f:
# use f
print f.closed # --> False
# ...
print f.closed # --> True
Note
----
This class uses its own :meth:`__getitem__` method so if `stream`
implements :meth:`stream.__getitem__` then that will be masked and
this class should not be used.
Warning
-------
By default, :meth:`NamedStream.close` will **not close the
stream** but instead :meth:`~NamedStream.reset` it to the
beginning. [#NamedStreamClose]_ Provide the ``force=True`` keyword
to :meth:`NamedStream.close` to always close the stream.
"""
def __init__(self, stream, filename, reset=True, close=False):
"""Initialize the :class:`NamedStream` from a `stream` and give it a `name`.
The constructor attempts to rewind the stream to the beginning unless
the keyword `reset` is set to ``False``. If rewinding fails, a
:class:`MDAnalysis.StreamWarning` is issued.
Parameters
----------
stream : stream
an open stream (e.g. :class:`file` or :func:`cStringIO.StringIO`)
filename : str
the filename that should be associated with the stream
reset : bool (optional)
start the stream from the beginning (either :meth:`reset` or :meth:`seek`)
when the class instance is constructed
close : bool (optional)
close the stream when a :keyword:`with` block exits or when
:meth:`close` is called; note that the default is **not to close
the stream**
Notes
-----
By default, this stream will *not* be closed by :keyword:`with` and
:meth:`close` (see there) unless the `close` keyword is set to
``True``.
.. versionadded:: 0.9.0
"""
# constructing the class from an instance of itself has weird behavior
# on __del__ and super on python 3. Let's warn the user and ensure the
# class works normally.
if isinstance(stream, NamedStream):
warnings.warn("Constructed NamedStream from a NamedStream",
RuntimeWarning)
stream = stream.stream
self.stream = stream
self.name = filename
self.close_stream = close
if reset:
self.reset()
def reset(self):
"""Move to the beginning of the stream"""
# try to rewind
try:
self.stream.reset() # e.g. StreamIO
except (AttributeError, IOError):
try:
self.stream.seek(0) # typical file objects
except (AttributeError, IOError):
warnings.warn("NamedStream {0}: not guaranteed to be at the beginning."
"".format(self.name),
category=StreamWarning)
# access the stream
def __getattr__(self, x):
try:
return getattr(self.stream, x)
except AttributeError:
return getattr(self.name, x)
def __iter__(self):
return iter(self.stream)
def __next__(self):
return self.stream.__next__()
def __enter__(self):
# do not call the stream's __enter__ because the stream is already open
return self
def __exit__(self, *args):
# NOTE: By default (close=False) we only reset the stream and NOT close it; this makes
# it easier to use it as a drop-in replacement for a filename that might
# be opened repeatedly (at least in MDAnalysis)
#try:
# return self.stream.__exit__(*args)
#except AttributeError:
# super(NamedStream, self).__exit__(*args)
self.close()
def __fspath__(self):
return self.name
# override more IOBase methods, as these are provided by IOBase and are not
# caught with __getattr__ (ugly...)
def close(self, force=False):
"""Reset or close the stream.
If :attr:`NamedStream.close_stream` is set to ``False`` (the default)
then this method will *not close the stream* and only :meth:`reset` it.
If the *force* = ``True`` keyword is provided, the stream will be
closed.
.. Note:: This ``close()`` method is non-standard. ``del NamedStream``
always closes the underlying stream.
"""
if self.close_stream or force:
try:
return self.stream.close()
except AttributeError:
return super(NamedStream, self).close()
else:
self.flush()
self.reset()
def __del__(self):
"""Always closes the stream."""
self.close(force=True)
@property
def closed(self):
"""``True`` if stream is closed."""
try:
return self.stream.closed
except AttributeError:
return super(NamedStream, self).closed
def seek(self, offset, whence=os.SEEK_SET):
"""Change the stream position to the given byte `offset` .
Parameters
----------
offset : int
`offset` is interpreted relative to the position
indicated by `whence`.
whence : {0, 1, 2} (optional)
Values for `whence` are:
- :data:`io.SEEK_SET` or 0 – start of the stream (the default); `offset`
should be zero or positive
- :data:`io.SEEK_CUR` or 1 – current stream position; `offset` may be
negative
- :data:`io.SEEK_END` or 2 – end of the stream; `offset` is usually
negative
Returns
-------
int
the new absolute position in bytes.
"""
try:
return self.stream.seek(offset, whence) # file.seek: no kw
except AttributeError:
return super(NamedStream, self).seek(offset, whence)
def tell(self):
"""Return the current stream position."""
try:
return self.stream.tell()
except AttributeError:
return super(NamedStream, self).tell()
def truncate(self, *size):
"""Truncate the stream's size to `size`.
Parameters
----------
size : int (optional)
The `size` defaults to the current position (if no `size` argument
is supplied). The current file position is not changed.
"""
try:
return self.stream.truncate(*size)
except AttributeError:
return super(NamedStream, self).truncate(*size)
def seekable(self):
"""Return ``True`` if the stream supports random access.
If ``False``, :meth:`seek`, :meth:`tell` and :meth:`truncate` will
raise :exc:`IOError`.
"""
try:
return self.stream.seekable()
except AttributeError:
return super(NamedStream, self).seekable()
def readable(self):
"""Return ``True`` if the stream can be read from.
If ``False``, :meth:`read` will raise :exc:`IOError`.
"""
try:
return self.stream.readable()
except AttributeError:
return super(NamedStream, self).readable()
def writable(self):
"""Return ``True`` if the stream can be written to.
If ``False``, :meth:`write` will raise :exc:`IOError`.
"""
try:
return self.stream.writable()
except AttributeError:
return super(NamedStream, self).writable()
def flush(self):
"""Flush the write buffers of the stream if applicable.
This does nothing for read-only and non-blocking streams. For file
objects one also needs to call :func:`os.fsync` to write contents to
disk.
"""
try:
return self.stream.flush()
except AttributeError:
return super(NamedStream, self).flush()
def fileno(self):
"""Return the underlying file descriptor (an integer) of the stream if it exists.
An :exc:`IOError` is raised if the IO object does not use a file descriptor.
"""
try:
return self.stream.fileno()
except AttributeError:
# IOBase.fileno does not raise IOError as advertised so we do this here
raise IOError("This NamedStream does not use a file descriptor.")
def readline(self):
try:
return self.stream.readline()
except AttributeError:
return super(NamedStream, self).readline()
# fake the important parts of the string API
# (other methods such as rfind() are automatically dealt with via __getattr__)
def __getitem__(self, x):
return self.name[x]
def __eq__(self, x):
return self.name == x
def __ne__(self, x):
return not self == x
def __lt__(self, x):
return self.name < x
def __len__(self):
return len(self.name)
def __add__(self, x):
return self.name + x
def __radd__(self, x):
return x + self.name
def __mul__(self, x):
return self.name * x
__rmul__ = __mul__
def __format__(self, format_spec):
return self.name.format(format_spec)
def __str__(self):
return self.name
def __repr__(self):
return "<NamedStream({0}, {1})>".format(self.stream, self.name)
def realpath(*args):
"""Join all args and return the real path, rooted at ``/``.
Expands '~', '~user', and environment variables such as :envvar:`$HOME`.
Returns ``None`` if any of the args is ``None``.
"""
if None in args:
return None
return os.path.realpath(os.path.expanduser(os.path.expandvars(os.path.join(*args))))
def get_ext(filename):
"""Return the lower-cased extension of `filename` without a leading dot.
Parameters
----------
filename : str
Returns
-------
root : str
ext : str
"""
root, ext = os.path.splitext(filename)
if ext.startswith(os.extsep):
ext = ext[1:]
return root, ext.lower()
def check_compressed_format(root, ext):
"""Check if this is a supported gzipped/bzip2ed file format and return UPPERCASE format.
Parameters
----------
root : str
path of a file, without extension `ext`
ext : str
extension (currently only "bz2" and "gz" are recognized as compressed formats)
Returns
-------
format : str
upper case format extension *if* the compression can be handled by
:func:`openany`
See Also
--------
openany : function that is used to open and decompress formats on the fly; only
compression formats implemented in :func:`openany` are recognized
"""
# XYZReader&others are setup to handle both plain and compressed (bzip2, gz) files
# ..so if the first file extension is bzip2 or gz, look at the one to the left of it
if ext.lower() in ("bz2", "gz"):
try:
root, ext = get_ext(root)
except:
raise TypeError("Cannot determine coordinate format for '{0}.{1}'"
"".format(root, ext))
return ext.upper()
def format_from_filename_extension(filename):
"""Guess file format from the file extension.
Parameters
----------
filename : str
Returns
-------
format : str
Raises
------
TypeError
if the file format cannot be determined
"""
try:
root, ext = get_ext(filename)
except:
raise TypeError(
"Cannot determine file format for file '{0}'.\n"
" You can set the format explicitly with "
"'Universe(..., format=FORMAT)'.".format(filename))
format = check_compressed_format(root, ext)
return format
def guess_format(filename):
"""Return the format of `filename`
The current heuristic simply looks at the filename extension and can work
around compressed format extensions.
Parameters
----------
filename : str or stream
path to the file or a stream, in which case ``filename.name`` is looked