This repository has been archived by the owner on Sep 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 118
/
api.py
2109 lines (1679 loc) Β· 92.3 KB
/
api.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
# This file is part of PyEMMA.
#
# Copyright (c) 2015, 2014 Computational Molecular Biology Group, Freie Universitaet Berlin (GER)
#
# PyEMMA is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
r"""User-API for the pyemma.coordinates package
.. currentmodule:: pyemma.coordinates.api
"""
from pathlib import Path
import numpy as _np
import logging as _logging
from pyemma.util import types as _types
# lift this function to the api
from pyemma.coordinates.util.stat import histogram
from pyemma.util.exceptions import PyEMMA_DeprecationWarning as _PyEMMA_DeprecationWarning
_logger = _logging.getLogger(__name__)
__docformat__ = "restructuredtext en"
__author__ = "Frank Noe, Martin Scherer"
__copyright__ = "Copyright 2015, Computational Molecular Biology Group, FU-Berlin"
__credits__ = ["Benjamin Trendelkamp-Schroer", "Martin Scherer", "Frank Noe"]
__maintainer__ = "Martin Scherer"
__email__ = "m.scherer AT fu-berlin DOT de"
__all__ = ['featurizer', # IO
'load',
'source',
'combine_sources',
'histogram',
'pipeline',
'discretizer',
'save_traj',
'save_trajs',
'pca', # transform
'tica',
'tica_nystroem',
'vamp',
'covariance_lagged',
'cluster_regspace', # cluster
'cluster_kmeans',
'cluster_mini_batch_kmeans',
'cluster_uniform_time',
'assign_to_centers',
]
_string_types = str
# ==============================================================================
#
# DATA PROCESSING
#
# ==============================================================================
def _check_old_chunksize_arg(chunksize, chunk_size_default, **kw):
# cases:
# 1. chunk_size not given, return chunksize
# 2. chunk_size given, chunksize is default, warn, return chunk_size
# 3. chunk_size and chunksize given, warn, return chunksize
chosen_chunk_size = NotImplemented
deprecated_arg_given = 'chunk_size' in kw
is_default = chunksize == chunk_size_default
if not deprecated_arg_given: # case 1.
chosen_chunk_size = chunksize
else:
import warnings
from pyemma.util.annotators import get_culprit
filename, lineno = get_culprit(3)
if is_default: # case 2.
warnings.warn_explicit('Passed deprecated argument "chunk_size", please use "chunksize"',
category=_PyEMMA_DeprecationWarning, filename=filename, lineno=lineno)
chosen_chunk_size = kw.pop('chunk_size') # remove this argument to avoid further passing to other funcs.
else: # case 3.
warnings.warn_explicit('Passed two values for chunk size: "chunk_size" and "chunksize", while the first one'
' is deprecated. Please use "chunksize" in the future.',
category=_PyEMMA_DeprecationWarning, filename=filename, lineno=lineno)
chosen_chunk_size = chunksize
assert chosen_chunk_size is not NotImplemented
return chosen_chunk_size
def featurizer(topfile):
r""" Featurizer to select features from MD data.
Parameters
----------
topfile : str or mdtraj.Topology instance
path to topology file (e.g pdb file) or a mdtraj.Topology object
Returns
-------
feat : :class:`Featurizer <pyemma.coordinates.data.featurization.featurizer.MDFeaturizer>`
Examples
--------
Create a featurizer and add backbone torsion angles to active features.
Then use it in :func:`source`
>>> import pyemma.coordinates # doctest: +SKIP
>>> feat = pyemma.coordinates.featurizer('my_protein.pdb') # doctest: +SKIP
>>> feat.add_backbone_torsions() # doctest: +SKIP
>>> reader = pyemma.coordinates.source(["my_traj01.xtc", "my_traj02.xtc"], features=feat) # doctest: +SKIP
or
>>> traj = mdtraj.load('my_protein.pdb') # # doctest: +SKIP
>>> feat = pyemma.coordinates.featurizer(traj.topology) # doctest: +SKIP
.. autoclass:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.data.featurization.featurizer.MDFeaturizer
:attributes:
"""
from pyemma.coordinates.data.featurization.featurizer import MDFeaturizer
return MDFeaturizer(topfile)
# TODO: DOC - which topology file formats does mdtraj support? Find out and complete docstring
def load(trajfiles, features=None, top=None, stride=1, chunksize=None, **kw):
r""" Loads coordinate features into memory.
If your memory is not big enough consider the use of **pipeline**, or use
the stride option to subsample the data.
Parameters
----------
trajfiles : str, list of str or nested list (one level) of str
A filename or a list of filenames to trajectory files that can be
processed by pyemma. Both molecular dynamics trajectory files and raw
data files (tabulated ASCII or binary) can be loaded.
If a nested list of filenames is given, eg.:
[['traj1_0.xtc', 'traj1_1.xtc'], 'traj2_full.xtc'], ['traj3_0.xtc, ...]]
the grouped fragments will be treated as a joint trajectory.
When molecular dynamics trajectory files are loaded either a featurizer
must be specified (for reading specific quantities such as distances or
dihedrals), or a topology file (in that case only Cartesian coordinates
will be read). In the latter case, the resulting feature vectors will
have length 3N for each trajectory frame, with N being the number of
atoms and (x1, y1, z1, x2, y2, z2, ...) being the sequence of
coordinates in the vector.
Molecular dynamics trajectory files are loaded through mdtraj (http://mdtraj.org/latest/),
and can possess any of the mdtraj-compatible trajectory formats
including:
* CHARMM/NAMD (.dcd)
* Gromacs (.xtc)
* Gromacs (.trr)
* AMBER (.binpos)
* AMBER (.netcdf)
* TINKER (.arc),
* MDTRAJ (.hdf5)
* LAMMPS trajectory format (.lammpstrj)
Raw data can be in the following format:
* tabulated ASCII (.dat, .txt)
* binary python (.npy, .npz)
features : MDFeaturizer, optional, default = None
a featurizer object specifying how molecular dynamics files should
be read (e.g. intramolecular distances, angles, dihedrals, etc).
top : str, mdtraj.Trajectory or mdtraj.Topology, optional, default = None
A molecular topology file, e.g. in PDB (.pdb) format or an already
loaded mdtraj.Topology object. If it is an mdtraj.Trajectory object, the topology
will be extracted from it.
stride : int, optional, default = 1
Load only every stride'th frame. By default, every frame is loaded
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
data : ndarray or list of ndarray
If a single filename was given as an input (and unless the format is
.npz), the return will be a single ndarray of size (T, d), where T is
the number of time steps in the trajectory and d is the number of features
(coordinates, observables). When reading from molecular dynamics data
without a specific featurizer, each feature vector will have size d=3N
and will hold the Cartesian coordinates in the sequence
(x1, y1, z1, x2, y2, z2, ...).
If multiple filenames were given, or if the file is a .npz holding
multiple arrays, the result is a list of appropriately shaped arrays
See also
--------
:func:`pyemma.coordinates.source`
if your memory is not big enough, specify data source and put it into your
transformation or clustering algorithms instead of the loaded data. This
will stream the data and save memory on the cost of longer processing
times.
Examples
--------
>>> from pyemma.coordinates import load
>>> files = ['traj01.xtc', 'traj02.xtc'] # doctest: +SKIP
>>> output = load(files, top='my_structure.pdb') # doctest: +SKIP
"""
from pyemma.coordinates.data.util.reader_utils import create_file_reader
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(load)['chunksize'], **kw)
if isinstance(trajfiles, _string_types) or (
isinstance(trajfiles, (list, tuple))
and (any(isinstance(item, (list, tuple, str)) for item in trajfiles)
or len(trajfiles) == 0)):
reader = create_file_reader(trajfiles, top, features, chunksize=cs, **kw)
trajs = reader.get_output(stride=stride)
if len(trajs) == 1:
return trajs[0]
else:
return trajs
else:
raise ValueError('unsupported type (%s) of input' % type(trajfiles))
def source(inp, features=None, top=None, chunksize=None, **kw):
r""" Defines trajectory data source
This function defines input trajectories without loading them. You can pass
the resulting object into transformers such as :func:`pyemma.coordinates.tica`
or clustering algorithms such as :func:`pyemma.coordinates.cluster_kmeans`.
Then, the data will be streamed instead of being loaded, thus saving memory.
You can also use this function to construct the first stage of a data
processing :func:`pipeline`.
Parameters
----------
inp : str (file name) or ndarray or list of strings (file names) or list of ndarrays or nested list of str|ndarray (1 level)
The inp file names or input data. Can be given in any of
these ways:
1. File name of a single trajectory. It can have any of the molecular
dynamics trajectory formats or raw data formats specified in :py:func:`load`.
2. List of trajectory file names. It can have any of the molecular
dynamics trajectory formats or raw data formats specified in :py:func:`load`.
3. Molecular dynamics trajectory in memory as a numpy array of shape
(T, N, 3) with T time steps, N atoms each having three (x,y,z)
spatial coordinates.
4. List of molecular dynamics trajectories in memory, each given as a
numpy array of shape (T_i, N, 3), where trajectory i has T_i time
steps and all trajectories have shape (N, 3).
5. Trajectory of some features or order parameters in memory
as a numpy array of shape (T, N) with T time steps and N dimensions.
6. List of trajectories of some features or order parameters in memory,
each given as a numpy array of shape (T_i, N), where trajectory i
has T_i time steps and all trajectories have N dimensions.
7. List of NumPy array files (.npy) of shape (T, N). Note these
arrays are not being loaded completely, but mapped into memory
(read-only).
8. List of tabulated ASCII files of shape (T, N).
9. Nested lists (1 level) like), eg.:
[['traj1_0.xtc', 'traj1_1.xtc'], ['traj2_full.xtc'], ['traj3_0.xtc, ...]]
the grouped fragments will be treated as a joint trajectory.
features : MDFeaturizer, optional, default = None
a featurizer object specifying how molecular dynamics files should be
read (e.g. intramolecular distances, angles, dihedrals, etc). This
parameter only makes sense if the input comes in the form of molecular
dynamics trajectories or data, and will otherwise create a warning and
have no effect.
top : str, mdtraj.Trajectory or mdtraj.Topology, optional, default = None
A topology file name. This is needed when molecular dynamics
trajectories are given and no featurizer is given.
In this case, only the Cartesian coordinates will be read. You can also pass an already
loaded mdtraj.Topology object. If it is an mdtraj.Trajectory object, the topology
will be extracted from it.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
reader : :class:`DataSource <pyemma.coordinates.data._base.datasource.DataSource>` object
See also
--------
:func:`pyemma.coordinates.load`
If your memory is big enough to load all features into memory, don't
bother using source - working in memory is faster!
:func:`pyemma.coordinates.pipeline`
The data input is the first stage for your pipeline. Add other stages
to it and build a pipeline to analyze big data in streaming mode.
Examples
--------
Create a reader for NumPy files:
>>> import numpy as np
>>> from pyemma.coordinates import source
>>> reader = source(['001.npy', '002.npy'] # doctest: +SKIP
Create a reader for trajectory files and select some distance as feature:
>>> reader = source(['traj01.xtc', 'traj02.xtc'], top='my_structure.pdb') # doctest: +SKIP
>>> reader.featurizer.add_distances([[0, 1], [5, 6]]) # doctest: +SKIP
>>> calculated_features = reader.get_output() # doctest: +SKIP
create a reader for a csv file:
>>> reader = source('data.csv') # doctest: +SKIP
Create a reader for huge NumPy in-memory arrays to process them in
huge chunks to avoid memory issues:
>>> data = np.random.random(int(1e6))
>>> reader = source(data, chunksize=1000)
>>> from pyemma.coordinates import cluster_regspace
>>> regspace = cluster_regspace(reader, dmin=0.1)
Returns
-------
reader : a reader instance
.. autoclass:: pyemma.coordinates.data.interface.ReaderInterface
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.data.interface.ReaderInterface
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.data.interface.ReaderInterface
:attributes:
"""
from pyemma.coordinates.data._base.iterable import Iterable
from pyemma.coordinates.data.util.reader_utils import create_file_reader
from pyemma.util.reflection import get_default_args
cs = _check_old_chunksize_arg(chunksize, get_default_args(source)['chunksize'], **kw)
# CASE 1: input is a string or list of strings
# check: if single string create a one-element list
if isinstance(inp, _string_types) or (
isinstance(inp, (list, tuple))
and (any(isinstance(item, (list, tuple, _string_types)) for item in inp) or len(inp) == 0)):
reader = create_file_reader(inp, top, features, chunksize=cs, **kw)
elif isinstance(inp, _np.ndarray) or (isinstance(inp, (list, tuple))
and (any(isinstance(item, _np.ndarray) for item in inp) or len(inp) == 0)):
# CASE 2: input is a (T, N, 3) array or list of (T_i, N, 3) arrays
# check: if single array, create a one-element list
# check: do all arrays have compatible dimensions (*, N, 3)? If not: raise ValueError.
# check: if single array, create a one-element list
# check: do all arrays have compatible dimensions (*, N)? If not: raise ValueError.
# create MemoryReader
from pyemma.coordinates.data.data_in_memory import DataInMemory as _DataInMemory
reader = _DataInMemory(inp, chunksize=cs, **kw)
elif isinstance(inp, Iterable):
inp.chunksize = cs
return inp
else:
raise ValueError('unsupported type (%s) of input' % type(inp))
return reader
def combine_sources(sources, chunksize=None):
r""" Combines multiple data sources to stream from.
The given source objects (readers and transformers, eg. TICA) are concatenated in dimension axis during iteration.
This can be used to couple arbitrary features in order to pass them to an Estimator expecting only one source,
which is usually the case. All the parameters for iterator creation are passed to the actual sources, to ensure
consistent behaviour.
Parameters
----------
sources : list, tuple
list of DataSources (Readers, StreamingTransformers etc.) to combine for streaming access.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Notes
-----
This is currently only implemented for matching lengths trajectories.
Returns
-------
merger : :class:`SourcesMerger <pyemma.coordinates.data.sources_merger.SourcesMerger>`
"""
from pyemma.coordinates.data.sources_merger import SourcesMerger
return SourcesMerger(sources, chunk=chunksize)
def pipeline(stages, run=True, stride=1, chunksize=None):
r""" Data analysis pipeline.
Constructs a data analysis :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>` and parametrizes it
(unless prevented).
If this function takes too long, consider loading data in memory.
Alternatively if the data is to large to be loaded into memory make use
of the stride parameter.
Parameters
----------
stages : data input or list of pipeline stages
If given a single pipeline stage this must be a data input constructed
by :py:func:`source`. If a list of pipelining stages are given, the
first stage must be a data input constructed by :py:func:`source`.
run : bool, optional, default = True
If True, the pipeline will be parametrized immediately with the given
stages. If only an input stage is given, the run flag has no effect at
this time. True also means that the pipeline will be immediately
re-parametrized when further stages are added to it.
*Attention* True means this function may take a long time to compute.
If False, the pipeline will be passive, i.e. it will not do any
computations before you call parametrize()
stride : int, optional, default = 1
If set to 1, all input data will be used throughout the pipeline to
parametrize its stages. Note that this could cause the parametrization
step to be very slow for large data sets. Since molecular dynamics data
is usually correlated at short timescales, it is often sufficient to
parametrize the pipeline at a longer stride.
See also stride option in the output functions of the pipeline.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pipe : :class:`Pipeline <pyemma.coordinates.pipelines.Pipeline>`
A pipeline object that is able to conduct big data analysis with
limited memory in streaming mode.
Examples
--------
>>> import numpy as np
>>> from pyemma.coordinates import source, tica, assign_to_centers, pipeline
Create some random data and cluster centers:
>>> data = np.random.random((1000, 3))
>>> centers = data[np.random.choice(1000, 10)]
>>> reader = source(data)
Define a TICA transformation with lag time 10:
>>> tica_obj = tica(lag=10)
Assign any input to given centers:
>>> assign = assign_to_centers(centers=centers)
>>> pipe = pipeline([reader, tica_obj, assign])
>>> pipe.parametrize()
.. autoclass:: pyemma.coordinates.pipelines.Pipeline
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:attributes:
"""
from pyemma.coordinates.pipelines import Pipeline
if not isinstance(stages, list):
stages = [stages]
p = Pipeline(stages, param_stride=stride, chunksize=chunksize)
if run:
p.parametrize()
return p
def discretizer(reader,
transform=None,
cluster=None,
run=True,
stride=1,
chunksize=None):
r""" Specialized pipeline: From trajectories to clustering.
Constructs a pipeline that consists of three stages:
1. an input stage (mandatory)
2. a transformer stage (optional)
3. a clustering stage (mandatory)
This function is identical to calling :func:`pipeline` with the three
stages, it is only meant as a guidance for the (probably) most common
usage cases of a pipeline.
Parameters
----------
reader : instance of :class:`pyemma.coordinates.data.reader.ChunkedReader`
The reader instance provides access to the data. If you are working
with MD data, you most likely want to use a FeatureReader.
transform : instance of :class: `pyemma.coordinates.Transformer`
an optional transform like PCA/TICA etc.
cluster : instance of :class: `pyemma.coordinates.AbstractClustering`
clustering Transformer (optional) a cluster algorithm to assign
transformed data to discrete states.
stride : int, optional, default = 1
If set to 1, all input data will be used throughout the pipeline
to parametrize its stages. Note that this could cause the
parametrization step to be very slow for large data sets. Since
molecular dynamics data is usually correlated at short timescales,
it is often sufficient to parametrize the pipeline at a longer stride.
See also stride option in the output functions of the pipeline.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pipe : a :class:`Pipeline <pyemma.coordinates.pipelines.Discretizer>` object
A pipeline object that is able to streamline data analysis of large
amounts of input data with limited memory in streaming mode.
Examples
--------
Construct a discretizer pipeline processing all data
with a PCA transformation and cluster the principal components
with uniform time clustering:
>>> from pyemma.coordinates import source, pca, cluster_regspace, discretizer
>>> from pyemma.datasets import get_bpti_test_data
>>> from pyemma.util.contexts import settings
>>> reader = source(get_bpti_test_data()['trajs'], top=get_bpti_test_data()['top'])
>>> transform = pca(dim=2)
>>> cluster = cluster_regspace(dmin=0.1)
Create the discretizer, access the the discrete trajectories and save them to files:
>>> with settings(show_progress_bars=False):
... disc = discretizer(reader, transform, cluster)
... disc.dtrajs # doctest: +ELLIPSIS
[array([...
This will store the discrete trajectory to "traj01.dtraj":
>>> from pyemma.util.files import TemporaryDirectory
>>> import os
>>> with TemporaryDirectory('dtrajs') as tmpdir:
... disc.save_dtrajs(output_dir=tmpdir)
... sorted(os.listdir(tmpdir))
['bpti_001-033.dtraj', 'bpti_034-066.dtraj', 'bpti_067-100.dtraj']
.. autoclass:: pyemma.coordinates.pipelines.Pipeline
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:methods:
.. rubric:: Attributes
.. autoautosummary:: pyemma.coordinates.pipelines.Pipeline
:attributes:
"""
from pyemma.coordinates.clustering.kmeans import KmeansClustering
from pyemma.coordinates.pipelines import Discretizer
if cluster is None:
_logger.warning('You did not specify a cluster algorithm.'
' Defaulting to kmeans(k=100)')
cluster = KmeansClustering(n_clusters=100)
disc = Discretizer(reader, transform, cluster, param_stride=stride, chunksize=chunksize)
if run:
disc.parametrize()
return disc
def save_traj(traj_inp, indexes, outfile, top=None, stride=1, chunksize=None, image_molecules=False, verbose=True):
r""" Saves a sequence of frames as a single trajectory.
Extracts the specified sequence of time/trajectory indexes from traj_inp
and saves it to one single molecular dynamics trajectory file. The output
format will be determined by the outfile name.
Parameters
----------
traj_inp :
traj_inp can be of two types.
1. a python list of strings containing the filenames associated with
the indices in :py:obj:`indexes`. With this type of input, a :py:obj:`topfile` is mandatory.
2. a :py:func:`pyemma.coordinates.data.feature_reader.FeatureReader`
object containing the filename list in :py:obj:`traj_inp.trajfiles`.
Please use :py:func:`pyemma.coordinates.source` to construct it.
With this type of input, the input :py:obj:`topfile` will be ignored.
and :py:obj:`traj_inp.topfile` will be used instead
indexes : ndarray(T, 2) or list of ndarray(T_i, 2)
A (T x 2) array for writing a trajectory of T time steps. Each row
contains two indexes (i, t), where i is the index of the trajectory
from the input and t is the index of the time step within the trajectory.
If a list of index arrays is given, these will be simply concatenated,
i.e. they will be written subsequently in the same trajectory file.
outfile : str.
The name of the output file. Its extension will determine the file type
written. Example: "out.dcd" If set to None, the trajectory object is
returned to memory
top : str, mdtraj.Trajectory, or mdtraj.Topology
The topology needed to read the files in the list :py:obj:`traj_inp`.
If :py:obj:`traj_inp` is not a list, this parameter is ignored.
stride : integer, default is 1
This parameter informs :py:func:`save_traj` about the stride used in
:py:obj:`indexes`. Typically, :py:obj:`indexes` contains frame-indexes
that match exactly the frames of the files contained in :py:obj:`traj_inp.trajfiles`.
However, in certain situations, that might not be the case. Examples
are cases in which a stride value != 1 was used when
reading/featurizing/transforming/discretizing the files contained
in :py:obj:`traj_inp.trajfiles`.
chunksize : int. Default=None.
The chunksize for reading input trajectory files. If :py:obj:`traj_inp`
is a :py:func:`pyemma.coordinates.data.feature_reader.FeatureReader` object,
this input variable will be ignored and :py:obj:`traj_inp.chunksize` will be used instead.
image_molecules: boolean, default is False
If set to true, :py:obj:`save_traj` will call the method traj.image_molecules and try to correct for broken
molecules accross periodic boundary conditions.
(http://mdtraj.org/1.7.2/api/generated/mdtraj.Trajectory.html#mdtraj.Trajectory.image_molecules)
verbose : boolean, default is True
Inform about created filenames
Returns
-------
traj : :py:obj:`mdtraj.Trajectory` object
Will only return this object if :py:obj:`outfile` is None
"""
from mdtraj import Topology, Trajectory
from pyemma.coordinates.data.feature_reader import FeatureReader
from pyemma.coordinates.data.fragmented_trajectory_reader import FragmentedTrajectoryReader
from pyemma.coordinates.data.util.frames_from_file import frames_from_files
from pyemma.coordinates.data.util.reader_utils import enforce_top
import itertools
# Determine the type of input and extract necessary parameters
if isinstance(traj_inp, (FeatureReader, FragmentedTrajectoryReader)):
if isinstance(traj_inp, FragmentedTrajectoryReader):
# lengths array per reader
if not all(isinstance(reader, FeatureReader)
for reader in itertools.chain.from_iterable(traj_inp._readers)):
raise ValueError("Only FeatureReaders (MD-data) are supported for fragmented trajectories.")
trajfiles = traj_inp.filenames_flat
top = traj_inp._readers[0][0].featurizer.topology
else:
top = traj_inp.featurizer.topology
trajfiles = traj_inp.filenames
chunksize = traj_inp.chunksize
reader = traj_inp
else:
# Do we have what we need?
if not isinstance(traj_inp, (list, tuple)):
raise TypeError("traj_inp has to be of type list, not %s" % type(traj_inp))
if not isinstance(top, (_string_types, Topology, Trajectory)):
raise TypeError("traj_inp cannot be a list of files without an input "
"top of type str (eg filename.pdb), mdtraj.Trajectory or mdtraj.Topology. "
"Got type %s instead" % type(top))
trajfiles = traj_inp
reader = None
# Enforce the input topology to actually be an md.Topology object
top = enforce_top(top)
# Convert to index (T,2) array if parsed a list or a list of arrays
indexes = _np.vstack(indexes)
# Check that we've been given enough filenames
if len(trajfiles) < indexes[:, 0].max():
raise ValueError("traj_inp contains %u trajfiles, "
"but indexes will ask for file nr. %u"
% (len(trajfiles), indexes[:,0].max()))
traj = frames_from_files(trajfiles, top, indexes, chunksize, stride, reader=reader)
# Avoid broken molecules
if image_molecules:
traj.image_molecules(inplace=True)
# Return to memory as an mdtraj trajectory object
if outfile is None:
return traj
# or to disk as a molecular trajectory file
else:
if isinstance(outfile, Path):
outfile = str(outfile.resolve())
traj.save(outfile)
if verbose:
_logger.info("Created file %s" % outfile)
def save_trajs(traj_inp, indexes, prefix='set_', fmt=None, outfiles=None,
inmemory=False, stride=1, verbose=False):
r""" Saves sequences of frames as multiple trajectories.
Extracts a number of specified sequences of time/trajectory indexes from the
input loader and saves them in a set of molecular dynamics trajectories.
The output filenames are obtained by prefix + str(n) + .fmt, where n counts
the output trajectory and extension is either set by the user, or else
determined from the input. Example: When the input is in dcd format, and
indexes is a list of length 3, the output will by default go to files
"set_1.dcd", "set_2.dcd", "set_3.dcd". If you want files to be stored
in a specific subfolder, simply specify the relative path in the prefix,
e.g. prefix='~/macrostates/\pcca_'
Parameters
----------
traj_inp : :py:class:`pyemma.coordinates.data.feature_reader.FeatureReader`
A data source as provided by Please use :py:func:`pyemma.coordinates.source` to construct it.
indexes : list of ndarray(T_i, 2)
A list of N arrays, each of size (T_n x 2) for writing N trajectories
of T_i time steps. Each row contains two indexes (i, t), where i is the
index of the trajectory from the input and t is the index of the time
step within the trajectory.
prefix : str, optional, default = `set_`
output filename prefix. Can include an absolute or relative path name.
fmt : str, optional, default = None
Outpuf file format. By default, the file extension and format. It will
be determined from the input. If a different format is desired, specify
the corresponding file extension here without a dot, e.g. "dcd" or "xtc".
outfiles : list of str, optional, default = None
A list of output filenames. When given, this will override the settings
of prefix and fmt, and output will be written to these files.
inmemory : Boolean, default = False (untested for large files)
Instead of internally calling traj_save for every (T_i,2) array in
"indexes", only one call is made. Internally, this generates a
potentially large molecular trajectory object in memory that is
subsequently sliced into the files of "outfiles". Should be faster for
large "indexes" arrays and large files, though it is quite memory
intensive. The optimal situation is to avoid streaming two times
through a huge file for "indexes" of type: indexes = [[1 4000000],[1 4000001]]
stride : integer, default is 1
This parameter informs :py:func:`save_trajs` about the stride used in
the indexes variable. Typically, the variable indexes contains frame
indexes that match exactly the frames of the files contained in
traj_inp.trajfiles. However, in certain situations, that might not be
the case. Examples of these situations are cases in which stride
value != 1 was used when reading/featurizing/transforming/discretizing
the files contained in traj_inp.trajfiles.
verbose : boolean, default is False
Verbose output while looking for "indexes" in the "traj_inp.trajfiles"
Returns
-------
outfiles : list of str
The list of absolute paths that the output files have been written to.
"""
# Make sure indexes is iterable
assert _types.is_iterable(indexes), "Indexes must be an iterable of matrices."
# only if 2d-array, convert into a list
if isinstance(indexes, _np.ndarray):
if indexes.ndim == 2:
indexes = [indexes]
# Make sure the elements of that lists are arrays, and that they are shaped properly
for i_indexes in indexes:
assert isinstance(i_indexes, _np.ndarray), "The elements in the 'indexes' variable must be numpy.ndarrays"
assert i_indexes.ndim == 2, \
"The elements in the 'indexes' variable must have ndim = 2, and not %u" % i_indexes.ndim
assert i_indexes.shape[1] == 2, \
"The elements in the 'indexes' variable must be of shape (T_i,2), and not (%u,%u)" % i_indexes.shape
# Determine output format of the molecular trajectory file
if fmt is None:
fname = traj_inp.filenames[0]
while hasattr(fname, '__getitem__') and not isinstance(fname, (str, bytes)):
fname = fname[0]
import os
_, fmt = os.path.splitext(fname)
else:
fmt = '.' + fmt
# Prepare the list of outfiles before the loop
if outfiles is None:
outfiles = []
for ii in range(len(indexes)):
outfiles.append(prefix + '%06u' % ii + fmt)
# Check that we have the same name of outfiles as (T, 2)-indexes arrays
if len(indexes) != len(outfiles):
raise Exception('len(indexes) (%s) does not match len(outfiles) (%s)' % (len(indexes), len(outfiles)))
# This implementation looks for "i_indexes" separately, and thus one traj_inp.trajfile
# might be accessed more than once (less memory intensive)
if not inmemory:
for i_indexes, outfile in zip(indexes, outfiles):
# TODO: use **kwargs to parse to save_traj
save_traj(traj_inp, i_indexes, outfile, stride=stride, verbose=verbose)
# This implementation is "one file - one pass" but might temporally create huge memory objects
else:
traj = save_traj(traj_inp, indexes, outfile=None, stride=stride, verbose=verbose)
i_idx = 0
for i_indexes, outfile in zip(indexes, outfiles):
# Create indices for slicing the mdtraj trajectory object
f_idx = i_idx + len(i_indexes)
# print i_idx, f_idx
traj[i_idx:f_idx].save(outfile)
_logger.info("Created file %s" % outfile)
# update the initial frame index
i_idx = f_idx
return outfiles
# =========================================================================
#
# TRANSFORMATION ALGORITHMS
#
# =========================================================================
def pca(data=None, dim=-1, var_cutoff=0.95, stride=1, mean=None, skip=0, chunksize=None, **kwargs):
r""" Principal Component Analysis (PCA).
PCA is a linear transformation method that finds coordinates of maximal
variance. A linear projection onto the principal components thus makes a
minimal error in terms of variation in the data. Note, however, that this
method is not optimal for Markov model construction because for that
purpose the main objective is to preserve the slow processes which can
sometimes be associated with small variance.
It estimates a PCA transformation from data. When input data is given as an
argument, the estimation will be carried out right away, and the resulting
object can be used to obtain eigenvalues, eigenvectors or project input data
onto the principal components. If data is not given, this object is an
empty estimator and can be put into a :func:`pipeline` in order to use PCA
in streaming mode.
Parameters
----------
data : ndarray (T, d) or list of ndarray (T_i, d) or a reader created by
source function data array or list of data arrays. T or T_i are the
number of time steps in a trajectory. When data is given, the PCA is
immediately parametrized by estimating the covariance matrix and
computing its eigenvectors.
dim : int, optional, default -1
the number of dimensions (principal components) to project onto. A
call to the :func:`map <pyemma.coordinates.transform.PCA.map>` function reduces the d-dimensional
input to only dim dimensions such that the data preserves the
maximum possible variance amongst dim-dimensional linear projections.
-1 means all numerically available dimensions will be used unless
reduced by var_cutoff. Setting dim to a positive value is exclusive
with var_cutoff.
var_cutoff : float in the range [0,1], optional, default 0.95
Determines the number of output dimensions by including dimensions
until their cumulative kinetic variance exceeds the fraction
subspace_variance. var_cutoff=1.0 means all numerically available
dimensions (see epsilon) will be used, unless set by dim. Setting
var_cutoff smaller than 1.0 is exclusive with dim
stride : int, optional, default = 1
If set to 1, all input data will be used for estimation. Note that
this could cause this calculation to be very slow for large data
sets. Since molecular dynamics data is usually correlated at short
timescales, it is often sufficient to estimate transformations at
a longer stride. Note that the stride option in the get_output()
function of the returned object is independent, so you can parametrize
at a long stride, and still map all frames through the transformer.
mean : ndarray, optional, default None
Optionally pass pre-calculated means to avoid their re-computation.
The shape has to match the input dimension.
skip : int, default=0
skip the first initial n frames per trajectory.
chunksize: int, default=None
Number of data frames to process at once. Choose a higher value here,
to optimize thread usage and gain processing speed. If None is passed,
use the default value of the underlying reader/data source. Choose zero to
disable chunking at all.
Returns
-------
pca : a :class:`PCA<pyemma.coordinates.transform.PCA>` transformation object
Object for Principle component analysis (PCA) analysis.
It contains PCA eigenvalues and eigenvectors, and the projection of
input data to the dominant PCA
Notes
-----
Given a sequence of multivariate data :math:`X_t`,
computes the mean-free covariance matrix.
.. math:: C = (X - \mu)^T (X - \mu)
and solves the eigenvalue problem
.. math:: C r_i = \sigma_i r_i,
where :math:`r_i` are the principal components and :math:`\sigma_i` are
their respective variances.
When used as a dimension reduction method, the input data is projected onto
the dominant principal components.
See `Wiki page <http://en.wikipedia.org/wiki/Principal_component_analysis>`_ for more theory and references.
for more theory and references.
See also
--------
:class:`PCA <pyemma.coordinates.transform.PCA>` : pca object
:func:`tica <pyemma.coordinates.tica>` : for time-lagged independent component analysis
.. autoclass:: pyemma.coordinates.transform.pca.PCA
:members:
:undoc-members:
.. rubric:: Methods
.. autoautosummary:: pyemma.coordinates.transform.pca.PCA
:methods: