reader.py 23.6 KB
Newer Older
fabrice's avatar
fabrice committed
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
"""
                            Reader objects
"""
from __future__ import absolute_import, division, print_function

import os
import re
import logging
import collections
import scipy.spatial.distance as distance
from .base import sort_2dict
from .protmap import (ResMap, ResAtmMap)

logger = logging.getLogger(__name__)
Atom = collections.namedtuple("Atom", ["name", "coords"])


class RegexFile(object):
    def __init__(self, filepath, filetype='', regex='', sort=''):
        self.regex = regex
        self.sort = sort
        self.filepath = filepath
        self.filetype = filetype
        self.lines = {}

    def load(self):
        """
        Fill lines with dictionary. Each key is a line number in the given file
        :return: None
        """
        lines_dict = {}

        if not self.regex:
            logger.error("Can't parse file %s" % self.filepath)

        with open(self.filepath) as f:
            for index, line in enumerate(f):
                match = self.regex.match(line)
                if match:
                    lines_dict[index] = match.groupdict()

        if self.sort:
            lines_dict = sort_2dict(lines_dict, self.sort)

        self.lines = lines_dict


class MapFile(RegexFile):
    # List of 3tuples ("regex_file", "filetype", "sort_field")
    # sort_field allow sorting lines with values into this field
    # TODO: wrong regex for native_full ?
52
    # TODO: smarter dict ...
