Solutions to the exercises of part 5

Matrix classes

import Numeric;  N = Numeric
import LinearAlgebra; LA = LinearAlgebra

class Matrix:

    def __init__(self, array):
	if type(array) != type(N.array([0])) or len(array.shape) != 2:
	    raise ValueError, "argument not a rank-2 array"
	self.array = array

    def __str__(self):
	return str(self.array)

    def __repr__(self):
	return 'Matrix:\n' + str(self.array)

    def __add__(self, other_matrix):
	return Matrix(self.array+other_matrix.array)

    def __sub__(self, other_matrix):
	return Matrix(self.array-other_matrix.array)

    def __mul__(self, other_matrix):
	return Matrix(N.dot(self.array, other_matrix.array))

    def generalized_inverse(self):
	return Matrix(LA.generalized_inverse(self.array))


class SquareMatrix(Matrix):

    def __init__(self, array):
	Matrix.__init__(self, array)
	if self.array.shape[0] != self.array.shape[1]:
	    raise ValueError, "argument not a square matrix"

    def inverse(self):
	return SquareMatrix(LA.inverse(self.array))

    def eigenvalues(self):
	return LA.eigenvalues(self.array)

Peptide mass calculation

import string

class Residue:

    residue_name = {'a': 'ala', 'r': 'arg', 'n': 'asn', 'd': 'asp', 'c': 'cys',
		    'q': 'gln', 'e': 'glu', 'g': 'gly', 'h': 'his', 'i': 'ile',
		    'l': 'leu', 'k': 'lys', 'm': 'met', 'f': 'phe', 'p': 'pro',
		    's': 'ser', 't': 'thr', 'w': 'trp', 'y': 'tyr', 'v': 'val'}

    residue_mass = {'ala': 71.0790184654, 'arg': 157.196106437,
		    'asn': 114.104059219, 'asp': 114.080688839,
		    'cys': 103.143406585, 'gln': 128.131048075,
		    'glu': 128.107677695, 'gly': 57.0520296093,
		    'his': 137.141527428, 'ile': 113.159985034,
		    'leu': 113.159985034, 'lys': 129.182660137,
		    'met': 131.197384297, 'phe': 147.17714379,
		    'pro': 97.1170442246, 'ser': 87.0783231891,
		    'thr': 101.105312045, 'trp': 186.213916723,
		    'tyr': 163.176448514, 'val': 99.1329961777}

    def __init__(self, name):
	name = string.lower(name)
	if len(name) == 1:
	    name = self.residue_name[name]
	self.name = name

    def mass(self):
	return self.residue_mass[self.name]


class PeptideChain:

    terminus_mass = 18.0152566767

    def __init__(self, sequence):
	self.sequence = map(Residue, sequence)

    def mass(self):
	total_mass = self.terminus_mass
	for residue in self.sequence:
	    total_mass = total_mass + residue.mass()
	return total_mass


# Example:
print PeptideChain('AEG').mass()
print PeptideChain(['ala', 'arg', 'gly', 'his']).mass()

Table of Contents