Package csb :: Package statistics :: Package samplers
[frames] | no frames]

Source Code for Package csb.statistics.samplers

  1  """ 
  2  Defines abstract samplers. 
  3  """ 
  4   
  5  import numpy as np 
  6  import csb.core 
  7   
  8  from abc import ABCMeta, abstractmethod, abstractproperty 
9 10 11 -class DimensionError(TypeError):
12 pass
13
14 -class AbstractSampler(object):
15 """ 16 Abstract interface for sampling algorithms. 17 """ 18 19 __metaclass__ = ABCMeta 20 21 @abstractmethod
22 - def sample(self):
23 """ 24 Draw a sample. 25 @rtype: L{AbstractState} 26 """ 27 pass
28
29 -class AbstractState(object):
30 """ 31 Represents a point in phase-space. 32 """ 33 34 __metaclass__ = ABCMeta 35 36 @abstractproperty
37 - def position(self):
38 pass
39 40 @abstractproperty
41 - def momentum(self):
42 pass
43
44 -class State(AbstractState):
45 """ 46 Represents a point in phase-space. 47 """ 48 49 @staticmethod
50 - def check_flat_array(*args):
51 """ 52 Check whether arguments are flat, one-dimensional numpy arrays. 53 """ 54 55 for q in args: 56 if not isinstance(q, np.ndarray): 57 raise TypeError(q, 'numpy.ndarray expected!') 58 59 if not len(q.squeeze().shape) <= 1: 60 raise DimensionError(q, '1d numpy.ndarray expected!')
61 62 @staticmethod
63 - def check_equal_length(q, p):
64 """ 65 Check whether arguments have equal length. 66 """ 67 68 if len(q) != len(p): 69 raise DimensionError(p, 'momentum needs to have the same dimension as coordinates!')
70
71 - def __init__(self, position, momentum=None):
72 73 self._position = None 74 self._momentum = None 75 76 self.position = position 77 self.momentum = momentum
78 79 @property
80 - def position(self):
81 return self._position.copy()
82 @position.setter
83 - def position(self, value):
84 State.check_flat_array(value) 85 self._position = np.array(value) 86 87 @property
88 - def momentum(self):
89 if self._momentum is None: 90 return None 91 else: 92 return self._momentum.copy()
93 @momentum.setter
94 - def momentum(self, value):
95 if not value is None: 96 State.check_flat_array(value) 97 State.check_equal_length(value, self.position) 98 self._momentum = np.array(value) 99 else: 100 self._momentum = None
101
102 - def clone(self):
103 return State(self.position, self.momentum)
104
105 -class EnsembleState(csb.core.BaseCollectionContainer, AbstractState):
106 """ 107 Defines an Ensemble Monte Carlo state; it is a read-only collection 108 of State objects. 109 110 @param items: initialization list of states 111 @type items: list of L{States} 112 """ 113
114 - def __init__(self, items):
115 super(EnsembleState, self).__init__(items, type=State)
116 117 @property
118 - def position(self):
119 return np.array([s.positions for s in self]) 120 121 @property
122 - def momentum(self):
123 return np.array([s.momentum for s in self])
124