fabrice's avatar
fabrice committed
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
    types = {
        "plmdca": {
            "regex": re.compile("^(?P<res1_nb>\d+)\s+(?P<res1_name>\w)\s+"
                                "(?P<res2_nb>\d+)\s+(?P<res2_name>\w)\s+"
                                "(?P<mi_score>\d)\s+"
                                "(?P<plm_score>\-?\d+\.\d+)\s*$"),
            "score_field": "plm_score"
        },
        "evfold": {
            "regex": re.compile(
                '^(?P<res1_nb>\d+),(?P<res2_nb>\d+),'
                '(?P<ec_score>\-?\d+\.\d+e?\-?\d*),'
                '(?P<placeholder>\d),(?P<res1_cons>\d+),'
                '(?P<res2_cons>\d+),(?P<ss_filter>\d|\d{3}),'
                '(?P<high_cons_filter>\d|\d{3}),'
                '(?P<cc_filter>\d|\d{3}),(?P<res1_1l_code>\w),'
                '(?P<res2_1l_code>\w)$'),
            "score_field": "ec_score"
        },
        "pconsc": {
            "regex": re.compile(
                '^(?P<res1_nb>\d+) (?P<res2_nb>\d+) '
                '(?P<ec_score>\-?\d+\.\d+e?\-?\d*)$'),
            "score_field": "ec_score"
        },
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
        "pconsc1": {
            "regex": re.compile(
                '^(?P<res1_nb>\d+) (?P<res2_nb>\d+) '
                '(?P<ec_score>\-?\d+\.\d+e?\-?\d*)$'),
            "score_field": "ec_score"
        },
        "pconsc2": {
            "regex": re.compile(
                '^(?P<res1_nb>\d+) (?P<res2_nb>\d+) '
                '(?P<ec_score>\-?\d+\.\d+e?\-?\d*)$'),
            "score_field": "ec_score"
        },
        "metapsicov_stg1": {
            "regex": re.compile(
                '^(?P<res1_nb>\d+) (?P<res2_nb>\d+) \d (?P<res_dist>-?\d+.?\d*) '
                '(?P<ec_score>\-?\d+.\d+e?\-?\d*)$'),
            "score_field": "ec_score"
        },
        "metapsicov_stg2": {
            "regex": re.compile(
                '^(?P<res1_nb>\d+) (?P<res2_nb>\d+) \d (?P<res_dist>-?\d+.?\d*) '
                '(?P<ec_score>\-?\d+.\d+e?\-?\d*)$'),
            "score_field": "ec_score"
        },
        "psicov": {
fabrice's avatar
fabrice committed
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
            "regex": re.compile(
                '^(?P<res1_nb>\d+) (?P<res2_nb>\d+) \d (?P<res_dist>-?\d+.?\d*) '
                '(?P<ec_score>\-?\d+.\d+e?\-?\d*)$'),
            "score_field": "ec_score"
        },
        "gremlin": {
            "regex": re.compile(
                '^(?P<res1_nb>\d+)\t(?P<res2_nb>\d+)\t'
                '(?P<res1_id>\d+_[AC-IK-NP-TVWYZ])\t'
                '(?P<res2_id>\d+_[AC-IK-NP-TVWYZ])\t'
                '(?P<raw_score>\-?\d+\.\d+e?\-?\d*)\t'
                '(?P<scale_score>\-?\d+\.\d+e?\-?\d*)\t'
                '(?P<prob>\-?\d+\.\d+e?\-?\d*)'),
            "score_field": "scale_score"
        },
        "native": {
            "regex": re.compile(
                '^\s*(?P<res1_nb>\d+)\s+(?P<res2_nb>\d+)\s+('
                '?P<ca_ca>\d+\.\d+)\s+(?P<cb_cb>\d+\.\d+)\s+'
                '(?P<sc_sc>\d+\.\d+)\s+(?P<valid>\w+)'),
            "score_field": None
        },
        "native_full": {
            "regex": re.compile(
                '^\s*(?P<res1_nb>\d+)\s+(?P<res2_nb>\d+)\s+('
                '?P<ca_ca>\d+\.\d+)\s+(?P<cb_cb>\d+\.\d+)\s+'
                '(?P<sc_sc>\d+\.\d+)\s+(?P<valid>\w+)'),
            "score_field": None
        },
        "bbcontacts": {
            "regex": re.compile(
                '\s*(?P<identifier>\w+)\s+(?P<diversity>-?\d+\.?\d*)'
                '\s+(?P<direction>Parallel|Antiparallel)'
                '\s+(?P<viterbiscore>-?\d+\.?\d*)'
                '\s+(?P<indexpred>\d+)'
                '\s+(?P<state>first|internal|last)'
                '\s+(?P<res1_nb>\d+)\s+(?P<res2_nb>\d+)'),
            "score_field": None
        },
        "contactlist": {
            "regex": re.compile(
                '^\s*(?P<res1_nb>\d+)[\s,;]+(?P<res2_nb>\d+)[\s,'
                ';]*(?P<con_flag>\w*)'),
            "score_field": None
        },
        "metapsicovhb": {
            "regex": re.compile(
                '^\s*(?P<res_donor>\d+)[\s,;]+'
                '(?P<res_acceptor>\d+)[\s,;]+\d[\s,;]+'
                '(?P<res_dist>-?\d+.?\d*)[\s,;]+'
                '(?P<hbscore>-?\d+\.?\d*)'),
            "score_field": "hbscore"
        },
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
        "default_1": {
            "regex": re.compile(
                '^\s*(?P<res1_nb>\d+)\s+(?P<res2_nb>\d+)\s+'
                '(?P<resn1>\w+)\s+'
                '(?P<resn2>\w+)\s+'
                '(?P<score>[\w\d\.\+\-]+)'),
            "score_field": "score"
        },
        "default_2": {
            "regex": re.compile(
                '^\s*(?P<res1_nb>\d+)\s+(?P<res2_nb>\d+)\s+'
                '(?P<score>[\w\d\.\+\-]+)'),
            "score_field": "score"
        },
        "default_3": {
fabrice's avatar
fabrice committed
171
172
173
174
            "regex": re.compile(
                '^\s*(?P<res1_nb>\d+)\s+(?P<res2_nb>\d+)\s+'
                '(?P<resn1>\w+)\s+'
                '(?P<resn2>\w+)\s+'),
175
176
177
178
179
180
            "score_field": None
        },
        "default_4": {
            "regex": re.compile(
                '^\s*(?P<res1_nb>\d+)\s+(?P<res2_nb>\d+)\s+'),
            "score_field": None
fabrice's avatar
fabrice committed
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
        }
    }
    check_type = True

    def __init__(self, *args, **kwargs):
        super(MapFile, self).__init__(*args, **kwargs)
        if self.check_type:
            self.regex, self.filetype, self.sort = self.check_maptype()
        self.mapdict = {"alldistmap": None,
                        "allcontactmap": None,
                        "distmap": None,
                        "contactmap": None,
                        "scoremap": None}
        self.clashlist = None
        self.contactlist = None
        self.flaglist = None
        # self.contactmap = None
        # self.distmap = None

    def create_map(self, protein, contactdef, flaglist=None, offset=0, sym=True,
                   **kwargs):
        raise NotImplementedError("Class %s doesn't implement create_map" %
                                  self.__class__.__name__)

    def check_contacts(self, aa_seq):
        """
        Check if plm_dict is consistent with input sequence
        :param aa_seq:
        """
        logger.info("Checking consistency of contacts with input sequence")
        for line in self.lines:
            if self.lines[line]['res1_name'] != aa_seq[int(self.lines[line]['res1_nb']) - 1] \
                    or self.lines[line]['res2_name'] != aa_seq[int(self.lines[line]['res2_nb']) - 1]:
                logger.error("Difference between given sequence and residu "
                             "names in contact file at line %d !" % line)

    def update_map(self, resmap):
        raise NotImplementedError("Class %s doesn't implement update_map" %
                                  self.__class__.__name__)

    def check_maptype(self):
        logger.info("Checking format for file %s" % self.filepath)
        # Chechk if given type is supported
        if self.filetype not in self.types:
            logger.error("Format %s not supported !" % self.filetype)
            return [None] * 3
        # TODO: report this check into commands section
        with open(self.filepath) as infile:
            # Check first and second line of file
            for index, line in enumerate(infile):
                match = self.types[self.filetype].get("regex").match(line)
