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