File size: 11,860 Bytes
b7731cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2010 by Tiago Antao.  All rights reserved.
#
# This file is part of the Biopython distribution and governed by your
# choice of the "Biopython License Agreement" or the "BSD 3-Clause License".
# Please see the LICENSE file that should have been included as part of this
# package.

"""Code to parse BIG GenePop files.

The difference between this class and the standard Bio.PopGen.GenePop.Record
class is that this one does not read the whole file to memory.
It provides an iterator interface, slower but consuming much mess memory.
Should be used with big files (Thousands of markers and individuals).

See http://wbiomed.curtin.edu.au/genepop/ , the format is documented
here: http://wbiomed.curtin.edu.au/genepop/help_input.html .

Classes:
 - FileRecord           Holds GenePop data.

Functions:


"""
from Bio.PopGen.GenePop import get_indiv


def read(fname):
    """Parse a file containing a GenePop file.

    fname is a file name that contains a GenePop record.
    """
    record = FileRecord(fname)
    return record


class FileRecord:
    """Hold information from a GenePop record.

    Attributes:
    - marker_len         The marker length (2 or 3 digit code per allele).
    - comment_line       Comment line.
    - loci_list          List of loci names.

    Methods:
    - get_individual     Returns the next individual of the current population.
    - skip_population    Skips the current population.

    skip_population skips the individuals of the current population, returns
    True if there are more populations.

    get_individual returns an individual of the current population (or None
    if the list ended).

    Each individual is a pair composed by individual name and a list of alleles
    (2 per marker or 1 for haploid data). Examples::

        ('Ind1', [(1,2),    (3,3), (200,201)]
        ('Ind2', [(2,None), (3,3), (None,None)]
        ('Other1', [(1,1),  (4,3), (200,200)]

    """

    def __init__(self, fname):
        """Initialize the class."""
        self.comment_line = ""
        self.loci_list = []
        self.fname = fname
        self.start_read()

    def __str__(self):
        """Return (reconstructs) a GenePop textual representation.

        This might take a lot of memory.
        Marker length will be 3.
        """
        marker_len = 3
        rep = [self.comment_line + "\n"]
        rep.append("\n".join(self.loci_list) + "\n")
        current_pop = self.current_pop
        current_ind = self.current_ind
        self._handle.seek(0)
        self.skip_header()
        rep.append("Pop\n")
        more = True
        while more:
            res = self.get_individual()
            if res is True:
                rep.append("Pop\n")
            elif res is False:
                more = False
            else:
                name, markers = res
                rep.append(name)
                rep.append(",")
                for marker in markers:
                    rep.append(" ")
                    for al in marker:
                        if al is None:
                            al = "0"
                        aStr = str(al)
                        while len(aStr) < marker_len:
                            aStr = "".join(["0", aStr])
                        rep.append(aStr)
                rep.append("\n")
        self.seek_position(current_pop, current_ind)
        return "".join(rep)

    def start_read(self):
        """Start parsing a file containing a GenePop file."""
        self._handle = open(self.fname)
        self.comment_line = self._handle.readline().rstrip()
        # We can now have one loci per line or all loci in a single line
        # separated by either space or comma+space...
        # We will remove all commas on loci... that should not be a problem
        sample_loci_line = self._handle.readline().rstrip().replace(",", "")
        all_loci = sample_loci_line.split(" ")
        self.loci_list.extend(all_loci)
        for line in self._handle:
            line = line.rstrip()
            if line.upper() == "POP":
                break
            self.loci_list.append(line)
        else:
            raise ValueError(
                "No population data found, file probably not GenePop related"
            )
        # self._after_pop = True
        self.current_pop = 0
        self.current_ind = 0

    def skip_header(self):
        """Skip the Header. To be done after a re-open."""
        self.current_pop = 0
        self.current_ind = 0
        for line in self._handle:
            if line.rstrip().upper() == "POP":
                return

    def seek_position(self, pop, indiv):
        """Seek a certain position in the file.

        Arguments:
         - pop - pop position (0 is first)
         - indiv - individual in pop

        """
        self._handle.seek(0)
        self.skip_header()
        while pop > 0:
            self.skip_population()
            pop -= 1
        while indiv > 0:
            self.get_individual()
            indiv -= 1

    def skip_population(self):
        """Skip the current population. Returns true if there is another pop."""
        for line in self._handle:
            if line == "":
                return False
            line = line.rstrip()
            if line.upper() == "POP":
                self.current_pop += 1
                self.current_ind = 0
                return True

    def get_individual(self):
        """Get the next individual.

        Returns individual information if there are more individuals
        in the current population.
        Returns True if there are no more individuals in the current
        population, but there are more populations. Next read will
        be of the following pop.
        Returns False if at end of file.
        """
        for line in self._handle:
            line = line.rstrip()
            if line.upper() == "POP":
                self.current_pop += 1
                self.current_ind = 0
                return True
            else:
                self.current_ind += 1
                indiv_name, allele_list, ignore = get_indiv(line)
                return indiv_name, allele_list
        return False

    def remove_population(self, pos, fname):
        """Remove a population (by position).

        Arguments:
         - pos - position
         - fname - file to be created with population removed

        """
        old_rec = read(self.fname)
        with open(fname, "w") as f:
            f.write(self.comment_line + "\n")
            for locus in old_rec.loci_list:
                f.write(locus + "\n")
            curr_pop = 0
            l_parser = old_rec.get_individual()
            start_pop = True
            while l_parser:
                if curr_pop == pos:
                    old_rec.skip_population()
                    curr_pop += 1
                else:
                    if l_parser is True:
                        curr_pop += 1
                        start_pop = True
                    else:
                        if start_pop:
                            f.write("POP\n")
                            start_pop = False
                        name, markers = l_parser
                        f.write(name + ",")
                        for marker in markers:
                            f.write(" ")
                            for al in marker:
                                if al is None:
                                    al = "0"
                                aStr = str(al)
                                while len(aStr) < 3:
                                    aStr = "".join(["0", aStr])
                                f.write(aStr)
                        f.write("\n")

                l_parser = old_rec.get_individual()

    def remove_locus_by_position(self, pos, fname):
        """Remove a locus by position.

        Arguments:
         - pos - position
         - fname - file to be created with locus removed

        """
        old_rec = read(self.fname)
        with open(fname, "w") as f:
            f.write(self.comment_line + "\n")
            loci_list = old_rec.loci_list
            del loci_list[pos]
            for locus in loci_list:
                f.write(locus + "\n")
            l_parser = old_rec.get_individual()
            f.write("POP\n")
            while l_parser:
                if l_parser is True:
                    f.write("POP\n")
                else:
                    name, markers = l_parser
                    f.write(name + ",")
                    marker_pos = 0
                    for marker in markers:
                        if marker_pos == pos:
                            marker_pos += 1
                            continue
                        marker_pos += 1
                        f.write(" ")
                        for al in marker:
                            if al is None:
                                al = "0"
                            aStr = str(al)
                            while len(aStr) < 3:
                                aStr = "".join(["0", aStr])
                            f.write(aStr)
                    f.write("\n")

                l_parser = old_rec.get_individual()

    def remove_loci_by_position(self, positions, fname):
        """Remove a set of loci by position.

        Arguments:
         - positions - positions
         - fname - file to be created with locus removed

        """
        old_rec = read(self.fname)
        with open(fname, "w") as f:
            f.write(self.comment_line + "\n")
            loci_list = old_rec.loci_list
            positions.sort()
            positions.reverse()
            posSet = set()
            for pos in positions:
                del loci_list[pos]
                posSet.add(pos)
            for locus in loci_list:
                f.write(locus + "\n")
            l_parser = old_rec.get_individual()
            f.write("POP\n")
            while l_parser:
                if l_parser is True:
                    f.write("POP\n")
                else:
                    name, markers = l_parser
                    f.write(name + ",")
                    marker_pos = 0
                    for marker in markers:
                        if marker_pos in posSet:
                            marker_pos += 1
                            continue
                        marker_pos += 1
                        f.write(" ")
                        for al in marker:
                            if al is None:
                                al = "0"
                            aStr = str(al)
                            while len(aStr) < 3:
                                aStr = "".join(["0", aStr])
                            f.write(aStr)
                    f.write("\n")

                l_parser = old_rec.get_individual()

    def remove_locus_by_name(self, name, fname):
        """Remove a locus by name.

        Arguments:
         - name - name
         - fname - file to be created with locus removed

        """
        for i, locus in enumerate(self.loci_list):
            if locus == name:
                self.remove_locus_by_position(i, fname)
                return
        # If here than locus not existent... Maybe raise exception?
        #   Although it should be Ok... Just a boolean return, maybe?

    def remove_loci_by_name(self, names, fname):
        """Remove a loci list (by name).

        Arguments:
         - names - names
         - fname - file to be created with loci removed

        """
        positions = []
        for i, locus in enumerate(self.loci_list):
            if locus in names:
                positions.append(i)
        self.remove_loci_by_position(positions, fname)
        # If here than locus not existent... Maybe raise exception?
        #   Although it should be Ok... Just a boolean return, maybe?