232
233
234
235
236
                # TODO: DRY rule !!
                def1match = self.types["default_1"]["regex"].match(line)
                def2match = self.types["default_2"]["regex"].match(line)
                def3match = self.types["default_3"]["regex"].match(line)
                def4match = self.types["default_4"]["regex"].match(line)
fabrice's avatar
fabrice committed
237
238
239
240
241
242
243
                if match:
                    logger.debug("Format type correct")
                    return [
                        self.types[self.filetype].get("regex"),
                        self.filetype,
                        self.types[self.filetype].get("score_field")
                    ]
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
                elif def1match:
                    logger.debug("Format type correct")
                    return [
                        self.types["default_1"].get("regex"),
                        self.filetype,
                        self.types["default_1"].get("score_field")
                    ]
                elif def2match:
                    logger.debug("Format type correct")
                    return [
                        self.types["default_2"].get("regex"),
                        self.filetype,
                        self.types["default_2"].get("score_field")
                    ]
                elif def3match:
                    logger.debug("Format type correct")
                    return [
                        self.types["default_3"].get("regex"),
                        self.filetype,
                        self.types["default_3"].get("score_field")
                    ]
                elif def4match:
                    logger.debug("Format type correct")
                    return [
                        self.types["default_4"].get("regex"),
                        self.filetype,
                        self.types["default_4"].get("score_field")
                    ]
