File: __init__.py

package info (click to toggle)
python-biopython 1.68%2Bdfsg-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 46,860 kB
  • ctags: 13,237
  • sloc: python: 160,306; xml: 93,216; ansic: 9,118; sql: 1,208; makefile: 155; sh: 63
file content (244 lines) | stat: -rw-r--r-- 8,475 bytes parent folder | download | duplicates (2)
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
# Copyright 2014-2016 by Marco Galardini.  All rights reserved.
# This code is part of the Biopython distribution and governed by its
# license.  Please see the LICENSE file that should have been included
# as part of this package.
#

r"""phenotype data input/output.

Input
=====
The main function is Bio.phenotype.parse(...) which takes an input file,
and format string.  This returns an iterator giving PlateRecord objects:

    >>> from Bio import phenotype
    >>> for record in phenotype.parse("plates.csv", "pm-csv"):
    ...     print("%s %i" % (record.id, len(record)))
    ...
    PM01 96
    PM01 96
    PM09 96
    PM09 96

Note that the parse() function will invoke the relevant parser for the
format with its default settings.  You may want more control, in which case
you need to create a format specific sequence iterator directly.

Input - Single Records
======================
If you expect your file to contain one-and-only-one record, then we provide
the following 'helper' function which will return a single PlateRecord, or
raise an exception if there are no records or more than one record:

    >>> from Bio import phenotype
    >>> record = phenotype.read("plate.json", "pm-json")
    >>> print("%s %i" % (record.id, len(record)))
    PM01 96

This style is useful when you expect a single record only (and would
consider multiple records an error).  For example, when dealing with PM
JSON files saved by the opm library.

However, if you just want the first record from a file containing multiple
record, use the next() function on the iterator (or under Python 2, the
iterator's next() method):

    >>> from Bio import phenotype
    >>> record = next(phenotype.parse("plates.csv", "pm-csv"))
    >>> print("%s %i" % (record.id, len(record)))
    PM01 96

The above code will work as long as the file contains at least one record.
Note that if there is more than one record, the remaining records will be
silently ignored.

Output
======
Use the function Bio.phenotype.write(...), which takes a complete set of
PlateRecord objects (either as a list, or an iterator), an output file handle
(or in recent versions of Biopython an output filename as a string) and of
course the file format:

    >>> from Bio import phenotype
    >>> records = ...
    >>> phenotype.write(records, "example.json", "pm-json")

Or, using a handle::

    >>> from Bio import phenotype
    >>> records = ...
    >>> with open("example.json", "w") as handle:
    >>>    phenotype.write(records, handle, "pm-json")

You are expected to call this function once (with all your records) and if
using a handle, make sure you close it to flush the data to the hard disk.


File Formats
============
When specifying the file format, use lowercase strings.

 - pm-json - Phenotype Microarray plates in JSON format.
 - pm-csv  - Phenotype Microarray plates in CSV format, which is the
             machine vendor format

Note that while Bio.phenotype can read the above file formats, it can only
write in JSON format.
"""

from __future__ import print_function
from Bio._py3k import basestring

from Bio import BiopythonExperimentalWarning
from Bio.File import as_handle
from . import phen_micro

import warnings

__docformat__ = "epytext en"  # not just plaintext

warnings.warn('Bio.phenotype is an experimental submodule which may undergo '
        'significant changes prior to its future official release.',
        BiopythonExperimentalWarning)

# Convention for format names is "mainname-format" in lower case.

_FormatToIterator = {"pm-csv": phen_micro.CsvIterator,
                     "pm-json": phen_micro.JsonIterator,
                     }

_FormatToWriter = {"pm-json": phen_micro.JsonWriter,
                   }


def write(plates, handle, format):
    """Write complete set of PlateRecords to a file.

     - plates    - A list (or iterator) of PlateRecord objects.
     - handle    - File handle object to write to, or filename as string
                   (note older versions of Biopython only took a handle).
     - format    - lower case string describing the file format to write.

    You should close the handle after calling this function.

    Returns the number of records written (as an integer).
    """
    # Try and give helpful error messages:
    if not isinstance(format, basestring):
        raise TypeError("Need a string for the file format (lower case)")
    if not format:
        raise ValueError("Format required (lower case string)")
    if format != format.lower():
        raise ValueError("Format string '%s' should be lower case" % format)

    if isinstance(plates, phen_micro.PlateRecord):
        plates = [plates]

    with as_handle(handle, 'w') as fp:
        # Map the file format to a writer class
        if format in _FormatToWriter:
            writer_class = _FormatToWriter[format]
            count = writer_class(plates).write(fp)
        else:
            raise ValueError("Unknown format '%s'" % format)

        assert isinstance(count, int), "Internal error - the underlying %s " \
            "writer should have returned the record count, not %s" \
            % (format, repr(count))

    return count


def parse(handle, format):
    """Turns a phenotype file into an iterator returning PlateRecords.

     - handle   - handle to the file, or the filename as a string
                  (note older versions of Biopython only took a handle).
     - format   - lower case string describing the file format.

    Typical usage, opening a file to read in, and looping over the record(s):

    >>> from Bio import phenotype
    >>> filename = "plates.csv"
    >>> for record in phenotype.parse(filename, "pm-csv"):
    ...    print("ID %s" % record.id)
    ...    print("Number of wells %i" % len(record))
    ...
    ID PM01
    Number of wells 96

    Use the Bio.phenotype.read(...) function when you expect a single record
    only.
    """
    # Try and give helpful error messages:
    if not isinstance(format, basestring):
        raise TypeError("Need a string for the file format (lower case)")
    if not format:
        raise ValueError("Format required (lower case string)")
    if format != format.lower():
        raise ValueError("Format string '%s' should be lower case" % format)

    with as_handle(handle, 'rU') as fp:
        # Map the file format to a sequence iterator:
        if format in _FormatToIterator:
            iterator_generator = _FormatToIterator[format]
            i = iterator_generator(fp)
        else:
            raise ValueError("Unknown format '%s'" % format)
        # This imposes some overhead... wait until we drop Python 2.4 to fix it
        for r in i:
            yield r


def read(handle, format):
    """Turns a phenotype file into a single PlateRecord.

     - handle   - handle to the file, or the filename as a string
                  (note older versions of Biopython only took a handle).
     - format   - string describing the file format.

    This function is for use parsing phenotype files containing
    exactly one record.  For example, reading a PM JSON file:

    >>> from Bio import phenotype
    >>> record = phenotype.read("plate.json", "pm-json")
    >>> print("ID %s" % record.id)
    PM09
    >>> print("Number of wells %i" % len(record))
    Number of wells 96

    If the handle contains no records, or more than one record,
    an exception is raised.  For example:

    >>> from Bio import phenotype
    >>> record = phenotype.read("plates.csv", "pm-csv")
    Traceback (most recent call last):
        ...
    ValueError: More than one record found in handle

    If however you want the first record from a file containing
    multiple records this function would raise an exception (as
    shown in the example above).  Instead use:

    >>> from Bio import phenotype
    >>> record = next(phenotype.parse("plates.csv", "pm-csv"))
    >>> print("First record's ID %s" % record.id)
    First record's ID PM09

    Use the Bio.phenotype.parse(handle, format) function if you want
    to read multiple records from the handle.
    """
    iterator = parse(handle, format)
    try:
        first = next(iterator)
    except StopIteration:
        first = None
    if first is None:
        raise ValueError("No records found in handle")
    try:
        second = next(iterator)
    except StopIteration:
        second = None
    if second is not None:
        raise ValueError("More than one record found in handle")
    return first