-
Notifications
You must be signed in to change notification settings - Fork 35
/
h1d.go
519 lines (468 loc) · 12.1 KB
/
h1d.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
// Copyright 2015 The go-hep Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package hbook
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/gob"
"fmt"
"io"
"math"
"go-hep.org/x/hep/rio"
)
// H1D is a 1-dim histogram with weighted entries.
type H1D struct {
Binning Binning1D
Ann Annotation
}
// NewH1D returns a 1-dim histogram with n bins between xmin and xmax.
func NewH1D(n int, xmin, xmax float64) *H1D {
return &H1D{
Binning: newBinning1D(n, xmin, xmax),
Ann: make(Annotation),
}
}
// NewH1DFromEdges returns a 1-dim histogram given a slice of edges.
// The number of bins is thus len(edges)-1.
// It panics if the length of edges is <= 1.
// It panics if the edges are not sorted.
// It panics if there are duplicate edge values.
func NewH1DFromEdges(edges []float64) *H1D {
return &H1D{
Binning: newBinning1DFromEdges(edges),
Ann: make(Annotation),
}
}
// NewH1DFromBins returns a 1-dim histogram given a slice of 1-dim bins.
// It panics if the length of bins is < 1.
// It panics if the bins overlap.
func NewH1DFromBins(bins ...Range) *H1D {
return &H1D{
Binning: newBinning1DFromBins(bins),
Ann: make(Annotation),
}
}
// Name returns the name of this histogram, if any
func (h *H1D) Name() string {
v, ok := h.Ann["name"]
if !ok {
return ""
}
n, ok := v.(string)
if !ok {
return ""
}
return n
}
// Annotation returns the annotations attached to this histogram
func (h *H1D) Annotation() Annotation {
return h.Ann
}
// Rank returns the number of dimensions for this histogram
func (h *H1D) Rank() int {
return 1
}
// Entries returns the number of entries in this histogram
func (h *H1D) Entries() int64 {
return h.Binning.entries()
}
// EffEntries returns the number of effective entries in this histogram
func (h *H1D) EffEntries() float64 {
return h.Binning.effEntries()
}
// SumW returns the sum of weights in this histogram.
// Overflows are included in the computation.
func (h *H1D) SumW() float64 {
return h.Binning.Dist.SumW()
}
// SumW2 returns the sum of squared weights in this histogram.
// Overflows are included in the computation.
func (h *H1D) SumW2() float64 {
return h.Binning.Dist.SumW2()
}
// SumWX returns the 1st order weighted x moment
func (h *H1D) SumWX() float64 {
return h.Binning.Dist.SumWX()
}
// SumWX2 returns the 2nd order weighted x moment
func (h *H1D) SumWX2() float64 {
return h.Binning.Dist.SumWX2()
}
// XMean returns the mean X.
// Overflows are included in the computation.
func (h *H1D) XMean() float64 {
return h.Binning.Dist.mean()
}
// XVariance returns the variance in X.
// Overflows are included in the computation.
func (h *H1D) XVariance() float64 {
return h.Binning.Dist.variance()
}
// XStdDev returns the standard deviation in X.
// Overflows are included in the computation.
func (h *H1D) XStdDev() float64 {
return h.Binning.Dist.stdDev()
}
// XStdErr returns the standard error in X.
// Overflows are included in the computation.
func (h *H1D) XStdErr() float64 {
return h.Binning.Dist.stdErr()
}
// XRMS returns the XRMS in X.
// Overflows are included in the computation.
func (h *H1D) XRMS() float64 {
return h.Binning.Dist.rms()
}
// Fill fills this histogram with x and weight w.
func (h *H1D) Fill(x, w float64) {
h.Binning.fill(x, w)
}
// Bin returns the bin at coordinates (x) for this 1-dim histogram.
// Bin returns nil for under/over flow bins.
func (h *H1D) Bin(x float64) *Bin1D {
idx := h.Binning.coordToIndex(x)
if idx < 0 {
return nil
}
return &h.Binning.Bins[idx]
}
// XMin returns the low edge of the X-axis of this histogram.
func (h *H1D) XMin() float64 {
return h.Binning.xMin()
}
// XMax returns the high edge of the X-axis of this histogram.
func (h *H1D) XMax() float64 {
return h.Binning.xMax()
}
// Scale scales the content of each bin by the given factor.
func (h *H1D) Scale(factor float64) {
h.Binning.scaleW(factor)
}
// Integral computes the integral of the histogram.
//
// The number of parameters can be 0 or 2.
// If 0, overflows are included.
// If 2, the first parameter must be the lower bound of the range in which
// the integral is computed and the second one the upper range.
//
// If the lower bound is math.Inf(-1) then the underflow bin is included.
// If the upper bound is math.Inf(+1) then the overflow bin is included.
//
// Examples:
//
// // integral of all in-range bins + overflows
// v := h.Integral()
//
// // integral of all in-range bins, underflow and overflow bins included.
// v := h.Integral(math.Inf(-1), math.Inf(+1))
//
// // integrall of all in-range bins, overflow bin included
// v := h.Integral(h.Binning().LowerEdge(), math.Inf(+1))
//
// // integrall of all bins for which the lower edge is in [0.5, 5.5)
// v := h.Integral(0.5, 5.5)
func (h *H1D) Integral(args ...float64) float64 {
min, max := 0., 0.
switch len(args) {
case 0:
return h.SumW()
case 2:
min = args[0]
max = args[1]
if min > max {
panic("hbook: min > max")
}
default:
panic("hbook: invalid number of arguments. expected 0 or 2.")
}
integral := 0.0
for _, bin := range h.Binning.Bins {
v := bin.Range.Min
if min <= v && v < max {
integral += bin.SumW()
}
}
if math.IsInf(min, -1) {
integral += h.Binning.Outflows[0].SumW()
}
if math.IsInf(max, +1) {
integral += h.Binning.Outflows[1].SumW()
}
return integral
}
// Value returns the content of the idx-th bin.
//
// Value implements gonum/plot/plotter.Valuer
func (h *H1D) Value(i int) float64 {
return h.Binning.Bins[i].SumW()
}
// Len returns the number of bins for this histogram
//
// Len implements gonum/plot/plotter.Valuer
func (h *H1D) Len() int {
return len(h.Binning.Bins)
}
// XY returns the x,y values for the i-th bin
//
// XY implements gonum/plot/plotter.XYer
func (h *H1D) XY(i int) (float64, float64) {
bin := h.Binning.Bins[i]
x := bin.Range.Min
y := bin.SumW()
return x, y
}
// DataRange implements the gonum/plot.DataRanger interface
func (h *H1D) DataRange() (xmin, xmax, ymin, ymax float64) {
xmin = h.XMin()
xmax = h.XMax()
ymin = +math.MaxFloat64
ymax = -math.MaxFloat64
for _, b := range h.Binning.Bins {
v := b.SumW()
ymax = math.Max(ymax, v)
ymin = math.Min(ymin, v)
}
return xmin, xmax, ymin, ymax
}
// RioMarshal implements rio.RioMarshaler
func (h *H1D) RioMarshal(w io.Writer) error {
data, err := h.MarshalBinary()
if err != nil {
return err
}
var buf [8]byte
binary.LittleEndian.PutUint64(buf[:], uint64(len(data)))
_, err = w.Write(buf[:])
if err != nil {
return err
}
_, err = w.Write(data)
return err
}
// RioUnmarshal implements rio.RioUnmarshaler
func (h *H1D) RioUnmarshal(r io.Reader) error {
buf := make([]byte, 8)
_, err := io.ReadFull(r, buf)
if err != nil {
return err
}
n := int64(binary.LittleEndian.Uint64(buf))
buf = make([]byte, int(n))
_, err = io.ReadFull(r, buf)
if err != nil {
return err
}
return h.UnmarshalBinary(buf)
}
// RioVersion implements rio.RioStreamer
func (h *H1D) RioVersion() rio.Version {
return 0
}
// annToYODA creates a new Annotation with fields compatible with YODA
func (h *H1D) annToYODA() Annotation {
ann := make(Annotation, len(h.Ann))
ann["Type"] = "Histo1D"
ann["Path"] = "/" + h.Name()
ann["Title"] = ""
for k, v := range h.Ann {
if k == "name" {
continue
}
if k == "title" {
ann["Title"] = v
continue
}
ann[k] = v
}
return ann
}
// annFromYODA creates a new Annotation from YODA compatible fields
func (h *H1D) annFromYODA(ann Annotation) {
if len(h.Ann) == 0 {
h.Ann = make(Annotation, len(ann))
}
for k, v := range ann {
switch k {
case "Type":
// noop
case "Path":
h.Ann["name"] = string(v.(string)[1:]) // skip leading '/'
case "Title":
h.Ann["title"] = v.(string)
default:
h.Ann[k] = v
}
}
}
// MarshalYODA implements the YODAMarshaler interface.
func (h *H1D) MarshalYODA() ([]byte, error) {
buf := new(bytes.Buffer)
ann := h.annToYODA()
fmt.Fprintf(buf, "BEGIN YODA_HISTO1D %s\n", ann["Path"])
data, err := ann.MarshalYODA()
if err != nil {
return nil, err
}
buf.Write(data)
fmt.Fprintf(buf, "# Mean: %e\n", h.XMean())
fmt.Fprintf(buf, "# Area: %e\n", h.Integral())
fmt.Fprintf(buf, "# ID\t ID\t sumw\t sumw2\t sumwx\t sumwx2\t numEntries\n")
d := h.Binning.Dist
fmt.Fprintf(
buf,
"Total \tTotal \t%e\t%e\t%e\t%e\t%d\n",
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.Entries(),
)
d = h.Binning.Outflows[0]
fmt.Fprintf(
buf,
"Underflow\tUnderflow\t%e\t%e\t%e\t%e\t%d\n",
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.Entries(),
)
d = h.Binning.Outflows[1]
fmt.Fprintf(
buf,
"Overflow\tOverflow\t%e\t%e\t%e\t%e\t%d\n",
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.Entries(),
)
// bins
fmt.Fprintf(buf, "# xlow\t xhigh\t sumw\t sumw2\t sumwx\t sumwx2\t numEntries\n")
for _, bin := range h.Binning.Bins {
d := bin.Dist
fmt.Fprintf(
buf,
"%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
bin.Range.Min, bin.Range.Max,
d.SumW(), d.SumW2(), d.SumWX(), d.SumWX2(), d.Entries(),
)
}
fmt.Fprintf(buf, "END YODA_HISTO1D\n\n")
return buf.Bytes(), err
}
// UnmarshalYODA implements the YODAUnmarshaler interface.
func (h *H1D) UnmarshalYODA(data []byte) error {
r := bytes.NewBuffer(data)
_, err := readYODAHeader(r, "BEGIN YODA_HISTO1D")
if err != nil {
return err
}
ann := make(Annotation)
// pos of end of annotations
pos := bytes.Index(r.Bytes(), []byte("\n# Mean:"))
if pos < 0 {
return fmt.Errorf("hbook: invalid H1D-YODA data")
}
err = ann.UnmarshalYODA(r.Bytes()[:pos+1])
if err != nil {
return fmt.Errorf("hbook: %v\nhbook: %q", err, string(r.Bytes()[:pos+1]))
}
h.annFromYODA(ann)
r.Next(pos)
var ctx struct {
total bool
under bool
over bool
bins bool
}
// sets of xlow values, to infer number of bins in X.
xset := make(map[float64]int)
var (
dist Dist1D
oflows [2]Dist1D
bins []Bin1D
xmin = math.Inf(+1)
xmax = math.Inf(-1)
)
s := bufio.NewScanner(r)
scanLoop:
for s.Scan() {
buf := s.Bytes()
if len(buf) == 0 || buf[0] == '#' {
continue
}
rbuf := bytes.NewReader(buf)
switch {
case bytes.HasPrefix(buf, []byte("END YODA_HISTO1D")):
break scanLoop
case !ctx.total && bytes.HasPrefix(buf, []byte("Total \t")):
ctx.total = true
d := &dist
_, err = fmt.Fscanf(
rbuf,
"Total \tTotal \t%e\t%e\t%e\t%e\t%d\n",
&d.Dist.SumW, &d.Dist.SumW2,
&d.Stats.SumWX, &d.Stats.SumWX2,
&d.Dist.N,
)
if err != nil {
return fmt.Errorf("hbook: %v\nhbook: %q", err, string(buf))
}
case !ctx.under && bytes.HasPrefix(buf, []byte("Underflow\t")):
ctx.under = true
d := &oflows[0]
_, err = fmt.Fscanf(
rbuf,
"Underflow\tUnderflow\t%e\t%e\t%e\t%e\t%d\n",
&d.Dist.SumW, &d.Dist.SumW2,
&d.Stats.SumWX, &d.Stats.SumWX2,
&d.Dist.N,
)
if err != nil {
return fmt.Errorf("hbook: %v\nhbook: %q", err, string(buf))
}
case !ctx.over && bytes.HasPrefix(buf, []byte("Overflow\t")):
ctx.over = true
d := &oflows[1]
_, err = fmt.Fscanf(
rbuf,
"Overflow\tOverflow\t%e\t%e\t%e\t%e\t%d\n",
&d.Dist.SumW, &d.Dist.SumW2,
&d.Stats.SumWX, &d.Stats.SumWX2,
&d.Dist.N,
)
if err != nil {
return fmt.Errorf("hbook: %v\nhbook: %q", err, string(buf))
}
ctx.bins = true
case ctx.bins:
var bin Bin1D
d := &bin.Dist
_, err = fmt.Fscanf(
rbuf,
"%e\t%e\t%e\t%e\t%e\t%e\t%d\n",
&bin.Range.Min, &bin.Range.Max,
&d.Dist.SumW, &d.Dist.SumW2,
&d.Stats.SumWX, &d.Stats.SumWX2,
&d.Dist.N,
)
if err != nil {
return fmt.Errorf("hbook: %v\nhbook: %q", err, string(buf))
}
xset[bin.Range.Min] = 1
xmin = math.Min(xmin, bin.Range.Min)
xmax = math.Max(xmax, bin.Range.Max)
bins = append(bins, bin)
default:
return fmt.Errorf("hbook: invalid H1D-YODA data: %q", string(buf))
}
}
h.Binning = Binning1D{
Bins: bins,
Dist: dist,
Outflows: oflows,
XRange: Range{xmin, xmax},
}
return err
}
// check various interfaces
var _ Object = (*H1D)(nil)
var _ Histogram = (*H1D)(nil)
// serialization interfaces
var _ rio.Marshaler = (*H1D)(nil)
var _ rio.Unmarshaler = (*H1D)(nil)
var _ rio.Streamer = (*H1D)(nil)
func init() {
gob.Register((*H1D)(nil))
}