fabrice's avatar
fabrice committed
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
                if index > 2:
                    logger.error("Error reading %s file." % self.filetype)
                    # Remove contact file
                    break
        logger.error("Wrong format type given ...")
        return [None] * 3

    def read(self, protein=None, contactdef=5.0, groupby_method="min",
             scsc=None):
        logger.info("Reading %s file" % self.filepath)
        if self.filetype:
            # Read file with regex related to filetype
            self.load()
            logger.debug(self.lines)
        if protein:
            logger.info("Loading contact list")
            if self.filetype == "contactlist":
                self.flaglist = {
                    tuple(sorted(
                        [int(self.lines[contact].get("res1_nb")),
                         int(self.lines[contact].get("res2_nb"))]
                    )): self.lines[contact].get("con_flag")
                    for contact in self.lines if
                    self.lines[contact].get("res1_nb") and
                    self.lines[contact].get("res2_nb")}
            if self.filetype == "metapsicovhb":
                # HB contacts aren't sorted since the first res correspond to
                #  donor and second to acceptor
                self.contactlist = [
                    tuple([int(self.lines[contact].get("res_donor")),
                           int(self.lines[contact].get("res_acceptor"))])
                    for contact in self.lines
                    if self.lines[contact].get("res_donor") and
                    self.lines[contact].get("res_acceptor")]
            else:
                self.contactlist = [
                    tuple(sorted(
                        [int(self.lines[contact].get("res1_nb")),
                         int(self.lines[contact].get("res2_nb"))]))
                    for contact in self.lines
                    if self.lines[contact].get("res1_nb") and
                    self.lines[contact].get("res2_nb")]
            logger.debug(self.contactlist)
            sym = False if self.filetype == "metapsicovhb" else True
            self.create_map(protein, contactdef,
                            groupby_method=groupby_method, scsc=scsc,
                            flaglist=self.flaglist, sym=sym)
            if self.filetype == "plmdca":
                # If contact filetype contain residues name, check if it is
                # consistent with given sequence
                self.check_contacts(protein.aa_sequence.sequence)
            if self.filetype == "evfold":
                logger.info("Loading evfold clash list")
                self.clashlist = [
                    next((el for el in (self.lines[contact].get("ss_filter"),
                                        self.lines[contact].get("high_cons_filter"),
                                        self.lines[contact].get("cc_filter")) if el != "0"), "0")
                    for contact in self.lines if
                    self.lines[contact].get("res1_nb") and
                    self.lines[contact].get("res2_nb")]
                if len(self.contactlist) != len(self.clashlist):
                    logger.error("When reading input file, clash list is not "
                                 "the same length than contactlist")
                logger.debug(self.clashlist)


class ContactMapFile(MapFile):
    # "plmdca", "evfold", "bbcontacts", "pconsc", "gremlin", "metapsicov",
    def __init__(self, filepath, filetype):
        super(self.__class__, self).__init__(filepath, filetype)

    def update_map(self, resmap):
        # TODO: swap dataframe factory here
        raise NotImplementedError

    def create_map(self, protein, *args, **kwargs):
        """
        Get res - res map
        :param protein:
        :param args:
        :param kwargs:
        :return:
        """
        offset = min(protein.index)  # Should be 1 or upper (human_idx)
        idxnames = ["residuex"] if self.filetype != "metapsicovhb" else [
            "donor"]
        colnames = ["residuey"] if self.filetype != "metapsicovhb" else [
            "acceptor"]
        contactmap = ResMap(protein.aa_sequence.sequence, mtype='contact',
                            flaglist=kwargs['flaglist'],
                            seqidx=protein.index, index=idxnames,
363
364
                            columns=colnames, sym=kwargs['sym'],
                            desc=self.filetype)
fabrice's avatar
fabrice committed
365
366
367
        # DataFrame containing ec scores
        scoremap = ResMap(protein.aa_sequence.sequence, mtype='score',
                          seqidx=protein.index, index=idxnames,
368
369
                          columns=colnames, sym=kwargs['sym'],
                          desc=self.filetype) if self.sort else None
fabrice's avatar
fabrice committed
370
371
        distmap = ResMap(protein.aa_sequence.sequence, mtype='distance',
                         seqidx=protein.index, index=idxnames, columns=colnames,
372
373
                         sym=kwargs['sym'], desc=self.filetype) if \
            self.filetype == "metapsicovhb" else None
