IMP logo
IMP Reference Guide  2.20.0
The Integrative Modeling Platform
utilities.py
1 """@namespace IMP.pmi1.io.utilities
2  Utility classes and functions for IO.
3 """
4 
5 try:
6  from collections.abc import MutableSet # needs Python 3.3 or later
7 except ImportError:
8  from collections import MutableSet
9 import csv
10 
11 def get_db_from_csv(csvfilename):
12  outputlist = []
13  csvr = csv.DictReader(open(csvfilename))
14  for l in csvr:
15  outputlist.append(l)
16  return outputlist
17 
18 class OrderedSet(MutableSet):
19  def __init__(self, iterable=None):
20  self.end = end = []
21  end += [None, end, end] # sentinel node for doubly linked list
22  self.map = {} # key --> [key, prev, next]
23  if iterable is not None:
24  self |= iterable
25 
26  def __len__(self):
27  return len(self.map)
28 
29  def __contains__(self, key):
30  return key in self.map
31 
32  def add(self, key):
33  if key not in self.map:
34  end = self.end
35  curr = end[1]
36  curr[2] = end[1] = self.map[key] = [key, curr, end]
37 
38  def discard(self, key):
39  if key in self.map:
40  key, prev, next = self.map.pop(key)
41  prev[2] = next
42  next[1] = prev
43 
44  def __iter__(self):
45  end = self.end
46  curr = end[2]
47  while curr is not end:
48  yield curr[0]
49  curr = curr[2]
50 
51  def __reversed__(self):
52  end = self.end
53  curr = end[1]
54  while curr is not end:
55  yield curr[0]
56  curr = curr[1]
57 
58  def pop(self, last=True):
59  if not self:
60  raise KeyError('set is empty')
61  key = self.end[1][0] if last else self.end[2][0]
62  self.discard(key)
63  return key
64 
65  def __repr__(self):
66  if not self:
67  return '%s()' % (self.__class__.__name__,)
68  return '%s(%r)' % (self.__class__.__name__, list(self))
69 
70  def __eq__(self, other):
71  if isinstance(other, OrderedSet):
72  return len(self) == len(other) and list(self) == list(other)
73  return set(self) == set(other)