De-lint parameters.py.

This commit is contained in:
Nathan Baker
2020-05-25 09:58:51 -07:00
parent c7c626791a
commit 32fbb30464

View File

@@ -1,232 +1,262 @@
"""Holds parameters and settings."""
from __future__ import division import pkg_resources
from __future__ import print_function
import math
import propka.lib as lib import propka.lib as lib
import sys, os
from propka.lib import info, warning from propka.lib import info, warning
import pkg_resources
# names and types of all key words in configuration file # names and types of all key words in configuration file
matrices = ['interaction_matrix'] MATRICES = ['interaction_matrix']
PAIR_WISE_MATRICES = ['sidechain_cutoffs']
pair_wise_matrices = ['sidechain_cutoffs'] NUMBER_DICTIONARIES = ['VanDerWaalsVolume', 'charge', 'model_pkas', 'ions',
number_dictionaries = ['VanDerWaalsVolume','charge','model_pkas','ions',
'valence_electrons', 'custom_model_pkas'] 'valence_electrons', 'custom_model_pkas']
LIST_DICTIONARIES = ['backbone_NH_hydrogen_bond', 'backbone_CO_hydrogen_bond']
list_dictionaries = ['backbone_NH_hydrogen_bond','backbone_CO_hydrogen_bond'] STRING_DICTIONARIES = ['protein_group_mapping']
STRING_LISTS = ['ignore_residues', 'angular_dependent_sidechain_interactions',
string_dictionaries = ['protein_group_mapping']
string_lists = ['ignore_residues','angular_dependent_sidechain_interactions',
'acid_list', 'base_list', 'exclude_sidechain_interactions', 'acid_list', 'base_list', 'exclude_sidechain_interactions',
'backbone_reorganisation_list', 'write_out_order'] 'backbone_reorganisation_list', 'write_out_order']
DISTANCES = ['desolv_cutoff', 'buried_cutoff', 'coulomb_cutoff1',
distances = ['desolv_cutoff','buried_cutoff','coulomb_cutoff1','coulomb_cutoff2'] 'coulomb_cutoff2']
PARAMETERS = ['Nmin', 'Nmax', 'desolvationSurfaceScalingFactor',
parameters = ['Nmin','Nmax','desolvationSurfaceScalingFactor','desolvationPrefactor', 'desolvationPrefactor', 'desolvationAllowance', 'coulomb_diel',
'desolvationAllowance','coulomb_diel','COO_HIS_exception','OCO_HIS_exception', 'COO_HIS_exception', 'OCO_HIS_exception', 'CYS_HIS_exception',
'CYS_HIS_exception','CYS_CYS_exception','min_ligand_model_pka','max_ligand_model_pka', 'CYS_CYS_exception', 'min_ligand_model_pka',
'include_H_in_interactions','coupling_max_number_of_bonds', 'max_ligand_model_pka', 'include_H_in_interactions',
'coupling_max_number_of_bonds',
'min_bond_distance_for_hydrogen_bonds', 'coupling_penalty', 'min_bond_distance_for_hydrogen_bonds', 'coupling_penalty',
'shared_determinants','common_charge_centre','hide_penalised_group', 'remove_penalised_group', 'shared_determinants', 'common_charge_centre',
'max_intrinsic_pka_diff','min_interaction_energy','max_free_energy_diff','min_swap_pka_shift', 'hide_penalised_group', 'remove_penalised_group',
'min_pka','max_pka','sidechain_interaction'] 'max_intrinsic_pka_diff', 'min_interaction_energy',
'max_free_energy_diff', 'min_swap_pka_shift', 'min_pka',
strings = ['version','output_file_tag','ligand_typing','pH','reference'] 'max_pka', 'sidechain_interaction']
STRINGS = ['version', 'output_file_tag', 'ligand_typing', 'pH', 'reference']
class Parameters: class Parameters:
def __init__(self, parameter_file): """PROPKA parameter class."""
def __init__(self, parameter_file):
"""Initialize parameter class.
Args:
parameter_file: file with parameters
"""
# TODO - need to define all members explicitly
self.model_pkas = {}
self.interaction_matrix = InteractionMatrix("interaction_matrix")
self.sidechain_cutoffs = None
# TODO - it would be nice to rename these but they're defined everywhere
self.COO_HIS_exception = None
self.OCO_HIS_exception = None
self.CYS_HIS_exception = None
self.CYS_CYS_exception = None
# These functions set up remaining data structures implicitly
self.set_up_data_structures() self.set_up_data_structures()
self.read_parameters(parameter_file) self.read_parameters(parameter_file)
#self.print_interaction_parameters() def read_parameters(self, file_):
#self.print_interaction_parameters_latex() """Read parameters from file.
#####self.print_interactions_latex()
#sys.exit(0)
Args:
return file_: file to read
"""
def read_parameters(self, file):
# try to locate the parameters file # try to locate the parameters file
try: try:
ifile = pkg_resources.resource_filename(__name__, file) ifile = pkg_resources.resource_filename(__name__, file_)
input = lib.open_file_for_reading(ifile) input_ = lib.open_file_for_reading(ifile)
except: except (IOError, FileNotFoundError, ValueError):
input = lib.open_file_for_reading(file) input_ = lib.open_file_for_reading(file_)
for line in input_:
for line in input:
self.parse_line(line) self.parse_line(line)
return
def parse_line(self, line): def parse_line(self, line):
"""Parse parameter file line."""
# first, remove comments # first, remove comments
comment_pos = line.find('#') comment_pos = line.find('#')
if comment_pos != -1: if comment_pos != -1:
line = line[:comment_pos] line = line[:comment_pos]
# split the line into words # split the line into words
words = line.split() words = line.split()
if len(words) == 0: if len(words) == 0:
return return
# parse the words # parse the words
if len(words)==3 and words[0] in number_dictionaries: if len(words) == 3 and words[0] in NUMBER_DICTIONARIES:
self.parse_to_number_dictionary(words) self.parse_to_number_dictionary(words)
elif len(words)==2 and words[0] in string_lists: elif len(words) == 2 and words[0] in STRING_LISTS:
self.parse_to_string_list(words) self.parse_to_string_list(words)
elif len(words)==2 and words[0] in distances: elif len(words) == 2 and words[0] in DISTANCES:
self.parse_distance(words) self.parse_distance(words)
elif len(words)==2 and words[0] in parameters: elif len(words) == 2 and words[0] in PARAMETERS:
self.parse_parameter(words) self.parse_parameter(words)
elif len(words)==2 and words[0] in strings: elif len(words) == 2 and words[0] in STRINGS:
self.parse_string(words) self.parse_string(words)
elif len(words)>2 and words[0] in list_dictionaries: elif len(words) > 2 and words[0] in LIST_DICTIONARIES:
self.parse_to_list_dictionary(words) self.parse_to_list_dictionary(words)
elif words[0] in matrices+pair_wise_matrices: elif words[0] in MATRICES+PAIR_WISE_MATRICES:
self.parse_to_matrix(words) self.parse_to_matrix(words)
elif len(words)==3 and words[0] in string_dictionaries: elif len(words) == 3 and words[0] in STRING_DICTIONARIES:
self.parse_to_string_dictionary(words) self.parse_to_string_dictionary(words)
#info(words)
return
def parse_to_number_dictionary(self, words): def parse_to_number_dictionary(self, words):
exec('self.%s[\'%s\'] = %s'%tuple(words)) """Parse field to number dictionary.
return
Args:
words: strings to parse.
"""
dict_ = getattr(self, words[0])
key = words[1]
value = words[2]
dict_[key] = float(value)
def parse_to_string_dictionary(self, words): def parse_to_string_dictionary(self, words):
exec('self.%s[\'%s\'] = \'%s\''%tuple(words)) """Parse field to string dictionary.
return
Args:
words: strings to parse
"""
dict_ = getattr(self, words[0])
key = words[1]
value = words[2]
dict_[key] = value
def parse_to_list_dictionary(self, words): def parse_to_list_dictionary(self, words):
exec('if not \'%s\' in self.%s.keys(): self.%s[\'%s\'] = []'%(words[1],words[0],words[0],words[1])) """Parse field to list dictionary.
for word in words[2:]:
exec('self.%s[\'%s\'].append(%s)'%(words[0],words[1],word))
return Args:
words: strings to parse.
"""
dict_ = getattr(self, words[0])
key = words[1]
if not key in dict_:
dict_[key] = []
for value in words[2:]:
if isinstance(value, list):
dict_[key].append([float(x) for x in value])
dict_[key].append(float(value))
def parse_to_string_list(self, words): def parse_to_string_list(self, words):
exec('self.%s.append(\'%s\')'%tuple(words)) """Parse field to string list.
return
Args:
words: strings to parse
"""
list_ = getattr(self, words[0])
value = words[1]
list_.append(value)
def parse_to_matrix(self, words): def parse_to_matrix(self, words):
exec('self.%s.add(%s)'%(words[0],tuple(words[1:]))) """Parse field to matrix.
return
Args:
words: strings to parse
"""
matrix = getattr(self, words[0])
value = tuple(words[1:])
matrix.add(value)
def parse_distance(self, words): def parse_distance(self, words):
# float check needed """Parse field to distance.
exec('self.%s = %s'%tuple(words))
exec('self.%s_squared = pow(%s,2)'%tuple(words)) Args:
return words: strings to parse
"""
value = float(words[1])
setattr(self, words[0], value)
value_sq = value*value
setattr(self, "%s_squared" % words[0], value_sq)
def parse_parameter(self, words): def parse_parameter(self, words):
exec('self.%s = %s'%tuple(words)) """Parse field to parameters.
return
Args:
words: strings to parse
"""
value = float(words[1])
setattr(self, words[0], value)
def parse_string(self, words): def parse_string(self, words):
#info('self.%s = \'%s\''%tuple(words)) """Parse field to strings.
exec('self.%s = \'%s\''%tuple(words))
return
Args:
words: strings to parse
"""
setattr(self, words[0], words[1])
def set_up_data_structures(self): def set_up_data_structures(self):
for key_word in number_dictionaries+list_dictionaries+string_dictionaries: """Set up internal data structures.
exec('self.%s = {}'%key_word)
for key_word in string_lists:
exec('self.%s = []'%key_word)
for key_word in strings:
exec('self.%s = \'\''%key_word)
for key_word in matrices:
exec('self.%s = Interaction_matrix(\'%s\')'%(key_word,key_word))
for key_word in pair_wise_matrices:
exec('self.%s =Pair_wise_matrix(\'%s\')'%(key_word,key_word))
return TODO - it would be better to make these assignments explicit in __init__.
"""
for key_word in NUMBER_DICTIONARIES + LIST_DICTIONARIES \
+ STRING_DICTIONARIES:
setattr(self, key_word, {})
for key_word in STRING_LISTS:
setattr(self, key_word, [])
for key_word in STRINGS:
setattr(self, key_word, "")
for key_word in MATRICES:
matrix = InteractionMatrix(key_word)
setattr(self, key_word, matrix)
for key_word in PAIR_WISE_MATRICES:
matrix = PairwiseMatrix(key_word)
setattr(self, key_word, matrix)
def print_interaction_parameters(self): def print_interaction_parameters(self):
"""Print interaction parameters."""
info('--------------- Model pKa values ----------------------') info('--------------- Model pKa values ----------------------')
for k in self.model_pkas.keys(): for k in self.model_pkas:
info('%3s %8.2f' % (k, self.model_pkas[k])) info('%3s %8.2f' % (k, self.model_pkas[k]))
info('') info('')
info('--------------- Interactions --------------------------') info('--------------- Interactions --------------------------')
agroups = ['COO', 'HIS', 'CYS', 'TYR', 'SER', 'N+', 'LYS', 'AMD', 'ARG', 'TRP', 'ROH', 'CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP', 'SH'] agroups = ['COO', 'HIS', 'CYS', 'TYR', 'SER', 'N+', 'LYS', 'AMD',
lgroups = ['CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP', 'SH'] 'ARG', 'TRP', 'ROH', 'CG', 'C2N', 'N30', 'N31', 'N32',
'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM',
map = { 'N1', 'O2', 'OP', 'SH']
'CG' :['ARG'], lgroups = ['CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO',
'C2N':['ARG'], 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP', 'SH']
'N30':['N+','LYS'], map_ = {'CG': ['ARG'], 'C2N': ['ARG'], 'N30': ['N+', 'LYS'],
'N31':['N+','LYS'], 'N31': ['N+', 'LYS'], 'N32': ['N+', 'LYS'], 'N33': ['N+', 'LYS'],
'N32':['N+','LYS'], 'NAR': ['HIS'], 'OCO': ['COO'], 'OP': [], 'SH': ['CYS'],
'N33':['N+','LYS'] , 'NP1': [], 'OH': ['ROH'], 'O3': [], 'CL': [], 'F': [],
'NAR':['HIS'], 'NAM': ['AMD'], 'N1': [], 'O2': []}
'OCO':['COO'], for group1 in agroups:
'OP' :[],#['TYR','SER'], for group2 in lgroups:
'SH' :['CYS'] , interaction = '%3s %3s %1s %4s %4s' \
'NP1':[], % (group1, group2, self.interaction_matrix[group1][group2], \
'OH' :['ROH'], self.sidechain_cutoffs.get_value(group1, group2)[0], \
'O3' :[] , self.sidechain_cutoffs.get_value(group1, group2)[1])
'CL' :[],
'F' :[],
'NAM':['AMD'],
'N1' :[],
'O2' :[]}
for g1 in agroups:
for g2 in lgroups:
interaction = '%3s %3s %1s %4s %4s'%(g1,g2,
self.interaction_matrix[g1][g2],
self.sidechain_cutoffs.get_value(g1,g2)[0],
self.sidechain_cutoffs.get_value(g1,g2)[1])
map_interaction = '' map_interaction = ''
if g2 in map: if group2 in map_:
for m in map[g2]: for val in map_[group2]:
map_interaction += '|%3s %3s %1s %4s %4s'%(g1,m, map_interaction += '|%3s %3s %1s %4s %4s' \
self.interaction_matrix[g1][m], % (group1, val, \
self.sidechain_cutoffs.get_value(g1,m)[0], self.interaction_matrix[group1][val], \
self.sidechain_cutoffs.get_value(g1,m)[1]) self.sidechain_cutoffs.get_value(group1, val)[0], \
if self.interaction_matrix[g1][m] != self.interaction_matrix[g1][g2]: self.sidechain_cutoffs.get_value(group1, val)[1])
if self.interaction_matrix[group1][val] \
!= self.interaction_matrix[group1][group2]:
map_interaction += '* ' map_interaction += '* '
if self.sidechain_cutoffs.get_value(g1,m)[0] != self.sidechain_cutoffs.get_value(g1,g2)[0] or \ if self.sidechain_cutoffs.get_value(group1, val)[0] \
self.sidechain_cutoffs.get_value(g1,m)[1] != self.sidechain_cutoffs.get_value(g1,g2)[1]: != self.sidechain_cutoffs.get_value(group1, group2)[0] \
or self.sidechain_cutoffs.get_value(group1, val)[1] \
!= self.sidechain_cutoffs.get_value(group1, group2)[1]:
map_interaction += '! ' map_interaction += '! '
else: else:
map_interaction += ' ' map_interaction += ' '
if len(map[g2])==0 and (self.sidechain_cutoffs.get_value(g1,g2)[0] !=3 or self.sidechain_cutoffs.get_value(g1,g2)[1] != 4): if len(map_[group2]) == 0 \
and (self.sidechain_cutoffs.get_value(group1, group2)[0] \
!= 3 or self.sidechain_cutoffs.get_value(group1, group2)[1] != 4):
map_interaction += '? ' map_interaction += '? '
info(interaction, map_interaction) info(interaction, map_interaction)
if group1 == group2:
if g1==g2:
break break
info('-') info('-')
info('--------------- Exceptions ----------------------------') info('--------------- Exceptions ----------------------------')
info('COO-HIS', self.COO_HIS_exception) info('COO-HIS', self.COO_HIS_exception)
info('OCO-HIS', self.OCO_HIS_exception) info('OCO-HIS', self.OCO_HIS_exception)
info('CYS-HIS', self.CYS_HIS_exception) info('CYS-HIS', self.CYS_HIS_exception)
info('CYS-CYS', self.CYS_CYS_exception) info('CYS-CYS', self.CYS_CYS_exception)
info('--------------- Mapping -------------------------------') info('--------------- Mapping -------------------------------')
info(""" info("""
Titratable: Titratable:
@@ -251,45 +281,19 @@ NAM
N1 N1
O2 O2
""") """)
return
def print_interaction_parameters_latex(self): def print_interaction_parameters_latex(self):
# info('--------------- Model pKa values ----------------------') """Print interaction parameters in LaTeX format."""
# for k in self.model_pkas.keys(): # TODO - if these lists and dictionaries are the same as above, then
# info('%3s %8.2f'%(k,self.model_pkas[k])) # should be constants at the level of the module
agroups = ['COO', 'HIS', 'CYS', 'TYR', 'SER', 'N+', 'LYS', 'AMD',
# info('') 'ARG', 'TRP', 'ROH', 'CG', 'C2N', 'N30', 'N31', 'N32',
# info('--------------- Interactions --------------------------') 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM',
agroups = ['COO', 'HIS', 'CYS', 'TYR', 'SER', 'N+', 'LYS', 'AMD', 'ARG', 'TRP', 'ROH', 'CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP', 'SH'] 'N1', 'O2', 'OP', 'SH']
lgroups = ['CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP', 'SH'] lgroups = ['CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO',
'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP',
map = { 'SH']
'CG' :['ARG'], str_ = """
'C2N':['ARG'],
'N30':['N+','LYS'],
'N31':['N+','LYS'],
'N32':['N+','LYS'],
'N33':['N+','LYS'] ,
'NAR':['HIS'],
'OCO':['COO'],
'OP' :[],#['TYR','SER'],
'SH' :['CYS'] ,
'NP1':['AMD'],
'OH' :['ROH'],
'O3' :[] ,
'CL' :[],
'F' :[],
'NAM':[],
'N1' :[],
'O2' :[]}
s = """
\\begin{longtable}{lllll} \\begin{longtable}{lllll}
\\caption{Ligand interaction parameters. For interactions not listed, the default value of %s is applied.} \\caption{Ligand interaction parameters. For interactions not listed, the default value of %s is applied.}
\\label{tab:ligand_interaction_parameters}\\\\ \\label{tab:ligand_interaction_parameters}\\\\
@@ -313,32 +317,31 @@ Group1 & Group2 & Interaction & c1 &c2 \\\\
\\endlastfoot \\endlastfoot
""" % (self.sidechain_cutoffs.default) """ % (self.sidechain_cutoffs.default)
for g1 in agroups: for group1 in agroups:
for g2 in lgroups: for group2 in lgroups:
if self.interaction_matrix[g1][g2]=='-': if self.interaction_matrix[group1][group2] == '-':
continue continue
if self.sidechain_cutoffs.get_value(g1,g2)==self.sidechain_cutoffs.default: if self.sidechain_cutoffs.get_value(group1, group2) \
== self.sidechain_cutoffs.default:
continue continue
str_ += '%3s & %3s & %1s & %4s & %4s\\\\ \n'\
% (group1, group2, \
s+= '%3s & %3s & %1s & %4s & %4s\\\\ \n'%(g1,g2, self.interaction_matrix[group1][group2], \
self.interaction_matrix[g1][g2], self.sidechain_cutoffs.get_value(group1, group2)[0], \
self.sidechain_cutoffs.get_value(g1,g2)[0], self.sidechain_cutoffs.get_value(group1, group2)[1])
self.sidechain_cutoffs.get_value(g1,g2)[1]) if group1 == group2:
if g1==g2:
break break
str_ += ' \\end{longtable}\n'
s += ' \\end{longtable}\n' info(str_)
info(s)
return
def print_interactions_latex(self): def print_interactions_latex(self):
agroups = ['COO', 'HIS', 'CYS', 'TYR', 'SER', 'N+', 'LYS', 'AMD', 'ARG', 'TRP', 'ROH', 'CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP', 'SH'] """Print interactions in LaTeX."""
lgroups = ['CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP', 'SH'] # TODO - are these the same lists as above? Convert to module constants.
agroups = ['COO', 'HIS', 'CYS', 'TYR', 'SER', 'N+', 'LYS', 'AMD',
'ARG', 'TRP', 'ROH', 'CG', 'C2N', 'N30', 'N31', 'N32',
s = """ 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM',
'N1', 'O2', 'OP', 'SH']
str_ = """
\\begin{longtable}{%s} \\begin{longtable}{%s}
\\caption{Ligand interaction parameters. For interactions not listed, the default value of %s is applied.} \\caption{Ligand interaction parameters. For interactions not listed, the default value of %s is applied.}
\\label{tab:ligand_interaction_parameters}\\\\ \\label{tab:ligand_interaction_parameters}\\\\
@@ -362,173 +365,185 @@ Group1 & Group2 & Interaction & c1 &c2 \\\\
\\endlastfoot \\endlastfoot
""" % ('l'*len(agroups), self.sidechain_cutoffs.default) """ % ('l'*len(agroups), self.sidechain_cutoffs.default)
for g1 in agroups: for group1 in agroups:
for g2 in agroups: for group2 in agroups:
str_ += '%3s & %3s & %1s & %4s & %4s\\\\ \n' \
s+= '%3s & %3s & %1s & %4s & %4s\\\\ \n'%(g1,g2, % (group1, group2, \
self.interaction_matrix[g1][g2], self.interaction_matrix[group1][group2], \
self.sidechain_cutoffs.get_value(g1,g2)[0], self.sidechain_cutoffs.get_value(group1, group2)[0], \
self.sidechain_cutoffs.get_value(g1,g2)[1]) self.sidechain_cutoffs.get_value(group1, group2)[1])
if group1 == group2:
if g1==g2:
break break
str_ += ' \\end{longtable}\n'
s += ' \\end{longtable}\n' info(str_)
info(s)
return
class InteractionMatrix:
"""Interaction matrix class."""
class Interaction_matrix:
def __init__(self, name): def __init__(self, name):
"""Initialize with name of matrix.
Args:
name: name of interaction matrix
"""
self.name = name self.name = name
self.value = None
self.ordered_keys = [] self.ordered_keys = []
self.dictionary = {} self.dictionary = {}
return
def add(self, words): def add(self, words):
"""Add values to matrix.
Args:
words: values to add
"""
new_group = words[0] new_group = words[0]
self.ordered_keys.append(new_group) self.ordered_keys.append(new_group)
if not new_group in self.dictionary.keys(): if not new_group in self.dictionary.keys():
self.dictionary[new_group] = {} self.dictionary[new_group] = {}
for i, group in enumerate(self.ordered_keys):
for i in range(len(self.ordered_keys)):
group = self.ordered_keys[i]
if len(words) > i+1: if len(words) > i+1:
try: try:
exec('self.value = %s'%words[i+1]) self.value = float(words[i+1])
except: except ValueError:
self.value = words[i+1] self.value = words[i+1]
self.dictionary[group][new_group] = self.value self.dictionary[group][new_group] = self.value
self.dictionary[new_group][group] = self.value self.dictionary[new_group][group] = self.value
return
def get_value(self, item1, item2): def get_value(self, item1, item2):
"""Get specific matrix value.
Args:
item1: matrix row index
item2: matrix column index
Returns:
matrix value or None
"""
try: try:
return self.dictionary[item1][item2] return self.dictionary[item1][item2]
except: except KeyError:
return None return None
def __getitem__(self, group): def __getitem__(self, group):
"""Get specific group from matrix.
Args:
group: group to get
"""
if group not in self.dictionary.keys(): if group not in self.dictionary.keys():
raise Exception('%s not found in interaction matrix %s'%(group,self.name)) str_ = '%s not found in interaction matrix %s' % (group, self.name)
raise KeyError(str_)
return self.dictionary[group] return self.dictionary[group]
def keys(self): def keys(self):
"""Get keys from matrix.
Returns:
dictionary key list
"""
return self.dictionary.keys() return self.dictionary.keys()
def __str__(self): def __str__(self):
s = ' ' str_ = ' '
for k1 in self.ordered_keys: for key in self.ordered_keys:
s+='%3s '%k1 str_ += '%3s ' % key
s+='\n' str_ += '\n'
for k1 in self.ordered_keys: for key1 in self.ordered_keys:
s+='%3s '%k1 str_ += '%3s ' % key1
for k2 in self.ordered_keys: for key2 in self.ordered_keys:
s+='%3s '%self[k1][k2] str_ += '%3s ' % self[key1][key2]
s+='\n' str_ += '\n'
return str_
return s
# ks = ['COO', 'SER', 'ARG', 'LYS', 'HIS', 'AMD', 'CYS', 'TRP','ROH','TYR','N+','CG', 'C2N', 'N30', 'N31', 'N32', 'N33', 'NAR', 'OCO', 'NP1', 'OH', 'O3', 'CL', 'F', 'NAM', 'N1', 'O2', 'OP', 'SH']
# p = ''
# n=0
# for i in range(len(ks)):
# for j in range(i,len(ks)):
# if not [0.0,0.0]==self[ks[i]][ks[j]]:
# if not [3.0,4.0]==self[ks[i]][ks[j]]:
# p+='sidechain_cutoff %3s %3s %s\n'%(ks[i],ks[j],self[ks[i]][ks[j]])
# n+=1
# info('total',n,len(ks))
# return p
class PairwiseMatrix:
"""Pairwise interaction matrix class."""
class Pair_wise_matrix:
def __init__(self, name): def __init__(self, name):
"""Initialize pairwise matrix.
Args:
name: name of pairwise interaction
"""
self.name = name self.name = name
self.dictionary = {} self.dictionary = {}
self.default = [0.0, 0.0] self.default = [0.0, 0.0]
return
def add(self, words): def add(self, words):
"""Add information to the matrix.
TODO - this function unnecessarily bundles arguments into a tuple
Args:
words: tuple with assignment information and value
"""
# assign the default value # assign the default value
if len(words) == 3 and words[0] == 'default': if len(words) == 3 and words[0] == 'default':
self.default = [float(words[1]), float(words[2])] self.default = [float(words[1]), float(words[2])]
return return
# assign non-default values # assign non-default values
g1 = words[0] group1 = words[0]
g2 = words[1] group2 = words[1]
v = [float(words[2]), float(words[3])] value = [float(words[2]), float(words[3])]
self.insert(group1, group2, value)
self.insert(group2, group1, value)
self.insert(g1,g2,v) def insert(self, key1, key2, value):
self.insert(g2,g1,v) """Insert value into matrix.
return Args:
key1: first matrix key (row)
def insert(self, k1,k2,v): key2: second matrix key (column)
value: value to insert
if k1 in self.dictionary.keys() and k2 in self.dictionary[k1].keys(): """
if k1!=k2: if key1 in self.dictionary and key2 in self.dictionary[key1]:
warning('Parameter value for %s, %s defined more than once' % (k1, k2)) if key1 != key2:
str_ = 'Parameter value for %s, %s defined more than once' \
if not k1 in self.dictionary: % (key1, key2)
self.dictionary[k1] = {} warning(str_)
if not key1 in self.dictionary:
self.dictionary[k1][k2] =v self.dictionary[key1] = {}
self.dictionary[key1][key2] = value
return
def get_value(self, item1, item2): def get_value(self, item1, item2):
"""Get specified value from matrix.
Args:
item1: row index
item2: column index
Returns:
matrix value (or default)
"""
try: try:
return self.dictionary[item1][item2] return self.dictionary[item1][item2]
except: except KeyError:
return self.default return self.default
def __getitem__(self, group): def __getitem__(self, group):
"""Get item from matrix corresponding to specific group.
Args:
group: group to retrieve
Returns:
matrix information
"""
if group not in self.dictionary.keys(): if group not in self.dictionary.keys():
raise Exception('%s not found in interaction matrix %s'%(group,self.name)) str_ = '%s not found in interaction matrix %s' % (group, self.name)
raise KeyError(str_)
return self.dictionary[group] return self.dictionary[group]
def keys(self): def keys(self):
"""Get keys from matrix.
Returns:
dictionary key list
"""
return self.dictionary.keys() return self.dictionary.keys()
def __str__(self): def __str__(self):
s='' str_ = ''
for k1 in self.keys(): for key1 in self.keys():
for k2 in self[k1].keys(): for key2 in self[key1].keys():
s += '%s %s %s\n'%(k1,k2,self[k1][k2]) str_ += '%s %s %s\n' % (key1, key2, self[key1][key2])
return str_
return s