fabrice's avatar
fabrice committed
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

        for contact_id in self.lines:
            if self.filetype == "metapsicovhb":
                resid1 = int(self.lines[contact_id].get('res_donor'))
                resid2 = int(self.lines[contact_id].get('res_acceptor'))
                dist = float(self.lines[contact_id].get('res_dist'))
            else:
                resid1 = int(self.lines[contact_id].get('res1_nb'))
                resid2 = int(self.lines[contact_id].get('res2_nb'))
                dist = None
            # Res id start from 0 in res-res map
            residx1 = contactmap.index[resid1 - offset]
            residx2 = contactmap.index[resid2 - offset]

            if (int(residx1.split("-")[0]) != resid1) or \
                    (resid2 != int(residx2.split("-")[0])):
                logger.error("Wrong resid humanidx (%d, %d) in contact (%d) is "
                             "not the same in resmap (%d, %d)" % (
                                 resid1, resid2, contact_id,
                                 int(residx1.split("-")[0]),
                                 int(residx2.split("-")[0])))

            contactmap.set_value(residx1, residx2, True)
            if self.sort:
                scoremap.sort_list.append((resid1 - offset, resid2 - offset))
                scoremap.set_value(residx1, residx2,
                                   float(self.lines[contact_id].get(self.sort)))
            if distmap is not None:
                distmap.set_value(residx1, residx2, dist)

        logger.debug("%s contact map:\n%s" % (self.filetype, contactmap))
        self.mapdict["contactmap"] = contactmap
        logger.debug("%s score map:\n%s" % (self.filetype, scoremap))
        self.mapdict["scoremap"] = scoremap
        if distmap is not None:
            self.mapdict["distmap"] = distmap


class PDBFile(MapFile):
    pdbreg = re.compile('^(?P<record>ATOM  |HETATM)(?P<serial>[\s\w]{5})'
                        '\s(?P<name>[\s\w]{4})'
                        '(?P<altLoc>[\s\w])'
                        '(?P<resName>\w{3})\s(?P<chainID>\w)'
                        '(?P<resSeq>[\s\w]{4})(?P<iCode>[\s\w])'
                        '\s{3}(?P<x>[\s\d-]{4}\.\d{3})(?P<y>[\s\d-]{4}\.\d{3})'
                        '(?P<z>[\s\d-]{4}\.\d{3})'
                        '(?P<occupancy>[\s\d-]{3}\.\d{2})'
                        '(?P<tempFactor>[\s\d-]{3}\.\d{2})'
                        '\s{10}(?P<element>[\s\w]{2})'
                        '(?P<charge>[\s\w]{2})')

    def __init__(self, *args, **kwargs):
        # TODO: use PDB object in aria
        # TODO: write dataframe in a separated file
        self.check_type = False
        super(PDBFile, self).__init__(*args, regex=self.pdbreg, filetype="pdb",
                                      **kwargs)

    def create_map(self, protein, contactdef, groupby_method="min", scsc=None,
                   flaglist=None, sym=True):
        resmap = ResAtmMap(protein.aa_sequence.sequence, mtype='distance',
                           flaglist=flaglist,
436
                           seqidx=protein.index, desc=self.filetype)
