matblas-Substitutionsmatrizen in Python lesen
English
Deutsch
Problem:
Du möchtest Substitutionsmatrizen im matblas-Format einlesen, z.B. diese BLOSUM62 von NCBI, in ein numpy-ndarray.
Lösung
Verwende dieses Snippet:
read_matblas.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import with_statement
import numpy
__author__ = "Uli Köhler"
__license__ = "Apache License v2.0"
__version__ = "1.0"
def readMatblasAlignmentMatrix(filename):
"""
Liest eine Substitutionsmatrix im matblas-Format.
Keyword-Argumente:
filename: Der Dateiname, aus dem die Matrix gelesen werden soll
Gibt ein Tupel (Spalten-/Zeilen-Liste, numpy-Substitutionsmatrix) zurück
"""
with open(filename) as infile:
currentRow = 0
for line in infile:
if line.startswith("#"): continue
elif line.startswith(" "): #Spaltenindikator
columns = line.split()
matrix = numpy.empty((len(columns), len(columns)), dtype=numpy.int32)
else: #Matrixzeile
parts = line.split()
assert(len(parts) == len(columns) + 1)
#Annehmen, dass Zeilen in derselben Reihenfolge wie Spalten sind
assert(columns[currentRow] == parts[0])
matrix[:,currentRow] = parts[1:]
currentRow += 1
return (columns, matrix)Check out similar posts by category:
Python
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow