@@ -29,30 +29,30 @@ class Categorize(Factory, Container):
29
29
"""
30
30
31
31
@staticmethod
32
- def ed (entries , contentType , pairsAsDict = None , ** pairs ):
32
+ def ed (entries , contentType , binsAsDict = None , ** bins ):
33
33
"""Create a Categorize that is only capable of being added.
34
34
35
35
Parameters:
36
36
entries (float): the number of entries.
37
37
contentType (str): the value's sub-aggregator type (must be provided to determine type for the case when `bins` is empty).
38
- pairs (dict from str to :doc:`Container <histogrammar.defs.Container>`): the non-empty bin categories and their values.
38
+ bins (dict from str to :doc:`Container <histogrammar.defs.Container>`): the non-empty bin categories and their values.
39
39
"""
40
40
if not isinstance (entries , numbers .Real ) and entries not in ("nan" , "inf" , "-inf" ):
41
41
raise TypeError ("entries ({0}) must be a number" .format (entries ))
42
42
if not isinstance (contentType , basestring ):
43
43
raise TypeError ("contentType ({0}) must be a string" .format (contentType ))
44
- if not all (isinstance (k , basestring ) and isinstance (v , Container ) for k , v in pairs .items ()):
45
- raise TypeError ("pairs ({0}) must be a dict from strings to Containers" .format (pairs ))
44
+ if not all (isinstance (k , basestring ) and isinstance (v , Container ) for k , v in bins .items ()):
45
+ raise TypeError ("bins ({0}) must be a dict from strings to Containers" .format (bins ))
46
46
if entries < 0.0 :
47
47
raise ValueError ("entries ({0}) cannot be negative" .format (entries ))
48
48
49
49
out = Categorize (None , None )
50
50
out .entries = float (entries )
51
- if pairsAsDict is None :
52
- out .pairs = {}
51
+ if binsAsDict is None :
52
+ out .bins = {}
53
53
else :
54
- out .pairs = pairsAsDict
55
- out .pairs .update (pairs )
54
+ out .bins = binsAsDict
55
+ out .bins .update (bins )
56
56
out .contentType = contentType
57
57
return out .specialize ()
58
58
@@ -70,55 +70,55 @@ def __init__(self, quantity, value=Count()):
70
70
71
71
Other Parameters:
72
72
entries (float): the number of entries, initially 0.0.
73
- pairs (dict from str to :doc:`Container <histogrammar.defs.Container>`): the map, probably a hashmap, to fill with values when their `entries` become non-zero.
73
+ bins (dict from str to :doc:`Container <histogrammar.defs.Container>`): the map, probably a hashmap, to fill with values when their `entries` become non-zero.
74
74
"""
75
75
if value is not None and not isinstance (value , Container ):
76
76
raise TypeError ("value ({0}) must be None or a Container" .format (value ))
77
77
self .entries = 0.0
78
78
self .quantity = serializable (quantity )
79
79
self .value = value
80
- self .pairs = {}
80
+ self .bins = {}
81
81
if value is not None :
82
82
self .contentType = str (value .factory .name )
83
83
super (Categorize , self ).__init__ ()
84
84
self .specialize ()
85
85
86
86
@property
87
- def pairsMap (self ):
88
- """Input ``pairs `` as a key-value map."""
89
- return self .pairs
87
+ def binsMap (self ):
88
+ """Input ``bins `` as a key-value map."""
89
+ return self .bins
90
90
91
91
@property
92
92
def size (self ):
93
- """Number of ``pairs ``."""
94
- return len (self .pairs )
93
+ """Number of ``bins ``."""
94
+ return len (self .bins )
95
95
96
96
@property
97
97
def keys (self ):
98
- """Iterable over the keys of the ``pairs ``."""
99
- return self .pairs .keys ()
98
+ """Iterable over the keys of the ``bins ``."""
99
+ return self .bins .keys ()
100
100
101
101
@property
102
102
def values (self ):
103
- """Iterable over the values of the ``pairs ``."""
104
- return list (self .pairs .values ())
103
+ """Iterable over the values of the ``bins ``."""
104
+ return list (self .bins .values ())
105
105
106
106
@property
107
107
def keySet (self ):
108
- """Set of keys among the ``pairs ``."""
109
- return set (self .pairs .keys ())
108
+ """Set of keys among the ``bins ``."""
109
+ return set (self .bins .keys ())
110
110
111
111
def __call__ (self , x ):
112
112
"""Attempt to get key ``x``, throwing an exception if it does not exist."""
113
- return self .pairs [x ]
113
+ return self .bins [x ]
114
114
115
115
def get (self , x ):
116
116
"""Attempt to get key ``x``, returning ``None`` if it does not exist."""
117
- return self .pairs .get (x )
117
+ return self .bins .get (x )
118
118
119
119
def getOrElse (self , x , default ):
120
120
"""Attempt to get key ``x``, returning an alternative if it does not exist."""
121
- return self .pairs .get (x , default )
121
+ return self .bins .get (x , default )
122
122
123
123
@inheritdoc (Container )
124
124
def zero (self ): return Categorize (self .quantity , self .value )
@@ -128,14 +128,14 @@ def __add__(self, other):
128
128
if isinstance (other , Categorize ):
129
129
out = Categorize (self .quantity , self .value )
130
130
out .entries = self .entries + other .entries
131
- out .pairs = {}
131
+ out .bins = {}
132
132
for k in self .keySet .union (other .keySet ):
133
- if k in self .pairs and k in other .pairs :
134
- out .pairs [k ] = self .pairs [k ] + other .pairs [k ]
135
- elif k in self .pairs :
136
- out .pairs [k ] = self .pairs [k ].copy ()
133
+ if k in self .bins and k in other .bins :
134
+ out .bins [k ] = self .bins [k ] + other .bins [k ]
135
+ elif k in self .bins :
136
+ out .bins [k ] = self .bins [k ].copy ()
137
137
else :
138
- out .pairs [k ] = other .pairs [k ].copy ()
138
+ out .bins [k ] = other .bins [k ].copy ()
139
139
return out .specialize ()
140
140
141
141
else :
@@ -150,9 +150,9 @@ def fill(self, datum, weight=1.0):
150
150
if not isinstance (q , basestring ):
151
151
raise TypeError ("function return value ({0}) must be a string" .format (q ))
152
152
153
- if q not in self .pairs :
154
- self .pairs [q ] = self .value .zero ()
155
- self .pairs [q ].fill (datum , weight )
153
+ if q not in self .bins :
154
+ self .bins [q ] = self .value .zero ()
155
+ self .bins [q ].fill (datum , weight )
156
156
157
157
# no possibility of exception from here on out (for rollback)
158
158
self .entries += weight
@@ -161,29 +161,29 @@ def _cppGenerateCode(self, parser, generator, inputFieldNames, inputFieldTypes,
161
161
normexpr = self ._c99QuantityExpr (parser , generator , inputFieldNames , inputFieldTypes , derivedFieldTypes , derivedFieldExprs , None )
162
162
163
163
initCode .append (" " * initIndent + self ._c99ExpandPrefix (* initPrefix ) + ".entries = 0.0;" )
164
- initCode .append (" " * initIndent + self ._c99ExpandPrefix (* initPrefix ) + ".pairs .clear();" )
164
+ initCode .append (" " * initIndent + self ._c99ExpandPrefix (* initPrefix ) + ".bins .clear();" )
165
165
fillCode .append (" " * fillIndent + self ._c99ExpandPrefix (* fillPrefix ) + ".entries += " + weightVarStack [- 1 ] + ";" )
166
166
167
167
value = "value_" + str (len (tmpVarTypes ))
168
168
tmpVarTypes [value ] = self .value ._c99StorageType () + "*"
169
169
170
- fillCode .append ("""{indent}if ({pairs }.find({q}) == {pairs }.end())
171
- {indent} {pairs }[{q}] = {prototype}; // copy
172
- {indent}{value} = &({pairs }[{q}]); // reference""" .format (
170
+ fillCode .append ("""{indent}if ({bins }.find({q}) == {bins }.end())
171
+ {indent} {bins }[{q}] = {prototype}; // copy
172
+ {indent}{value} = &({bins }[{q}]); // reference""" .format (
173
173
indent = " " * fillIndent ,
174
174
q = normexpr ,
175
175
value = value ,
176
176
prototype = self ._c99ExpandPrefix (* fillPrefix ) + ".value" ,
177
- pairs = self ._c99ExpandPrefix (* fillPrefix ) + ".pairs " ))
177
+ bins = self ._c99ExpandPrefix (* fillPrefix ) + ".bins " ))
178
178
179
179
self .value ._c99GenerateCode (parser , generator , inputFieldNames , inputFieldTypes , derivedFieldTypes , derivedFieldExprs , storageStructs , initCode , initPrefix + (("var" , "value" ),), initIndent , fillCode , (("var" , "(*" + value + ")" ),), fillIndent , weightVars , weightVarStack , tmpVarTypes )
180
180
181
181
storageStructs [self ._c99StructName ()] = """
182
182
typedef struct {{
183
183
double entries;
184
184
{1} value;
185
- std::unordered_map<std::string, {1}> pairs ;
186
- {1}& getValues(std::string i) {{ return pairs [i]; }}
185
+ std::unordered_map<std::string, {1}> bins ;
186
+ {1}& getValues(std::string i) {{ return bins [i]; }}
187
187
}} {0};
188
188
""" .format (self ._c99StructName (), self .value ._c99StorageType ())
189
189
@@ -194,11 +194,11 @@ def _clingUpdate(self, filler, *extractorPrefix):
194
194
obj = self ._clingExpandPrefix (filler , * extractorPrefix )
195
195
self .entries += obj .entries
196
196
197
- for i in obj .pairs :
197
+ for i in obj .bins :
198
198
key = i .first
199
- if key not in self .pairs :
200
- self .pairs [key ] = self .value .copy ()
201
- self .pairs [key ]._clingUpdate (obj , ("func" , ["getValues" , key ]))
199
+ if key not in self .bins :
200
+ self .bins [key ] = self .value .copy ()
201
+ self .bins [key ]._clingUpdate (obj , ("func" , ["getValues" , key ]))
202
202
203
203
def _c99StructName (self ):
204
204
return "Cz" + self .value ._c99StructName ()
@@ -212,17 +212,17 @@ def _numpy(self, data, weights, shape):
212
212
# no possibility of exception from here on out (for rollback)
213
213
for x , w in zip (q , weights ):
214
214
if w > 0.0 :
215
- if x not in self .pairs :
216
- self .pairs [x ] = self .value .zero ()
217
- self .pairs [x ].fill (x , w )
215
+ if x not in self .bins :
216
+ self .bins [x ] = self .value .zero ()
217
+ self .bins [x ].fill (x , w )
218
218
219
219
# no possibility of exception from here on out (for rollback)
220
220
self .entries += float (weights .sum ())
221
221
222
222
@property
223
223
def children (self ):
224
224
"""List of sub-aggregators, to make it possible to walk the tree."""
225
- return [self .value ] + list (self .pairs .values ())
225
+ return [self .value ] + list (self .bins .values ())
226
226
227
227
@inheritdoc (Container )
228
228
def toJsonFragment (self , suppressName ):
@@ -233,11 +233,11 @@ def toJsonFragment(self, suppressName):
233
233
binsName = self .value .quantityName
234
234
else :
235
235
binsName = None
236
- elif len (self .pairs ) > 0 :
237
- if getattr (list (self .pairs .values ())[0 ], "quantity" , None ) is not None :
238
- binsName = list (self .pairs .values ())[0 ].quantity .name
239
- elif getattr (list (self .pairs .values ())[0 ], "quantityName" , None ) is not None :
240
- binsName = list (self .pairs .values ())[0 ].quantityName
236
+ elif len (self .bins ) > 0 :
237
+ if getattr (list (self .bins .values ())[0 ], "quantity" , None ) is not None :
238
+ binsName = list (self .bins .values ())[0 ].quantity .name
239
+ elif getattr (list (self .bins .values ())[0 ], "quantityName" , None ) is not None :
240
+ binsName = list (self .bins .values ())[0 ].quantityName
241
241
else :
242
242
binsName = None
243
243
else :
@@ -246,7 +246,7 @@ def toJsonFragment(self, suppressName):
246
246
return maybeAdd ({
247
247
"entries" : floatToJson (self .entries ),
248
248
"bins:type" : self .value .name if self .value is not None else self .contentType ,
249
- "bins" : dict ((k , v .toJsonFragment (True )) for k , v in self .pairs .items ()),
249
+ "bins" : dict ((k , v .toJsonFragment (True )) for k , v in self .bins .items ()),
250
250
}, ** {"name" : None if suppressName else self .quantity .name ,
251
251
"bins:name" : binsName })
252
252
@@ -280,11 +280,11 @@ def fromJsonFragment(json, nameFromParent):
280
280
raise JsonFormatException (json ["bins:name" ], "Categorize.bins:name" )
281
281
282
282
if isinstance (json ["bins" ], dict ):
283
- pairs = dict ((k , factory .fromJsonFragment (v , dataName )) for k , v in json ["bins" ].items ())
283
+ bins = dict ((k , factory .fromJsonFragment (v , dataName )) for k , v in json ["bins" ].items ())
284
284
else :
285
285
raise JsonFormatException (json , "Categorize.bins" )
286
286
287
- out = Categorize .ed (entries , contentType , ** pairs )
287
+ out = Categorize .ed (entries , contentType , ** bins )
288
288
out .quantity .name = nameFromParent if name is None else name
289
289
return out .specialize ()
290
290
@@ -295,11 +295,11 @@ def __repr__(self):
295
295
return "<Categorize values={0} size={1}" .format (self .values [0 ].name if self .size > 0 else self .value .name if self .value is not None else self .contentType , self .size )
296
296
297
297
def __eq__ (self , other ):
298
- return isinstance (other , Categorize ) and numeq (self .entries , other .entries ) and self .quantity == other .quantity and self .pairs == other .pairs
298
+ return isinstance (other , Categorize ) and numeq (self .entries , other .entries ) and self .quantity == other .quantity and self .bins == other .bins
299
299
300
300
def __ne__ (self , other ): return not self == other
301
301
302
302
def __hash__ (self ):
303
- return hash ((self .entries , self .quantity , tuple (sorted (self .pairs .items ()))))
303
+ return hash ((self .entries , self .quantity , tuple (sorted (self .bins .items ()))))
304
304
305
305
Factory .register (Categorize )
0 commit comments