00dea1ab77fd9bd78324a18b6bea880aa2f7d272
[sawsim.git] / pysawsim / sawsim.py
1 # Copyright (C) 2010  W. Trevor King <wking@drexel.edu>
2 #
3 # This program is free software: you can redistribute it and/or modify
4 # it under the terms of the GNU General Public License as published by
5 # the Free Software Foundation, either version 3 of the License, or
6 # (at your option) any later version.
7 #
8 # This program is distributed in the hope that it will be useful,
9 # but WITHOUT ANY WARRANTY; without even the implied warranty of
10 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 # GNU General Public License for more details.
12 #
13 # You should have received a copy of the GNU General Public License
14 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
15 #
16 # The author may be contacted at <wking@drexel.edu> on the Internet, or
17 # write to Trevor King, Drudge's University, Physics Dept., 3141 Chestnut St.,
18 # Philadelphia PA 19104, USA.
19
20
21 """`sawsim` output parsing utilities.
22
23 * `Event` instances represent domain state transitions.
24 * `parse()` parses the output of a typical `sawsim` run.
25 """
26
27
28 from collections import namedtuple
29
30
31
32 Event = namedtuple(
33     typename='Event',
34     field_names=['force', 'initial_state', 'final_state'])
35
36
37 def parse(text):
38     """Parse the output of a `sawsim` run.
39
40     >>> text = '''#Force (N)\\tinitial state\\tFinal state
41     ... 2.90301e-10\\tfolded\\tunfolded
42     ... 2.83948e-10\\tfolded\\tunfolded
43     ... 2.83674e-10\\tfolded\\tunfolded
44     ... 2.48384e-10\\tfolded\\tunfolded
45     ... 2.43033e-10\\tfolded\\tunfolded
46     ... 2.77589e-10\\tfolded\\tunfolded
47     ... 2.85343e-10\\tfolded\\tunfolded
48     ... 2.67796e-10\\tfolded\\tunfolded
49     ... '''
50     >>> events = list(parse(text))
51     >>> len(events)
52     8
53     >>> events[0]  # doctest: +ELLIPSIS
54     Event(force=2.9030...e-10, initial_state='folded', final_state='unfolded')
55     """
56     for line in text.splitlines():
57         line = line.strip()
58         if len(line) == 0 or line.startswith('#'):
59             continue
60         fields = line.split('\t')
61         if len(fields) != 3:
62             raise ValueError(fields)
63         force,initial_state,final_state = fields
64         yield Event(float(force), initial_state, final_state)