-
Notifications
You must be signed in to change notification settings - Fork 77
/
Copy pathall_classes.py
2803 lines (2385 loc) · 139 KB
/
all_classes.py
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
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
436
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python3
#
# all_classes.py
#
# Copyright 2019 Luan Carvalho Martins <luancarvalho@ufmg.br>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
import os.path
import tempfile
import networkx
import numpy
from collections import OrderedDict
import os_util
import re
from copy import deepcopy
def namedlist(typename, field_names, defaults=(), types=()):
""" Returns a new subclass of list with named fields. Recipe by Sergey Shepelev at
https://code.activestate.com/recipes/578041-namedlist/ altered by Luan Carvalho Martins
:param str typename: name of the class
:param list field_names: list of fields
:param list defaults: right-to-left list of defaults
:param list types: list of types
:rtype: function
"""
if isinstance(field_names, str):
field_names = field_names.split()
fields_len = len(field_names)
if types:
if len(types) != fields_len:
raise TypeError("Expected {} types, got {}".format(len(types), fields_len))
class ResultType(list):
__slots__ = ('_parent',)
_fields = field_names
def _fixed_length_error(*args, **kwargs):
raise TypeError(u"Named list has fixed length")
append = _fixed_length_error
insert = _fixed_length_error
pop = _fixed_length_error
remove = _fixed_length_error
def sort(self):
raise TypeError(u"Sorting named list in place would corrupt field accessors. Use sorted(x)")
def _replace(self, **kwargs):
values = map(kwargs.pop, field_names, self)
if kwargs:
raise TypeError(u"Unexpected field names: {s!r}".format(kwargs.keys()))
if len(values) != fields_len:
raise TypeError(u"Expected {e} arguments, got {n}".format(
e=fields_len, n=len(values)))
return ResultType(*values)
def __repr__(self):
items_repr = ", ".join("{name}={value!r}".format(name=name, value=value)
for name, value in zip(field_names, self))
return "{typename}({items})".format(typename=typename, items=items_repr)
def __init__(self, *args, **kwargs):
self._parent = None
self.extend([None] * fields_len)
if len(args) + len(kwargs) + len(defaults) < len(field_names):
raise TypeError("__init__() missing {} required arguments"
"".format(len(field_names) - (len(args) + len(kwargs) + len(defaults))))
elif len(args) + len(kwargs) > len(field_names):
raise TypeError("__init__() takes {} positional arguments but {} were given"
"".format(len(field_names), len(args) + len(kwargs)))
[setattr(self, k, v) for k, v in zip(reversed(field_names), defaults)]
[setattr(self, k, v) for k, v in zip(field_names, args)]
[setattr(self, k, v) for k, v in kwargs.items()]
for v, t in zip(self, types):
if t is not False and type(v) != t:
raise TypeError("Unsupported operand type(s) __init__(): '{}' and '{}'".format(type(v), t))
def __deepcopy__(self, memodict={}):
return self.__class__(**{k: v for k, v in zip(field_names, self)})
def keys(self):
return self._fields[:]
ResultType.__name__ = typename
for i, name in enumerate(field_names):
fget = eval("lambda self: self[{0:d}]".format(i))
fset = eval("lambda self, value: self.__setitem__({0:d}, value)".format(i))
setattr(ResultType, name, property(fget, fset))
return ResultType
class Namespace(OrderedDict):
""" A simple ordered namespace class """
def __getattr__(self, item):
return self[item]
def __setattr__(self, key, value):
self[key] = value
def __str__(self):
items_data = []
for k, v in self.items():
if len(str(v)) < 50:
items_data.append('{}={}'.format(k, v))
else:
try:
items_data.append('<{} object at {} with len {}>'.format(v.__class__, hex(id(v)), len(v)))
except (TypeError, UnboundLocalError):
items_data.append('<{} object at {}>'.format(v.__class__, hex(id(v))))
this_str = 'Namespace({})'.format(', '.join(items_data))
return this_str
def __repr__(self):
return self.__str__()
class AntSolver:
""" Stores a network and use ACO to find a solution minimizing AntSolver.calculate_network_cost """
class Solution:
""" Stores solution data """
def __init__(self, network_graph, solution_cost, pheromone_multiplier=0):
""" Create a new instance of Solution
:param networkx.Graph network_graph: solution network
:param float solution_cost: solution cost
:param float pheromone_multiplier: pheromone multiplier used in run
:rtype: float
"""
self.graph = network_graph
self.cost = float(solution_cost)
self.pheromone_multiplier = pheromone_multiplier
@property
def cost_list(self):
""" List of all stored costs
:rtype: list
"""
if len(self._cost_list) != len(self.solutions):
self._cost_list = [each_cost.cost for each_cost in self.solutions]
return self._cost_list
@property
def mean_cost(self):
""" Mean value of all stored costs
:rtype: float
"""
return float(sum(self.cost_list)) / len(self.solutions)
@property
def best_solution(self):
""" Return the best solution found or False if no solution was stored
:rtype: AntSolver.Solution
"""
if len(self.cost_list) == 0:
return False
else:
this_index = self.cost_list.index(min(self.cost_list))
return self.solutions[this_index]
@property
def pheromone_intensity(self):
""" Intensity of pheromone to be deposited
:rtype: float
"""
return self._pheromone_intensity
@pheromone_intensity.setter
def pheromone_intensity(self, value):
if value >= 0.0:
self._pheromone_intensity = value
else:
raise ValueError('pheromone_intensity must be non-negative')
def calculate_network_cost(self, network_graph, decompose=False):
""" Calculates the network cost
:param networkx.Graph network_graph: network te be calculated
:param bool decompose: return the components to the final value
:rtype: network cost
"""
if self.length_exponent:
all_lengths = dict(networkx.all_pairs_shortest_path_length(network_graph))
lengths_matrix = numpy.array([j for i in all_lengths.values() for j in list(i.values())], dtype=float)
length_cost = numpy.sum(lengths_matrix ** self.length_exponent)
else:
length_cost = 0
if self.degree_multiplier != 0:
degree_cost = numpy.array(list(dict(networkx.degree(network_graph)).values()))
degree_cost = ((degree_cost - self.degree_target) ** self.degree_exponent).sum() * self.degree_multiplier
else:
degree_cost = 0
perturbation_cost = [i[2] ** self.perturbation_exponent for i in network_graph.edges(data='cost')]
perturbation_cost = self.perturbation_multiplier * numpy.array(perturbation_cost).sum()
if decompose is False:
return length_cost + perturbation_cost + degree_cost
else:
return {'total': length_cost + perturbation_cost + degree_cost,
'length': length_cost,
'perturbation': perturbation_cost,
'degree': degree_cost}
def run_multi_ants(self, runs, **kwargs):
""" Run several ants, pass all kwargs to run_ant
:param int runs: run this many ants
:rtype: list
"""
if runs <= 0:
raise ValueError('runs must be positive')
return [self.run_ant(**kwargs) for _ in range(runs)]
def run_ant(self, pheromone_intensity=None, algorithm=None, verbosity=0):
""" Do the ant work
:param float pheromone_intensity: pheromone intensity multiplier (None: use default; 0: do not deposit)
:param str algorithm: select algorithm: "classic" (original ACO) or "modified" (modified version to generate
optimized maps), default: use value from object
:param int verbosity: set verbosity level
:rtype: self.Solution
"""
# Regenerate random seed (necessary in threaded execution)
rand_gen = numpy.random.default_rng()
if not algorithm:
algorithm = self.algorithm
if algorithm == 'modified':
worker_network = self.complete_network_undirect.copy()
edge_list = list(worker_network.edges())
# Prepare the probabilities of removing each edge
desirability_list = numpy.array([each_edge[2]['desirability'] ** self.alpha
* each_edge[2]['cost'] ** self.beta
for each_edge in worker_network.edges(data=True)])
if self.unbound_runs != -1 and len(self.solutions) > self.unbound_runs:
# Do not select static edges
indices_larger = numpy.zeros(desirability_list.shape, dtype=bool)
indices_larger[numpy.argpartition(desirability_list, -self.minimum_edges)[-self.minimum_edges:]] = True
indices_above_threshold = desirability_list > self.permanent_edge_threshold
desirability_list[indices_larger & indices_above_threshold] = 1e9
desirability_list = 1 / desirability_list
n_min_edges_per_node, n_path_long, n_is_connected = 0, 0, 0
while True:
# normalize desirability_list (required by rand_gen.choice)
desirability_list = desirability_list / desirability_list.sum()
# Select a edge to remove
selected_edge = edge_list[rand_gen.choice(range(len(edge_list)), p=desirability_list)]
# Test if removed edge is valid (ie: network is still connected and not any path > path_threshold)
temp_network = worker_network.copy()
temp_network.remove_edge(*selected_edge)
if self.min_edges_per_node >= 2 \
and any((v < self.min_edges_per_node for k, v in temp_network.degree)):
# at least one of the network edges has less then min_edges_per_node edges
n_min_edges_per_node += 1
pass
elif max([j for i in dict(networkx.all_pairs_shortest_path_length(temp_network)).values()
for j in i.values()]) > self.path_threshold:
# at least one of the network paths would be longer than threshold
n_path_long += 1
pass
elif not networkx.is_connected(temp_network.to_undirected(as_view=True)):
# network would be disconnected
n_is_connected += 1
pass
else:
worker_network.remove_edge(*selected_edge)
desirability_list = numpy.delete(desirability_list, edge_list.index(selected_edge))
del edge_list[edge_list.index(selected_edge)]
if len(edge_list) == self.minimum_edges:
break
if self.extra_edge_beta > 0 \
and rand_gen.exponential(self.extra_edge_beta) > len(edge_list) - self.minimum_edges:
break
os_util.local_print('Modified ACO statistics: n_min_edges_per_node {}, n_path_long {}, n_is_connected {}'
''.format(n_min_edges_per_node, n_path_long, n_is_connected),
msg_verbosity=os_util.verbosity_level.debug)
this_cost = self.calculate_network_cost(worker_network)
elif algorithm == 'classic':
# Setup worker network
worker_network = deepcopy(self.complete_network_undirect)
for e in worker_network.edges:
worker_network.edges[e]['visited'] = False
for n in worker_network.nodes:
worker_network.nodes[n]['visited'] = False
first_node = list(worker_network.nodes)[rand_gen.integers(len(worker_network.nodes))]
current_node = first_node
while True:
worker_network.nodes[current_node]['visited'] = True
# Find near, unvisited nodes and edges
near_nodes = set([node for node in worker_network.adj[current_node]
if not worker_network.nodes[node]['visited']])
near_edges = [each_edge for each_edge in worker_network.edges(current_node, data=True)
if not each_edge[2]['visited']
and near_nodes.intersection(set(each_edge[:2]))]
if len(near_edges) == 0:
# All nodes visited, finish
worker_network.edges[(current_node, first_node)]['visited'] = True
results_map = deepcopy(self.complete_network_undirect)
results_map.remove_edges_from(self.complete_network_undirect.edges)
results_map.add_edges_from([e for e in worker_network.edges.data() if e[2]['visited']])
worker_network = results_map
break
desirability_list = numpy.array([e[2]['desirability'] for e in near_edges])
# Normalize desirability_list (required by rand_gen.choice)
desirability_list = desirability_list / desirability_list.sum()
# Select an edge to visit
selected_edge = near_edges[rand_gen.choice(range(len(near_edges)), p=desirability_list)]
# Move
worker_network.edges[selected_edge[:2]]['visited'] = True
current_node = selected_edge[0] if selected_edge[0] != current_node else selected_edge[1]
this_cost = self.calculate_network_cost(worker_network)
else:
os_util.local_print('Could not understand algorithm selection {}. Please, choose either "classic" or '
'"modified"'.format(algorithm), msg_verbosity=os_util.verbosity_level.error)
raise ValueError("Unknown algorithm {}".format(algorithm))
if pheromone_intensity != 0.0:
try:
last_n_elements = self.cost_list[-self.sliding_window:]
pheromone_multiplier = (sum(last_n_elements) / len(last_n_elements)) ** self.pheromone_exponent
pheromone_multiplier /= this_cost ** self.pheromone_exponent
except ZeroDivisionError:
# First run
pheromone_multiplier = 1
return self.Solution(worker_network, this_cost, pheromone_multiplier)
else:
return self.Solution(worker_network, this_cost)
def deposit_pheromone(self, pheromone_multiplier, solution_graph):
""" Deposit a pheromone trail
:param float pheromone_multiplier: pheromone intensity multiplier
:param networkx.Graph solution_graph: solution graph use by ant
:rtype: True
"""
for each_edge in solution_graph.edges:
this_pheromone = min(self.pheromone_intensity * pheromone_multiplier, self.max_pheromone_deposited)
self.complete_network_undirect[each_edge[0]][each_edge[1]]['desirability'] += this_pheromone
return True
def evaporate_pheromone(self, evaporating_rate=None):
""" Reduces the pheromone trail
:param float evaporating_rate: evaporate this much pheromone (Default: use stored)
:rtype: True
"""
if evaporating_rate is None:
evaporating_rate = self.evaporating_rate
for _, _, each_data in self.complete_network_undirect.edges(data=True):
each_data['desirability'] *= 1.0 - evaporating_rate
if each_data['desirability'] < self.min_edge_desirability:
each_data['desirability'] = self.min_edge_desirability
def __init__(self, network_graph, alpha=1, beta=1, path_threshold=-1, perturbation_multiplier=20,
perturbation_exponent=4.0, length_exponent=0.0, degree_multiplier=0.0, degree_target=None,
degree_exponent=2.0, pheromone_intensity=0.0, pheromone_exponent=2, max_pheromone_deposited=-1,
sliding_window=0, evaporating_rate=0.02, min_edge_desirability=0.1, min_unbound=-1,
permanent_edge_threshold=-1, extra_edge_beta=2, min_edges_per_node=2, algorithm='modified'):
""" Creates a new instance of AntSolver
:param networkx.Graph network_graph: graph to run ant on
:param float alpha: pheromone biasing exponent
:param float beta: cost biasing exponent
:param float path_threshold: max allowed path (-1: do not limit)
:param float perturbation_multiplier: multiplier for network cost
:param float perturbation_exponent: exponent for network cost
:param float length_exponent: raise exponent cost to this power
:param float degree_multiplier: multiplier for degree cost
:param float degree_target: target node degree
:param float pheromone_intensity: pheromone intensity multiplier (0: deposit nothing)
:param float pheromone_exponent: pheromone intensity exponent
:param float max_pheromone_deposited: deposit at most this much pheromone per run
:param int sliding_window: use the last sliding_window solutions to normalize the pheromone to be deposited
:param float evaporating_rate: evaporate this much pheromone per run
:param float min_edge_desirability: minimum edge desirability when reducing pheromone
:param float min_unbound: minimum number of runs when all edges can be removed (-1: off)
:param float permanent_edge_threshold: edges with this much pheromone become static (-1: off)
:param int min_edges_per_node: each edge must have at least this much nodes
:param str algorithm: select "classic" (original ACO) or "modified" (modified version to generate
optimized maps) algorithm
"""
# Data holder to store solutions found in multiple runs
self.solutions = []
self._cost_list = []
self.path_threshold = path_threshold if path_threshold != -1 else float('inf')
self.perturbation_multiplier = perturbation_multiplier
self.perturbation_exponent = perturbation_exponent
self.length_exponent = length_exponent
self.degree_target = degree_target if degree_target else min_edges_per_node
self.degree_multiplier = degree_multiplier
self.degree_exponent = degree_exponent
self.pheromone_intensity = pheromone_intensity
self.pheromone_exponent = pheromone_exponent
self.min_edge_desirability = min_edge_desirability
self.evaporating_rate = evaporating_rate
self.unbound_runs = min_unbound if min_unbound != -1 else float('inf')
self.permanent_edge_threshold = permanent_edge_threshold if permanent_edge_threshold != -1 else float('inf')
self.extra_edge_beta = extra_edge_beta
self.max_pheromone_deposited = max_pheromone_deposited if max_pheromone_deposited != -1 else float('inf')
self.min_edges_per_node = min_edges_per_node
self.sliding_window = sliding_window
self.algorithm = algorithm
self.alpha = alpha
self.beta = beta
self.complete_network = network_graph.copy()
self.complete_network_undirect = network_graph.to_undirected()
# Minimum number of edges is a Harary graph. See: Harary, F. "The Maximum Connectivity of a Graph." Proc. Nat.
# Acad. Sci. USA 48, 1142-1146, 1962. Also https://mathworld.wolfram.com/HararyGraph.html
self.minimum_edges = numpy.ceil((self.complete_network.number_of_nodes() * self.min_edges_per_node) / 2)
class TopologyData:
""" A class to store topology data.
"""
class MoleculeTypeData:
""" A class to store moleculetype data
"""
class DataHolder(list):
""" Simple class allowing to search using atom indices
"""
def __getitem__(self, item):
if isinstance(item, (int, slice)):
return super().__getitem__(item)
elif isinstance(item, frozenset):
return self.search_by_index(item)
else:
raise TypeError("DataHolder indices must be integers, slices, or frozenset, not {}"
"".format(type(item)))
def search_by_index(self, atoms):
""" Search DataHolder for elements containing atom
:param frozenset atoms: atom index
:rtype: generator
"""
atoms = frozenset(atoms) if not isinstance(atoms, frozenset) else atoms
for each_element in self:
if atoms in frozenset(each_element[0:self.n_fields]):
yield each_element
def search_all_with_index(self, id_list):
""" Search DataHolder for all elements containing atom
:param list id_list: list of atoms
:rtype: generator
"""
for each_element in self:
# True if any of elements from id_list is in the atom indices fields in each_element
if not set(id_list).isdisjoint(set(each_element[0:self.n_fields])):
yield each_element
def __init__(self, *args, n_fields):
if type(n_fields) != int and n_fields is not None:
raise TypeError("Expected int or NoneType, got {} instead".format(type(n_fields)))
self.n_fields = n_fields
super().__init__(args)
def check_a_b_topology(self, item):
"""Checks for the equivalence of A and B parameters for item
Parameters
----------
item : object
Term to check
Returns
-------
bool
"""
# Get field names
atom_fields = item.keys()[:self.n_fields]
# Test that parameters A and B are the same
get_a_b_terms = {i.replace('_A', '').replace('_B', '')
for i in item.keys()
if i not in atom_fields + ['function', 'comments']}
if not all((item.__getattribute__('{}_A'.format(i)) == item.__getattribute__('{}_B'.format(i))
for i in get_a_b_terms)):
return False
else:
return True
def append(self, x):
super().append(x)
x._parent = self
class MolNameDummy(str):
""" Super dummy class to return molecule name line """
def __init__(self, parent_class, molecule_name='LIG', nrexcl=3):
self.parent_class = parent_class
super().__init__()
self._name = molecule_name
self._nrexcl = nrexcl
def __str__(self):
try:
return '{:<10} {}'.format(self.parent_class.name, self._nrexcl) if self.parent_class.name \
else '{:<10} {}'.format(self._name, self._nrexcl)
except (UnboundLocalError, AttributeError):
return '{:<10} {}'.format(self._name, self._nrexcl)
@property
def num_atoms(self):
""" Get the number of atoms in this MoleculeType
:rtype: int
"""
return len(self.atoms_dict)
@property
def name(self):
return self._name
@name.setter
def name(self, molecule_name):
""" Sets the molecule name, propagating to residue name in atoms
:param str molecule_name: new molecule name
"""
self._name = molecule_name
for a in self.atoms_dict.values():
a.residue_name = molecule_name
self.name_line._name = molecule_name
def __init__(self, parent_class=None, molecule_name=''):
""" Constructs a new MoleculeTypeData.
:param TopologyData parent_class: outer TopologyData class
:param str molecule_name: name of this molecule
"""
self.output_sequence = []
self._name = None
self.name_line = self.MolNameDummy(self)
if parent_class:
self.parent_class = parent_class
self.atoms_dict = OrderedDict()
self.bonds_dict = self.DataHolder(n_fields=2)
self.pairs_dict = self.DataHolder(n_fields=2)
self.pairsnb_dict = self.DataHolder(n_fields=2)
self.exclusions_dict = self.DataHolder(n_fields=None)
self.angles_dict = self.DataHolder(n_fields=3)
self.dihe_dict = self.DataHolder(n_fields=4)
self.constraints_dict = self.DataHolder(n_fields=2)
self.settles_dict = self.DataHolder(n_fields=1)
self.vsites2_dict = self.DataHolder(n_fields=3)
self.vsites3_dict = self.DataHolder(n_fields=4)
self.vsites4_dict = self.DataHolder(n_fields=5)
if molecule_name:
self.name = molecule_name
def __str__(self):
""" Returns a formatted representation of a topology block
:rtype: str
"""
return_data = []
for each_element in self.output_sequence:
if isinstance(each_element, str):
return_data.append(each_element.__str__())
else:
return_data.extend(map(self._format_inline,
self.parent_class.find_online_parameter(each_element, self.atoms_dict)))
return '\n'.join(return_data)
@staticmethod
# TODO: automatically detect what are indexes and parameters and format accordingly
def _format_inline(index_list, parameter_list=None, comment='', align_size=7):
"""Formats a parameter line
Parameters
----------
index_list : list
list of indexes
parameter_list : list
list of parameters, if present
comment : str
inline comment, if any
align_size : int
column size for parameters_list, if present, for index_list otherwise if parameter_list=None
Returns
-------
str
Returns the formatted term line
"""
if parameter_list is not None:
terms = [index_list.__getattribute__(i) for i in index_list.keys()[:index_list._parent.n_fields + 1]]
terms += [index_list.__getattribute__(i) for i in parameter_list]
inline_param_str = ('{:<{align_size}} ' * len(terms)).format(*terms, align_size=align_size)
else:
# Test if this term holds topology A and B data, if so, print only top A
if index_list.__class__.__name__ in ["BondDataDual", "AngleDataDual", "DihedralDataDual",
"ConstraintDataDual"]:
terms = [index_list.__getattribute__(i) for i in index_list.keys() if not i.endswith('_B')]
comment += 'Suppressed topology B data: {}' \
''.format('; '.join(['{}: {}'.format(i, index_list.__getattribute__(i))
for i in index_list.keys() if i.endswith('_B')]))
else:
terms = [index_list.__getattribute__(i) for i in index_list.keys()]
if not comment and isinstance(index_list[-1], str):
# Comment is stored in index_list
comment = index_list[-1]
inline_param_str = ('{:<{align_size}} ' * (len(terms) - 1)).format(*terms[:-1],
align_size=align_size)
else:
inline_param_str = ('{:<{align_size}} ' * len(terms)).format(*terms, align_size=align_size)
if comment and comment.lstrip()[0] != ';':
inline_param_str += '; {}'.format(comment)
return inline_param_str
def make_restraint(self, selection_data=None, output_file=None, force_k=1000):
""" Generate a restraint file data from the supplied selection
Parameters
----------
selection_data : str, list
Generate restrains for this selection. Available formats are: a str that will be compiled to a regex
and matched against atom names; a list with integers, that will be matched against atom indexes, a list
with strs that will be (case insensitively) matched against residues name and index (eg, MET50).
output_file : str
Save restraint data to this file. Is None, restraint data will be returned.
force_k : int
Force constant for the restraints
Returns
-------
str
GROMACS-compatible restrains file data
"""
restraint_function = 1
header = f""";Position restrains generated for the {self.name} molecule using {selection_data} selection.
[ position_restraints ]
; atom type fx fy fz
"""
selection_data_index, selection_data_residues = [], []
atom_match = re.compile('')
try:
atom_match = re.compile(selection_data)
except TypeError as error:
if selection_data is None:
pass
elif isinstance(selection_data, list):
selection_data_index = [i for i in selection_data if isinstance(i, int)]
selection_data_residues = [i.lower() for i in selection_data if i not in selection_data]
else:
raise error
if selection_data == 'all':
restraint_atoms = [atom_index for atom_index, each_atom in self.atoms_dict.items()]
else:
restraint_atoms = []
for atom_index, each_atom in self.atoms_dict.items():
if isinstance(selection_data, list):
if int(each_atom.atom_index) in selection_data_index:
restraint_atoms.append(atom_index)
elif f'{each_atom.residue_name.lower()}{each_atom.residue_number}' in selection_data_residues:
restraint_atoms.append(atom_index)
elif atom_match.match(each_atom.atom_name):
restraint_atoms.append(atom_index)
restr_data = header + '\n'.join([f'{i:<7} {restraint_function:<5} {force_k:<5} {force_k:<5} {force_k:<5}'
for i in restraint_atoms])
if output_file is not None:
with open(output_file, 'w') as fh:
fh.write(restr_data)
else:
return restr_data
# Fields for unpacking atomtypes
__atomtype_dict = {0: namedlist('AtomTypeData', ['atom_type', 'm_u', 'q_e', 'particle_type', 'V', 'W', 'comments'],
defaults=['']),
1: namedlist('AtomTypeData',
['atom_type', 'bonded_type', 'm_u', 'q_e', 'particle_type', 'V', 'W',
'comments'], defaults=['']),
2: namedlist('AtomTypeData',
['atom_type', 'atomic_number', 'm_u', 'q_e', 'particle_type', 'V', 'W',
'comments'], defaults=['']),
3: namedlist('AtomTypeData', ['atom_type', 'bonded_type', 'atomic_number', 'm_u', 'q_e',
'particle_type', 'V', 'W', 'comments'], defaults=['']), }
# Fields for unpacking atoms
__atomdata_fields = {1: ['atom_index', 'atom_type', 'residue_number', 'residue_name', 'atom_name',
'charge_group_number', 'q_e', 'm_u', 'comments'],
-1: ['atom_index', 'atom_type', 'residue_number', 'residue_name', 'atom_name',
'charge_group_number', 'q_e', 'comments']}
# Fields for unpacking bonds (assembles a dict of possible fields list)
__bonddata_dict = {1: ['b0', 'kb', 'comments'], # Bond
2: ['b0', 'kb', 'comments'], # G96 bond
3: ['b0', 'D', 'beta', 'comments'], # Morse
4: ['b0', 'C', 'comments'], # cubic bond
5: ['comments'], # connection
6: ['b0', 'kb', 'comments'], # harmonic potential
7: ['b0', 'kb', 'comments'], # FENE bond
8: ['table_number', 'k', 'comments'], # tabulated bond
9: ['table_number', 'k', 'comments'], # tabulated bond
10: ['low', 'up1', 'up2', 'kdr', 'comments'], # restraint potential
-1: ['comments']} # bond read from somewhere else
__bonddata_fields = {function: ['atom_i', 'atom_j', 'function', *parameters]
for function, parameters in __bonddata_dict.items()}
# Fields for unpacking bonds for lines bearing both topology A and B data (assembles a dict of possible fields list)
__bonddata_dict_dualtop = {code: ['{}_A'.format(i) for i in this_terms[:-1]]
+ ['{}_B'.format(i) for i in this_terms[:-1]]
+ [this_terms[-1]]
for code, this_terms in __bonddata_dict.items()
if code in [1, 2, 3, 6, 8, 9]}
__bonddata_fields_dualtop = {function: ['atom_i', 'atom_j', 'function', *parameters]
for function, parameters in __bonddata_dict_dualtop.items()}
# Fields for unpacking pairs (assembles a dict of possible fields list)
__pairsdata_dict = {1: ['V', 'W', 'comments'], # extra LJ or Coulomb
2: ['fudge_QQ', 'qi', 'qj', 'V', 'W', 'comments'], # extra LJ or Coulomb
-1: ['comments']} # pair read from somewhere else
__pairsdata_fields = {function: ['atom_i', 'atom_j', 'function', *parameters]
for function, parameters in __pairsdata_dict.items()}
# Fields for unpacking pairs for lines bearing both topology A and B data (only fn=1 pairs allowed)
__pairsdata_fields_dualtop = {1: ['atom_i', 'atom_j', 'function', 'V_A', 'W_A', 'V_B', 'W_B', 'comments']}
__pairsnb_dict = {1: ['qi', 'qj', 'V', 'W', 'comments'], # extra LJ or Coulomb
-1: ['comments']} # nb pair read from somewhere else
__pairsnbdata_fields = {function: ['atom_i', 'atom_j', 'function', *parameters]
for function, parameters in __pairsdata_dict.items()}
# Fields for unpacking angles (assembles a dict of possible fields list)
__angledata_dict = {1: ['theta0', 'k', 'comments'], # angle
2: ['theta0', 'k', 'comments'], # G96 angle
3: ['r1e', 'r2e', 'krr', 'comments'], # cross bond-bond
4: ['r1e', 'r2e', 'r3e', 'kr_theta', 'comments'], # cross bond-angle
5: ['tetha0', 'k0', 'r13', 'kUB', 'comments'], # Urey-Bradley
6: ['theta0', 'C0', 'C1', 'C2', 'C3', 'C4', 'comments'], # quartic angle
8: ['table_number', 'k', 'comments'], # tabulated angle
9: ['table_number', 'comments'], # tabulated bond
10: ['theta0', 'k0', 'comments'], # restricted bending potential
-1: ['comments']} # angle read from somewhere else
__angledata_fields = {function: ['atom_i', 'atom_j', 'atom_k', 'function', *parameters]
for function, parameters in __angledata_dict.items()}
# Fields for unpacking angle for lines bearing both topology A and B data (assembles a dict of possible fields list)
__angledata_dict_dualtop = {code: ['{}_A'.format(i) for i in this_terms[:-1]]
+ ['{}_B'.format(i) for i in this_terms[:-1]]
+ [this_terms[-1]]
for code, this_terms in __angledata_dict.items()
if code in [1, 2, 5, 8]}
__angledata_fields_dualtop = {function: ['atom_i', 'atom_j', 'atom_k', 'function', *parameters]
for function, parameters in __angledata_dict_dualtop.items()}
# Fields for unpacking dihedrals (assembles a dict of possible fields list)
__dihedata_dict = {1: ['phi', 'k', 'multiplicity', 'comments'], # proper dihedral
2: ['zeta0', 'k', 'comments'], # improper dihedral
3: ['C0', 'C1', 'C2', 'C3', 'C4', 'C5', 'comments'], # Ryckaert-Bellemans dihedral
4: ['pih', 'k', 'multiplicity', 'comments'], # periodic improper dihedral
5: ['C1', 'C2', 'C3', 'C4', 'comments'], # Fourier dihedral
8: ['table_number', 'k', 'comments'], # tabulated dihedral
9: ['phi', 'k', 'multiplicity', 'comments'], # proper dihedral (multiple)
10: ['phi0', 'k', 'comments'], # restricted dihedral
11: ['a0', 'a1', 'a2', 'a3', 'a4', 'comments'], # combined bending-torsion potential
-1: ['comments']} # dihedral read from somewhere else
__dihedata_fields = {function: ['atom_i', 'atom_j', 'atom_k', 'atom_l', 'function', *parameters]
for function, parameters in __dihedata_dict.items()}
# Fields for unpacking dihedral for lines bearing both topology A and B data (assembles a dict of possible fields
# list)
__dihedata_dict_dualtop = {code: ['{}_A'.format(i) for i in this_terms[:-1]]
+ ['{}_B'.format(i) for i in this_terms[:-1]]
+ [this_terms[-1]]
for code, this_terms in __dihedata_dict.items()
if code in [1, 2, 3, 4, 5, 8, 9]}
__dihedata_fields_dualtop = {function: ['atom_i', 'atom_j', 'atom_k', 'atom_l', 'function', *parameters]
for function, parameters in __dihedata_dict_dualtop.items()}
# Fields for unpacking constraints (assembles a dict of possible fields list)
__constraint_dict = {1: ['b0', 'comments'], # proper dihedral
2: ['b0', 'comments'], # improper dihedral
-1: ['comments']} # dihedral read from somewhere else
__constraint_fields = {function: ['atom_i', 'atom_j', 'function', *parameters]
for function, parameters in __constraint_dict.items()}
# Fields for unpacking constraints for lines bearing both topology A and B data (assembles a dict of possible
# fields list)
__constraint_dict_dualtop = {code: ['{}_A'.format(i) for i in this_terms[:-1]]
+ ['{}_B'.format(i) for i in this_terms[:-1]]
+ [this_terms[-1]]
for code, this_terms in __constraint_dict.items() if code in [1, 2]}
__constraint_fields_dualtop = {function: ['atom_i', 'atom_j', 'function', *parameters]
for function, parameters in __constraint_dict_dualtop.items()}
# Fields for unpacking SETTLE directives. No FE is allowed and only fn = 1 is supported with a single atom
__setttles_data = namedlist('SettlesData', ['atom_ow', 'function', 'doh', 'dhh', 'comments'], defaults=[''])
# Fields for unpacking 2-atom virtual site
__vsite2_data = namedlist('VirtualSite2Data', ['site', 'atom_i', 'atom_j', 'function', 'a', 'comments'],
defaults=[''])
# Fields for unpacking 3-atom virtual site (assembles a dict of possible fields list)
__vsite3_dict = {1: ['a', 'b', 'comments'], # type 3
2: ['a', 'd', 'comments'], # type 3fd
3: ['theta', 'd', 'comments'], # type 3fad
4: ['a', 'b', 'c', 'comments']} # type 3out
__vsite3_fields = {function: ['site', 'atom_i', 'atom_j', 'atom_k', 'function', *parameters]
for function, parameters in __vsite3_dict.items()}
# FIXME: implement support for missing directives and constraints
def __init__(self, topology_files=None, verbosity=0):
""" Constructor of TolopogyData
:param [str, list] topology_files: reads topology from this file/these files
:param int verbosity: set verbosity level
"""
# This holds the unmodified lines from the file and references to elements
self.atomtype_dict = OrderedDict()
self.output_sequence = []
self.molecules = []
self.restraint_files = {}
self.__online_bondtypes = {}
self.__online_pairtypes = {}
self.__online_angletypes = {}
self.__online_dihedraltypes = {}
self.__online_constrainttypes = {}
self.type_directive_dict = {'bondtypes': {'data_fields': self.__bonddata_fields,
'function_index': 2,
'online_dict': self.__online_bondtypes,
'class_name': 'BondData'},
'pairtypes': {'data_fields': self.__pairsdata_fields,
'function_index': 2,
'online_dict': self.__online_pairtypes,
'class_name': 'PairData'},
'angletypes': {'data_fields': self.__angledata_fields,
'function_index': 3,
'online_dict': self.__online_angletypes,
'class_name': 'AngleData'},
'dihedraltypes': {'data_fields': self.__dihedata_fields,
'function_index': 4,
'online_dict': self.__online_dihedraltypes,
'class_name': 'DihedralData'},
'constrainttypes': {'data_fields': self.__constraint_fields,
'function_index': 2,
'online_dict': self.__online_constrainttypes,
'class_name': 'ConstraintData'}}
self.online_terms_dict = {each_element['class_name']: each_element for each_element
in self.type_directive_dict.values()}
if topology_files is not None:
if isinstance(topology_files, str):
self.read_topology([topology_files], verbosity=verbosity)
else:
self.read_topology(topology_files, verbosity=verbosity)
@staticmethod
def type_converter(value):
""" Splits a string into parts converts them to appropriated types
:param str value: string to be converted
:rtype: list
"""
return_list = []
value = value.split(';', 1)
for each_part in value[0].split():
return_list.append(os_util.detect_type(each_part, test_for_boolean=False))
try:
return_list.append(value[1])
except IndexError:
pass
finally:
return return_list
@staticmethod
def detect_solute_molecule_name(input_file, test_sol_molecules=None, gmx_bin='gmx', no_checks=False, verbosity=0):
"""Process file, trying to guess the name of the water molecule
Parameters
----------
input_file : str
Input file. Must be one of GROMACS-compatible index (.ndx), GROMACS run file (.tpr), GROMACS-compatible
topology (.top or .itp), or PDB. Type will be guessed from extension.
test_sol_molecules : list
Try this molecule names
gmx_bin : str
GROMACS binary
no_checks : bool
Ignore checks and keep going
verbosity : int
Sets verbosity level
Returns
-------
str
"""
from prepare_dual_topology import read_index_data, make_index
if not test_sol_molecules:
test_sol_molecules = water_res_names
if isinstance(test_sol_molecules, str):
test_sol_molecules = [test_sol_molecules]
file_type = os.path.splitext(input_file)[1]
if file_type == '.ndx':