fabrice's avatar
fabrice committed
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
        resmap[:] = self.update_map(resmap, sym=sym)
        logger.debug("pdb distance map:\n%s" % resmap)
        self.mapdict["alldistmap"] = resmap
        self.mapdict["distmap"] = resmap.reduce(groupby=groupby_method)
        self.mapdict["allcontactmap"] = resmap.contact_map(
            contactdef=contactdef, scsc_min=scsc)
        self.mapdict["contactmap"] = self.mapdict["allcontactmap"].reduce()

    def update_map(self, resmap, sym=True):
        # Map only on heavy atoms
        # TODO: check if same sequence in pdb file
        logger.info("Updating distance map with pdb file")
        newmap = resmap.copy()
        heavylist = []
        error_list = set()
        for atom in self.lines:
            if resmap.heavy_reg.match(self.lines[atom]['name'].strip()):
                heavylist.append(atom)

        # For each heavy atom
        for x, atomx in enumerate(heavylist):
            for atomy in heavylist[x:]:
                # TODO: Check first residue number in pdb file
                indx = "%03d-%s" % (int(self.lines[atomx]['resSeq']),
                                    self.lines[atomx]['resName'].strip()), \
                       self.lines[atomx]['name'].strip()
                indy = "%03d-%s" % (int(self.lines[atomy]['resSeq']),
                                    self.lines[atomy]['resName'].strip()), \
                       self.lines[atomy]['name'].strip()
                coordx = (float(self.lines[atomx]['x']),
                          float(self.lines[atomx]['y']),
                          float(self.lines[atomx]['z']))
                coordy = (float(self.lines[atomy]['x']),
                          float(self.lines[atomy]['y']),
                          float(self.lines[atomy]['z']))

                dist = distance.euclidean(coordx, coordy)
                if indx[0] in list(resmap.index.get_level_values("residuex"))\
                        and indy[0] in list(resmap.index.get_level_values("residuex")):
                    logger.debug("Update distance value (%s, %s)" % (indx, indy))
                    newmap.at[indx, indy] = dist
                    if sym:
                        # If symmetric matrix
                        newmap.at[indy, indx] = dist
                elif indx[0] not in list(resmap.index.get_level_values("residuex")):
                    error_list.add(indx[0])
                elif indy[0] not in list(resmap.index.get_level_values("residuex")):
                    error_list.add(indy[0])
        if error_list:
            # Listing related humanidx in the initial df
            idxlist = list(resmap.index.get_level_values("residuex"))
            erridx = [idx.split("-")[0] for idx in list(error_list)]
            missidx = list(set([idx for idx in idxlist
                                if idx.split("-")[0] in erridx]))
            for idx in missidx:
                newmap.loc[idx] = None
                if sym:
                    newmap.loc[:][idx] = None
            logger.error("Can't update pdb distance map for pos in pdb file "
                         "%s with %s" % (list(error_list), missidx))

        return newmap


class DistanceMapFile(MapFile):
    def __init__(self, filepath, filetype):
        super(MapFile).__init__(filepath, filetype)
        raise NotImplementedError

    def create_map(self, aa_seq, contactdef, **kwargs):
        pass

    # Native dist
    def update_map(self, resmap):
        pass
        # Construit map avec la liste de residus +  infos de distance du fichier
        # return DistanceMap


class ProtFileListReader:
    def __init__(self, cont_def=5.0):
        self.filelist = []
        self.contactdef = cont_def

    def clear(self):
        # TODO: Init supprime bien les fichiers du cache ?
        self.__init__(self.contactdef)

    def add_file(self, filepathlist, filetypelist=None):
        filepathlist = [filepathlist] if type(
            filepathlist) != list else filepathlist
        filetypelist = [filetypelist] if type(
            filetypelist) != list else filetypelist
        if not filetypelist or len(filepathlist) != len(filetypelist):
            filetypelist = [os.path.splitext(_)[1][1:] for _ in filepathlist]
        logger.info("Reader focused on file(s) %s %s" % (filepathlist,
                                                         filetypelist))
        for i, filepath in enumerate(filepathlist):
            if os.path.exists(filepath):
                # TODO: check_type functionstr
                logger.debug("Adding %s file to watchlist" % filetypelist[i])
                if filetypelist[i].lower() in ("pdb", "distfile"):
                    if os.path.splitext(filepath)[1][1:] == "pdb":
                        self.filelist.append(PDBFile(filepath))
                    else:
                        self.filelist.append(DistanceMapFile(filepath,
                                                             filetypelist[i]))
                else:
                    self.filelist.append(ContactMapFile(filepath,
                                                        filetypelist[i]))
                if not self.filelist[-1].regex:
                    logger.warning("Can't read %s" % filepath)
                    self.filelist.pop()

    def read(self, filepathlist, filetypelist=None, protein=None, scsc=None,
             **kwargs):
        self.clear()
        self.add_file(filepathlist, filetypelist=filetypelist)
        for fo in self.filelist:
            fo.read(protein=protein, contactdef=self.contactdef,
                    scsc=scsc, **kwargs)