cepgen is hosted by Hepforge, IPPP Durham
CepGen 1.2.5
Central exclusive processes event generator
Loading...
Searching...
No Matches
containers_cff.py
Go to the documentation of this file.
4
5class PrintHelper(object):
6 """Helper class for the pretty-printing of configuration parameters"""
7 _indent = 0
8 _indent_size = 4
9
10 def indent(self):
11 """Move to the next indentation block"""
12 self._indent += self._indent_size
13
14 def unindent(self):
15 """Go up to the previous indentation block"""
16 self._indent -= self._indent_size
18 def indentation(self):
19 """Current indentation level"""
20 return ' '*self._indent
22
23class Parameters(dict):
24 """A raw list of steering parameters"""
25 __getattr__ = dict.get
26 __setattr__ = dict.__setitem__
27 __delattr__ = dict.__delitem__
28
29 def __init__(self, *args, **kwargs):
30 """Construct a parameters set from dictionary arguments
31
32 Args:
33 args: list of arguments
34
35 Kwargs:
36 kwargs: list of named (keyworded) arguments
37
38 Examples:
39 >>> print(dict(Parameters(foo = 'bar', foo2 = 42)))
40 {'foo': 'bar', 'foo2': 42}
41 """
42 self.update(*args, **kwargs)
43 super(Parameters, self).__init__(*args, **kwargs)
44
45 def __deepcopy__(self, memo):
46 """Override the default dict deep copy operator"""
47 from copy import deepcopy
48 return Parameters([(deepcopy(k, memo), deepcopy(v, memo)) for k, v in self.items()])
50 def dump(self, printer=PrintHelper()):
51 """Human-readable dump of this object"""
52 out = self.__class__.__name__+'(\n'
53 printer.indent()
54 for k, v in self.items():
55 out += ('%s%s = ' % (printer.indentation(), k))
56 if v.__class__.__name__ in ['Parameters', 'Module']:
57 out += v.dump(printer)
58 elif v.__class__.__name__ in ['list', 'tuple']:
59 out += v.__class__.__name__ + '('
60 printer.indent()
61 for it in v:
62 if it.__class__.__name__ in ['Parameters', 'Module']:
63 out += '\n' + printer.indentation()
64 out += it.dump(printer)
65 else:
66 out += it.__repr__()
67 if it != v[-1]:
68 out += ', '
69 out += ')'
70 printer.unindent()
71 else:
72 out += v.__repr__()
73 out += ',\n'
74 printer.unindent()
75 out += printer.indentation()+')'
76 return out
77
78 def __repr__(self):
79 """Human-readable version of this object"""
80 return self.dump()
81
82 def clone(self, *args, **kwargs):
83 """Return a deep copy of this object"""
84 from copy import deepcopy
85 out = deepcopy(self)
86 for k in kwargs:
87 out[k] = kwargs.get(k)
88 return type(self)(out)
89
90 def load(self, mod):
91 """Extend this object by an include"""
92 from sys import modules
93 mod = mod.replace('/', '.')
94 __import__(mod)
95 self.extend(modules[mod])
96
97
98class Module(Parameters):
99 """A named parameters set to steer a generic module
100
101 Attributes:
102 mod_name: Name of this module
103 """
104
105 def __init__(self, name, *args, **kwargs):
106 """Construct a module parameters set from dictionary arguments
107
108 Args:
109 name: module name
110 args: list of arguments
111
112 Kwargs:
113 kwargs: list of named (keyworded) arguments
114
115 Examples:
116 >>> print(dict(Module('module1', foo = 'bar', foo2 = 42)))
117 {'foo': 'bar', 'foo2': 42, 'mod_name': 'module1'}
118 """
119 super(Module, self).__init__(*args, **kwargs)
120 self.mod_name = name
121
122 def __len__(self):
123 """Number of keys handled"""
124 return dict.__len__(self)-1 # discard the name key
125
126 def dump(self, printer=PrintHelper()):
127 """Human-readable dump of this object"""
128 out = self.__class__.__name__+'('+self.mod_name.__repr__()+',\n'
129 mod_repr = self.cloneclone('')
130 mod_repr.pop('mod_name', None)
131 for k, v in mod_repr.items():
132 printer.indent()
133 out += ('%s%s = ' % (printer.indentation(), k))
134 if v.__class__.__name__ not in ['Parameters', 'Module']:
135 out += v.__repr__()
136 else:
137 out += v.dump(printer)
138 out += ',\n'
139 printer.unindent()
140 out += printer.indentation()+')'
141 return out
142
143 def __repr__(self):
144 """Human-readable version of this object"""
145 return self.dumpdump()
146
147 def name(self):
148 return self.mod_name
149
150 def clone(self, name='', **kwargs):
151 """Return a deep copy of this object"""
152 out = Parameters(self).clone(**kwargs)
153 if name:
154 out.mod_name = name
155 return out
157
158class Sequence(list):
159 """An ordered modules sequence"""
160 MODULE = object()
161
162 def __init__(self, *args):
163 """Construct an ordered sequence of modules from a list
164
165 Args:
166 args: list of modules
167
168 Examples:
169 >>> module1 = Module('test1', foo = 'bar')
170 >>> module2 = Module('test2', foo2 = 42)
171 >>> print(Sequence(module1, module2))
172 Sequence([Module('test1',
173 foo = 'bar',
174 ), Module('test2',
175 foo2 = 42,
176 )])
177 """
178 super(Sequence, self).__init__(args)
179
180 def __delitem__(self, index):
181 """Remove an element from the sequence"""
182 self[index] = self.MODULE
183
184 def __iter__(self):
185 """Iterator definition for the sequence"""
186 return (item for item in super().__iter__() if item is not self.MODULE)
187
188 def __eq__(self, other):
189 """Equality operator"""
190 if isinstance(other, Sequence):
191 return all(x == y for x, y in zip(self, other))
192 return super().__eq__(other)
193
194 def __repr__(self):
195 """Human-readable representation of this sequence"""
196 return type(self).__name__+'('+super(Sequence, self).__repr__()+')'
197
198
199if __name__ == '__main__':
200 import unittest
201
202 class TestTypes(unittest.TestCase):
203 """Small collection of tests for our new types"""
204
205 def testModules(self):
206 """Test the Module object"""
207 mod = Module('empty')
208 self.assertEqual(len(mod), 0)
209 mod.param1 = 'foo'
210 self.assertEqual(len(mod), 1)
211 # playing with modules clones
212 mod_copy = mod.clone('notEmpty', param1 = 'boo', param2 = 'bar')
213 self.assertEqual(mod.param1, 'foo')
214 self.assertEqual(mod_copy.param1, 'boo')
215 self.assertEqual(mod_copy.param2, 'bar')
216 self.assertEqual(mod.param1+mod_copy.param2, 'foobar')
218 def testParameters(self):
219 """Test the Parameters object"""
220 params = Parameters(
221 first = 'foo',
222 second = 'bar',
223 third = 42,
224 fourth = (1, 2),
225 )
226 params_copy = params.clone(
227 second = 'bak',
228 )
229 self.assertEqual(len(params), 4)
230 self.assertEqual(params.first, params['first'])
231 self.assertEqual(params['second'], 'bar')
232 self.assertTrue(int(params.third) == params.third)
233 self.assertEqual(len(params.fourth), 2)
234 self.assertEqual(params.second, 'bar')
235 # playing with parameters clones
236 self.assertEqual(params_copy.second, 'bak')
237 # check that the clone does not change value if the origin does
238 # (i.e. we indeed have a deep copy and not a shallow one...)
239 params.third = 43
240 self.assertEqual(params.third, 43)
241 self.assertEqual(params_copy.third, 42)
242
243 def testSequences(self):
244 """Test the Sequence object"""
245 mod1 = Module('module1',
246 foo = 'bar',
247 foo2 = 42
248 )
249 mod2 = Module('module2',
250 foo = [i for i in range(4)]
251 )
252 seq = Sequence(mod1, mod2)
253 self.assertEqual(len(seq), 2)
254 # check that all sequence modules have their attributes
255 # conserved in the sequence construction
256 self.assertEqual(len(seq[0]), 2)
257 self.assertEqual(seq[0].foo, 'bar')
258 self.assertEqual(seq[0].name(), 'module1')
259 self.assertEqual(len(seq[1]), 1)
260 self.assertEqual(seq[1].name(), 'module2')
261 self.assertEqual(len(seq[1].foo), 4)
262
263 unittest.main()
A named parameters set to steer a generic module.
clone(self, name='', **kwargs)
Return a deep copy of this object.
__init__(self, name, *args, **kwargs)
Construct a module parameters set from dictionary arguments.
__repr__(self)
Human-readable version of this object.
dump(self, printer=PrintHelper())
Human-readable dump of this object.
__len__(self)
Number of keys handled.
A raw list of steering parameters.
load(self, mod)
Extend this object by an include.
__init__(self, *args, **kwargs)
Construct a parameters set from dictionary arguments.
__repr__(self)
Human-readable version of this object.
dump(self, printer=PrintHelper())
Human-readable dump of this object.
clone(self, *args, **kwargs)
Return a deep copy of this object.
__deepcopy__(self, memo)
Override the default dict deep copy operato.
Helper class for the pretty-printing of configuration parameters.
unindent(self)
Go up to the previous indentation block.
indent(self)
Move to the next indentation block.
indentation(self)
Current indentation level.
An ordered modules sequence.
__iter__(self)
Iterator definition for the sequence.
__repr__(self)
Human-readable representation of this sequence.
__init__(self, *args)
Construct an ordered sequence of modules from a list.
__eq__(self, other)
Equality operato.
__delitem__(self, index)
Remove an element from the sequence.
Small collection of tests for our new types.
testParameters(self)
Test the Parameters object.
testSequences(self)
Test the Sequence object.