Package paramz :: Package core :: Module lists_and_dicts
[hide private]
[frames] | no frames]

Source Code for Module paramz.core.lists_and_dicts

  1  #=============================================================================== 
  2  # Copyright (c) 2015, Max Zwiessele 
  3  # All rights reserved. 
  4  # 
  5  # Redistribution and use in source and binary forms, with or without 
  6  # modification, are permitted provided that the following conditions are met: 
  7  # 
  8  # * Redistributions of source code must retain the above copyright notice, this 
  9  #   list of conditions and the following disclaimer. 
 10  # 
 11  # * Redistributions in binary form must reproduce the above copyright notice, 
 12  #   this list of conditions and the following disclaimer in the documentation 
 13  #   and/or other materials provided with the distribution. 
 14  # 
 15  # * Neither the name of paramax nor the names of its 
 16  #   contributors may be used to endorse or promote products derived from 
 17  #   this software without specific prior written permission. 
 18  # 
 19  # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
 20  # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 
 21  # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
 22  # DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 
 23  # FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
 24  # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
 25  # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
 26  # CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
 27  # OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
 28  # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 
 29  #=============================================================================== 
 30   
 31  from collections import defaultdict 
 32  import weakref 
 33   
34 -def intarray_default_factory():
35 import numpy as np 36 return np.int_([])
37
38 -class IntArrayDict(defaultdict):
39 - def __init__(self, default_factory=None):
40 """ 41 Default will be self._default, if not set otherwise 42 """ 43 defaultdict.__init__(self, intarray_default_factory)
44
45 -class ArrayList(list):
46 """ 47 List to store ndarray-likes in. 48 It will look for 'is' instead of calling __eq__ on each element. 49 """
50 - def __contains__(self, other):
51 for el in self: 52 if el is other: 53 return True 54 return False
55
56 - def index(self, item):
57 index = 0 58 for el in self: 59 if el is item: 60 return index 61 index += 1 62 raise ValueError("{} is not in list".format(item))
63 pass
64
65 -class ObserverList(object):
66 """ 67 A list which containts the observables. 68 It only holds weak references to observers, such that unbound 69 observers dont dangle in memory. 70 """
71 - def __init__(self):
72 self._poc = []
73
74 - def __getitem__(self, ind):
75 p,o,c = self._poc[ind] 76 return p, o(), c
77
78 - def remove(self, priority, observer, callble):
79 """ 80 Remove one observer, which had priority and callble. 81 """ 82 self.flush() 83 for i in range(len(self) - 1, -1, -1): 84 p,o,c = self[i] 85 if priority==p and observer==o and callble==c: 86 del self._poc[i]
87
88 - def __repr__(self):
89 return self._poc.__repr__()
90
91 - def add(self, priority, observer, callble):
92 """ 93 Add an observer with priority and callble 94 """ 95 #if observer is not None: 96 ins = 0 97 for pr, _, _ in self: 98 if priority > pr: 99 break 100 ins += 1 101 self._poc.insert(ins, (priority, weakref.ref(observer), callble))
102
103 - def __str__(self):
104 from ..param import Param 105 from ..core.observable_array import ObsAr 106 from ..core.parameter_core import Parameterizable 107 ret = [] 108 curr_p = None 109 110 def frmt(o): 111 if isinstance(o, ObsAr): 112 return 'ObsArr <{}>'.format(hex(id(o))) 113 elif isinstance(o, (Param,Parameterizable)): 114 return '{}'.format(o.hierarchy_name()) 115 else: 116 return repr(o)
117 for p, o, c in self: 118 curr = '' 119 if curr_p != p: 120 pre = "{!s}: ".format(p) 121 curr_pre = pre 122 else: curr_pre = " "*len(pre) 123 curr_p = p 124 curr += curr_pre 125 126 ret.append(curr + ", ".join([frmt(o), str(c)])) 127 return '\n'.join(ret)
128
129 - def flush(self):
130 """ 131 Make sure all weak references, which point to nothing are flushed (deleted) 132 """ 133 self._poc = [(p,o,c) for p,o,c in self._poc if o() is not None]
134
135 - def __iter__(self):
136 self.flush() 137 for p, o, c in self._poc: 138 yield p, o(), c
139
140 - def __len__(self):
141 self.flush() 142 return self._poc.__len__()
143 144 pass 145