Hammer  1.0.0
Helicity Amplitude Module for Matrix Element Reweighting
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
hammerlib.pyx
Go to the documentation of this file.
1 #**** This file is a part of the HAMMER library
2 #**** Copyright (C) 2016 - 2020 The HAMMER Collaboration
3 #**** HAMMER is licensed under version 3 of the GPL; see COPYING for details
4 #**** Please note the MCnet academic guidelines; see GUIDELINES for details
5 
6 ## \file hammerlib.pyx
7 # \brief Cython class to wrap Hammer library
8 #
9 
10 # distutils: language = c++
11 # cython: c_string_type=unicode, c_string_encoding=default
12 
13 from typing import List, Set, Dict, Tuple, Optional, FrozenSet, AnyStr, Union, Any
14 from numbers import Number
15 
17 Vec3 = Tuple[float, float, float]
18 
19 from cppdefs cimport Hammer as cpp_Hammer
20 from cppdefs cimport Process as cpp_Process
21 from cppdefs cimport Particle as cpp_Particle
22 from cppdefs cimport FourMomentum as cpp_FourMomentum
23 from cppdefs cimport IOBuffer as cpp_IOBuffer
24 from cppdefs cimport IOBuffers as cpp_IOBuffers
25 from cppdefs cimport WTerm as cpp_WTerm
26 from cppdefs cimport HistoInfo as cpp_HistoInfo
27 from cppdefs cimport RecordType as cpp_RecordType
28 from cppdefs cimport BinContents as cpp_BinContents
29 from cppdefs cimport UMap as cpp_UMap
30 from cppdefs cimport Log as cpp_Log
31 from cppdefs cimport version as cpp_version
32 
33 from cpython cimport array
34 import array
35 from cpython cimport Py_buffer
36 
37 from io import FileIO
38 from struct import pack, unpack, calcsize
39 from enum import Enum, IntEnum
40 
41 from libc.stdint cimport uint8_t
42 from libcpp.string cimport string
43 from libcpp.map cimport map as cmap
44 from libcpp.pair cimport pair
45 from libcpp.vector cimport vector
46 from libcpp.memory cimport unique_ptr
47 from libcpp.set cimport set as cset
48 from cython.operator import dereference as deref, preincrement as inc
49 from cpython cimport bool
50 
51 from cymove cimport cymove as move
52 from cpython.version cimport PY_MAJOR_VERSION
53 
54 import cmath
55 
56 HAVE_NUMPY = True
57 try:
58  import numpy as np
59 except:
60  HAVE_NUMPY = False
61 
62 def _is_string(value: Any) -> bool:
63  return isinstance(value, (str, bytes, bytearray))
64 
65 def _is_set(value: Any) -> bool:
66  return isinstance(value, (set, frozenset))
67 
68 def _is_event_uid_group(value: Any) -> bool:
69  return (_is_set(value) and
70  all([(_is_set(elem) and
71  all([(type(elem2) is int and elem2>0)
72  for elem2 in elem]))
73  for elem in value]))
74 
75 def _is_list_of_string(value: Any) -> bool:
76  return (isinstance(value, list) and all([_is_string(elem) for elem in value]))
77 
78 def _is_list_of_list_of_string(value: Any) -> bool:
79  return (isinstance(value, list) and all([_is_list_of_string(elem) for elem in value]))
80 
81 def _is_vec_float(value: Any) -> bool:
82  return (isinstance(value, list) and all([type(elem) is float for elem in value]))
83 
84 def _is_vec_complex(value: Any) -> bool:
85  return (isinstance(value, list) and all([isinstance(elem, Number) for elem in value]))
86 
87 def _is_vec_int(value: Any) -> bool:
88  return (isinstance(value, list) and all([type(elem) is int for elem in value]))
89 
90 def _is_dict_float(value: Any) -> bool:
91  return (isinstance(value, dict) and all([(type(elem_v) is float and _is_string(elem_k)) for elem_k, elem_v in value.iteritems()]))
92 
93 def _is_dict_complex(value: Any) -> bool:
94  return (isinstance(value, dict) and all([(isinstance(elem_v, Number) and _is_string(elem_k)) for elem_k, elem_v in value.iteritems()]))
95 
96 cdef _to_set_of_sets(cset[cset[size_t]] value):
97  return frozenset([frozenset([int(elem2) for elem2 in elem]) for elem in value])
98 
99 class WTerm(Enum):
100  COMMON = 0
101  NUMERATOR = 1
102  DENOMINATOR = 2
103 
104 cdef cpp_WTerm _to_cpp_wterm(arg):
105  if arg == WTerm.COMMON:
106  return cpp_WTerm.COMMON
107  elif arg == WTerm.NUMERATOR:
108  return cpp_WTerm.NUMERATOR
109  elif arg == WTerm.DENOMINATOR:
110  return cpp_WTerm.DENOMINATOR
111  else:
112  return cpp_WTerm.COMMON
113 
114 class RecordType(IntEnum):
115  UNDEFINED = ord('u')
116  HEADER = ord('b')
117  EVENT = ord('e')
118  HISTOGRAM = ord('h')
119  RATE = ord('r')
120  HISTOGRAM_DEFINITION = ord('d')
121 
122 cdef class HistoInfo:
123 
124  cdef cpp_HistoInfo c_histo_info
125 
126  cdef from_cpp(self, cpp_HistoInfo info):
127  self.c_histo_info = info
128 
129  # Attribute access
130  @property
131  def name(self) -> AnyStr:
132  return self.c_histo_info.name
133  @name.setter
134  def name(self, name: AnyStr):
135  self.c_histo_info.name = name
136 
137  @property
138  def scheme(self) -> AnyStr:
139  return self.c_histo_info.scheme
140  @scheme.setter
141  def scheme(self, scheme: AnyStr):
142  self.c_histo_info.scheme = scheme
143 
144  @property
145  def event_group_id(self) -> EventUIDGroup:
146  return set([frozenset(elem) for elem in self.c_histo_info.eventGroupId])
147  @event_group_id.setter
148  def event_group_id(self, event_group_id: EventUIDGroup):
149  self.c_histo_info.eventGroupId = event_group_id
150 
151 cdef class BinContents:
152 
153  cdef cpp_BinContents c_bins
154 
155  @staticmethod
156  cdef from_cpp(cpp_BinContents value):
157  result = BinContents()
158  result.c_bins = value
159  return result
160 
161  @property
162  def sum_wi(self) -> float:
163  return self.c_bins.sumWi
164  @sum_wi.setter
165  def sum_wi(self, sum_wi: float):
166  self.c_bins.sumWi = sum_wi
167 
168  @property
169  def sum_wi2(self) -> float:
170  return self.c_bins.sumWi2
171  @sum_wi2.setter
172  def sum_wi2(self, sum_wi2: float):
173  self.c_bins.sumWi2 = sum_wi2
174 
175  @property
176  def n(self) -> int:
177  return self.c_bins.n
178  @n.setter
179  def n(self, n: int):
180  self.c_bins.n = n
181 
182 cdef class IOBuffers:
183 
184  cdef cpp_IOBuffers* p_io_buffers
185  cdef cpp_IOBuffers.iterator curr_it
186 
187  def __cinit__(self):
188  self.p_io_buffers = new cpp_IOBuffers()
189  self.curr_it = self.p_io_buffers.begin()
190 
191  def __dealloc__(self):
192  del self.p_io_buffers
193 
194  cdef from_cpp(self, cpp_IOBuffers buf):
195  del self.p_io_buffers
196  self.p_io_buffers = new cpp_IOBuffers(move(buf))
197  self.curr_it = self.p_io_buffers.begin()
198 
199  def __iter__(self):
200  self.curr_it = self.p_io_buffers.begin()
201  return self
202 
203  def __next__(self):
204  if self.curr_it == self.p_io_buffers.end():
205  raise StopIteration
206  result = IOBuffer()
207  result.from_cpp(deref(self.curr_it))
208  inc(self.curr_it)
209  return result
210 
211  def save(self, file_handler : FileIO):
212  cdef cpp_IOBuffers.iterator it = self.p_io_buffers.begin()
213  while it != self.p_io_buffers.end():
214  result = IOBuffer()
215  result.from_cpp(deref(it))
216  result.save(file_handler)
217  inc(it)
218 
219 cdef class IOBuffer:
220 
221  cdef cpp_IOBuffer c_buffer
222  cdef array.array buf
223  cdef int view_count
224  cdef Py_ssize_t strides
225 
226  def __cinit__(self):
227  self.buf = array.array('B', [0]*1000)
228  self.c_buffer.kind = cpp_RecordType.UNDEFINED
229  self.c_buffer.length = len(self.buf)
230  self.c_buffer.start = <uint8_t*>(&self.buf.data.as_uchars[0])
231  self.view_count = 0
232 
233  def __len__(self):
234  return self.c_buffer.length
235 
236  def __getbuffer__(self, Py_buffer *view, int flags):
237  cdef Py_ssize_t itemsize = 1
238  view.buf = <unsigned char *> self.c_buffer.start
239  view.format = 'B'
240  view.internal = NULL
241  view.itemsize = 1
242  view.len = self.c_buffer.length
243  view.ndim = 1
244  view.obj = self
245  view.readonly = 0
246  view.shape = <Py_ssize_t*> &self.c_buffer.length
247  view.strides = &itemsize
248  view.suboffsets = NULL
249  self.view_count += 1
250 
251  def __releasebuffer__(self, Py_buffer *buffer):
252  self.view_count -= 1
253 
254  cdef from_cpp(self, cpp_IOBuffer buf):
255  if self.view_count > 0:
256  raise ValueError("can't edit buffer while it's accessed via buffer protocol")
257  self.c_buffer = buf
258  self.view_count = 0
259 
260  cdef cpp_IOBuffer* to_cpp(self):
261  return &self.c_buffer
262 
263  cpdef init_from_size(self, int data_size = 0):
264  if self.view_count > 0:
265  raise ValueError("can't edit buffer while it's accessed via buffer protocol")
266  array.resize(self.buf, data_size)
267  self.c_buffer.kind = cpp_RecordType.UNDEFINED
268  self.c_buffer.length = len(self.buf)
269  self.c_buffer.start = <uint8_t*>(&self.buf.data.as_uchars[0])
270  self.view_count = 0
271 
272  @property
273  def kind(self) -> RecordType:
274  return self.c_buffer.kind
275 
276  @kind.setter
277  def kind(self, kind: RecordType):
278  self.c_buffer.kind = <cpp_RecordType>(kind)
279 
280  def save(self, file_handler : FileIO):
281  file_handler.write(pack(b'b', self.c_buffer.kind))
282  file_handler.write(pack(b'<L', self.c_buffer.length))
283  file_handler.write(self)
284 
285  def load(self, file_handler : FileIO):
286  tmp = file_handler.read(1)
287  if len(tmp) == 0:
288  return False
289  typebuf = unpack(b'b',tmp)
290  form = b'<L'
291  sizebuf = unpack(form, file_handler.read(calcsize(form)))[0]
292  self.init_from_size(sizebuf)
293  self.c_buffer.kind = <cpp_RecordType>(typebuf[0])
294  file_handler.readinto(self)
295  return True
296 
297 
298 cdef class FourMomentum:
299 
300  cdef cpp_FourMomentum c_mom
301 
302  def __cinit__(self, e: float = 0., px: float = 0., py: float = 0., pz: float = 0.):
303  self.c_mom = cpp_FourMomentum(e, px, py, pz)
304 
305  @staticmethod
306  def fromPtEtaPhiM(pt: float, eta: float, phi: float, m: float) -> FourMomentum:
307  result = FourMomentum()
308  result.c_mom = cpp_FourMomentum.fromPtEtaPhiM(pt, eta, phi, m)
309  return result
310 
311  @staticmethod
312  def fromEtaPhiME(eta: float, phi: float, m: float, e: float) -> FourMomentum:
313  result = FourMomentum()
314  result.c_mom = cpp_FourMomentum.fromEtaPhiME(eta, phi, m, e)
315  return result
316 
317  @staticmethod
318  def fromPM(px: float, py: float, pz: float, m: float) -> FourMomentum:
319  result = FourMomentum()
320  result.c_mom = cpp_FourMomentum.fromPM(px, py, pz, m)
321  return result
322 
323  @property
324  def px(self) -> float:
325  return self.c_mom.px()
326  @px.setter
327  def px(self, value: float):
328  self.c_mom.setPx(value)
329 
330  @property
331  def py(self) -> float:
332  return self.c_mom.py()
333  @py.setter
334  def py(self, value: float):
335  self.c_mom.setPy(value)
336 
337  @property
338  def pz(self) -> float:
339  return self.c_mom.pz()
340  @pz.setter
341  def pz(self, value: float):
342  self.c_mom.setPz(value)
343 
344  @property
345  def e(self) -> float:
346  return self.c_mom.E()
347  @e.setter
348  def e(self, value: float):
349  self.c_mom.setE(value)
350 
351  def mass(self) -> float:
352  return self.c_mom.mass()
353 
354  def mass2(self) -> float:
355  return self.c_mom.mass2()
356 
357  def p(self) -> float:
358  return self.c_mom.p()
359 
360  def p2(self) -> float:
361  return self.c_mom.p2()
362 
363  def pt(self) -> float:
364  return self.c_mom.pt()
365 
366  def rapidity(self) -> float:
367  return self.c_mom.rapidity()
368 
369  def phi(self) -> float:
370  return self.c_mom.phi()
371 
372  def eta(self) -> float:
373  return self.c_mom.eta()
374 
375  def theta(self) -> float:
376  return self.c_mom.theta()
377 
378  def p_vec(self) -> Vec3:
379  res = self.c_mom.pVec()
380  return (res[0], res[1], res[2])
381 
382  def gamma(self) -> float:
383  return self.c_mom.gamma()
384 
385  def beta(self) -> float:
386  return self.c_mom.beta()
387 
388  def boost_vector(self) -> Vec3:
389  res = self.c_mom.boostVector()
390  return (res[0], res[1], res[2])
391 
392 cdef class Particle:
393 
394  cdef cpp_Particle c_part
395 
396  def __cinit__(self, p: FourMomentum = FourMomentum(), pdg: int = 0):
397  self.c_part = cpp_Particle(p.c_mom, pdg)
398 
399  @staticmethod
400  cdef Particle from_cpp(cpp_Particle p):
401  part = Particle()
402  part.c_part = p
403  return part
404 
405  @property
406  def momentum(self) -> FourMomentum:
407  result = FourMomentum()
408  result.c_mom = self.c_part.momentum()
409  return result
410 
411  @momentum.setter
412  def momentum(self, val: FourMomentum):
413  self.c_part.setMomentum(val.c_mom)
414 
415  @property
416  def p(self) -> FourMomentum:
417  result = FourMomentum()
418  result.c_mom = self.c_part.momentum()
419  return result
420 
421  @p.setter
422  def p(self, val: FourMomentum):
423  self.c_part.setMomentum(val.c_mom)
424 
425  @property
426  def pdg_id(self) -> int:
427  return self.c_part.pdgId()
428 
429  @pdg_id.setter
430  def pdg_id(self, val: int):
431  self.c_part.setPdgId(val)
432 
433 
434 cdef class Process:
435 
436  cdef cpp_Process c_proc
437 
438  def add_particle(self, value: Particle):
439  return self.c_proc.addParticle(value.c_part)
440 
441  def add_vertex(self, parent: int, daughters: List[int]):
442  self.c_proc.addVertex(parent, daughters)
443 
444  def remove_vertex(self, vertex_id: int, prune: bool = False):
445  self.c_proc.removeVertex(vertex_id, prune)
446 
447  def get_daughters_ids(self, parent: int = 0):
448  return self.c_proc.getDaughtersIds(parent)
449 
450  def get_parent_id(self, daughter: int):
451  return self.c_proc.getParentId(daughter)
452 
453  def get_siblings_ids(self, particle: int = 0):
454  return self.c_proc.getSiblingsIds(particle)
455 
456  def get_particle(self, id: int):
457  result = Particle()
458  result.c_part = self.c_proc.getParticle(id)
459  return result
460 
461  def get_daughters(self, parent: int = 0, sorted: bool = False):
462  result = self.c_proc.getDaughters(parent, sorted)
463  return [Particle.from_cpp(elem) for elem in result]
464 
465  def get_siblings(self, particle: int = 0, sorted: bool = False):
466  result = self.c_proc.getSiblings(particle, sorted)
467  return [Particle.from_cpp(elem) for elem in result]
468 
469  def get_parent(self, daughter: int):
470  result = Particle()
471  result.c_part = self.c_proc.getParent(daughter)
472  return result
473 
474  def is_parent(self, particle: int):
475  return self.c_proc.isParent(particle)
476 
477  def get_first_vertex(self):
478  return self.c_proc.getFirstVertex()
479 
480  def get_id(self):
481  return self.c_proc.getId()
482 
483  def full_id(self):
484  return self.c_proc.fullId()
485 
486  def get_vertex_id(self, vertex):
487  return self.c_proc.getVertexId(vertex)
488 
489  def num_particles(self, without_photons: bool = False):
490  return self.c_proc.numParticles(without_photons)
491 
492 ## \brief main Hammer python class
493 #
494 # Provides the functionalities of `Hammer::Hammer` visible to a python program
495 #
496 # \ingroup PyExt
497 
498 cdef class Hammer:
499 
500  ## pointer to Hammer::Hammer class
501  cdef cpp_Hammer *wrapped
502 
503  ## base constructor
504  def __cinit__ (self):
505  self.wrapped = new cpp_Hammer()
506  if self.wrapped is NULL:
507  raise MemoryError()
508 
509  ## destructor
510  def __dealloc__ (self):
511  if self.wrapped is not NULL:
512  del self.wrapped
513 
514  def init_run(self):
515  self.wrapped.initRun()
516 
517  def init_event(self, weight: float = 1.0):
518  self.wrapped.initEvent(weight)
519 
520  def add_process(self, proc: Process) -> int:
521  return self.wrapped.addProcess(proc.c_proc)
522 
523  def remove_process(self, proc_id: int):
524  self.wrapped.removeProcess(proc_id)
525 
526  def set_event_histogram_bin(self, name: AnyStr, bins: List[int]):
527  self.wrapped.setEventHistogramBin(name, bins)
528 
529  def fill_event_histogram(self, name: AnyStr, values: List[float]):
530  self.wrapped.fillEventHistogram(name, values)
531 
532  def set_event_base_weight(self, weight: float):
533  self.wrapped.setEventBaseWeight(weight)
534 
535  def process_event(self):
536  self.wrapped.processEvent()
537 
538  def load_event_weights(self, buf: IOBuffer, merge: bool = False) -> bool:
539  return self.wrapped.loadEventWeights(deref(buf.to_cpp()), merge)
540 
541  def save_event_weights(self) -> IOBuffer:
542  result = IOBuffer()
543  result.from_cpp(self.wrapped.saveEventWeights())
544  return result
545 
546  def write_event_weights(self, file_handler: FileIO):
547  file_handler.write(self.save_event_weights())
548 
549  def load_run_header(self, buf: IOBuffer, merge: bool = False) -> bool:
550  return self.wrapped.loadRunHeader(deref(buf.to_cpp()), merge)
551 
552  def save_run_header(self) -> IOBuffer:
553  result = IOBuffer()
554  result.from_cpp(self.wrapped.saveRunHeader())
555  return result
556 
557  def write_run_header(self, file_handler: FileIO):
558  file_handler.write(self.save_run_header())
559 
560  def load_histogram_definition(self, buf: IOBuffer, merge: bool = False) -> AnyStr:
561  return self.wrapped.loadHistogramDefinition(deref(buf.to_cpp()), merge)
562 
563  def load_histogram(self, buf: IOBuffer, merge: bool = False) -> HistoInfo:
564  result = HistoInfo()
565  result.from_cpp(self.wrapped.loadHistogram(deref(buf.to_cpp()), merge))
566  return result
567 
568  def save_histogram(self, name_or_info: Union[AnyStr, HistoInfo]) -> IOBuffers:
569  result = IOBuffers()
570  cdef string s1
571  if _is_string(name_or_info):
572  s1 = name_or_info
573  result.from_cpp(self.wrapped.saveHistogram(s1))
574  elif isinstance(name_or_info, HistoInfo):
575  result.from_cpp(self.wrapped.saveHistogram(((HistoInfo)(name_or_info)).c_histo_info))
576  else:
577  print("Invalid Type")
578  return result
579 
580  def write_histogram(self, file_handler: FileIO, name_or_info: Union[AnyStr, HistoInfo]):
581  for elem in self.save_histogram(name_or_info):
582  file_handler.write(elem)
583 
584  def save_histogram(self, name: AnyStr, scheme_or_event_ids: Union[AnyStr, EventUIDGroup]) -> IOBuffers:
585  result = IOBuffers()
586  cdef string s1 = name
587  cdef string s2
588  cdef cset[cset[size_t]] s3
589  if _is_string(scheme_or_event_ids) == AnyStr:
590  s2 = scheme_or_event_ids
591  result.from_cpp(self.wrapped.saveHistogram(s1, s2))
592  elif _is_event_uid_group(scheme_or_event_ids):
593  s3 = scheme_or_event_ids
594  result.from_cpp(self.wrapped.saveHistogram(s1, s3))
595  else:
596  print("Invalid Type")
597  return result
598 
599  def write_histogram(self, file_handler: FileIO, name: AnyStr, scheme_or_event_ids: Union[AnyStr, EventUIDGroup]):
600  for elem in self.save_histogram(name, scheme_or_event_ids):
601  file_handler.write(elem)
602 
603  def save_histogram(self, name: AnyStr, scheme: AnyStr, event_ids: EventUIDGroup) -> IOBuffers:
604  result = IOBuffers()
605  result.from_cpp(self.wrapped.saveHistogram(name, scheme, event_ids))
606  return result
607 
608  def write_histogram(self, file_handler: FileIO, name: AnyStr, scheme: AnyStr, event_ids: EventUIDGroup):
609  for elem in self.save_histogram(name, scheme, event_ids):
610  file_handler.write(elem)
611 
612  def load_rates(self, buf: IOBuffer, merge: bool = False) -> bool:
613  return self.wrapped.loadRates(deref(buf.to_cpp()), merge)
614 
615  def save_rates(self) -> IOBuffer:
616  result = IOBuffer()
617  result.from_cpp(self.wrapped.saveRates())
618  return result
619 
620  def write_rates(self, file_handler: FileIO):
621  file_handler.write(self.save_rates())
622 
623  def read_cards(self, file_decays: AnyStr, file_options: AnyStr):
624  self.wrapped.readCards(file_decays, file_options)
625 
626  def save_option_card(self, file_options: AnyStr, use_default: bool = True):
627  self.wrapped.saveOptionCard(file_options, use_default)
628 
629  def save_header_card(self, file_decays: AnyStr):
630  self.wrapped.saveHeaderCard(file_decays)
631 
632  def save_references(self, file_refs: AnyStr):
633  self.wrapped.saveReferences(file_refs)
634 
635  def set_options(self, options: AnyStr):
636  self.wrapped.setOptions(options)
637 
638  def set_header(self, options: AnyStr):
639  self.wrapped.setHeader(options)
640 
641  def add_total_sum_of_weights(self, compress: bool = False, with_errors: bool = False):
642  self.wrapped.addTotalSumOfWeights(compress, with_errors)
643 
644  def add_histogram(self, name: AnyStr, bin_sizes: List[int], has_under_over_flow: bool = True, ranges: List[Tuple[float, float]] = []):
645  self.wrapped.addHistogram(name, bin_sizes, has_under_over_flow, ranges)
646 
647  def add_histogram(self, name: AnyStr, bin_edges: List[List[float]], has_under_over_flow: bool):
648  self.wrapped.addHistogram(name, bin_edges, has_under_over_flow)
649 
650  def collapse_processes_in_histogram(self, name: AnyStr):
651  self.wrapped.collapseProcessesInHistogram(name)
652 
653  def keep_errors_in_histogram(self, name: AnyStr, value: bool = True):
654  self.wrapped.keepErrorsInHistogram(name, value)
655 
656  def specialize_WC_in_weights(self, process: AnyStr, values_or_settings: Union[List[complex], Dict[AnyStr, complex]]):
657  cdef string s1 = process
658  cdef vector[double complex] v
659  cdef cmap[string, double complex] d
660  if _is_vec_complex(values_or_settings):
661  v = values_or_settings
662  self.wrapped.specializeWCInWeights(s1, v)
663  elif _is_dict_complex(values_or_settings):
664  d = values_or_settings
665  self.wrapped.specializeWCInWeights(s1, d)
666  else:
667  print("Invalid Type")
668 
669  def reset_specialize_WC_in_weights(self, process: AnyStr):
670  self.wrapped.resetSpecializeWCInWeights(process)
671 
672  def specialize_wc_in_histogram(self, name: AnyStr, process: AnyStr, values_or_settings: Union[List[complex], Dict[AnyStr, complex]]):
673  cdef string s1 = name
674  cdef string s2 = process
675  cdef vector[double complex] v
676  cdef cmap[string, double complex] d
677  if _is_vec_complex(values_or_settings):
678  v = values_or_settings
679  self.wrapped.specializeWCInHistogram(s1, s2, v)
680  elif _is_dict_complex(values_or_settings):
681  d = values_or_settings
682  self.wrapped.specializeWCInHistogram(s1, s2, d)
683  else:
684  print("Invalid Type")
685 
686  def specialize_ff_in_histogram(self, name: AnyStr, process: AnyStr, group: AnyStr, values_or_settings: Union[List[float], Dict[AnyStr, float]]):
687  cdef string s1 = name
688  cdef string s2 = process
689  cdef string s3 = group
690  cdef vector[double] v
691  cdef cmap[string, double] d
692  if _is_vec_float(values_or_settings):
693  v = values_or_settings
694  self.wrapped.specializeFFInHistogram(s1, s2, s3, v)
695  elif _is_dict_float(values_or_settings):
696  d = values_or_settings
697  self.wrapped.specializeFFInHistogram(s1, s2, s3, d)
698  else:
699  print("Invalid Type")
700 
701  def reset_specialization_in_histogram(self, name):
702  self.wrapped.resetSpecializationInHistogram(name)
703 
704  def create_projected_histogram(self, old_name, new_name, collapsed_index_positions: Set[int]):
705  self.wrapped.createProjectedHistogram(old_name, new_name, collapsed_index_positions)
706 
707  def remove_histogram(self, name):
708  self.wrapped.removeHistogram(name)
709 
710  def add_ff_scheme(self, scheme_name, schemes: Dict[AnyStr, AnyStr]):
711  self.wrapped.addFFScheme(scheme_name, schemes)
712 
713  def set_ff_input_scheme(self, schemes: Dict[AnyStr, AnyStr]):
714  self.wrapped.setFFInputScheme(schemes)
715 
716  def get_ff_scheme_names(self) -> List[str]:
717  res = self.wrapped.getFFSchemeNames()
718  return [str(elem) for elem in res]
719 
720  def include_decay(self, name_or_names: Union[List[AnyStr], AnyStr]) -> None:
721  cdef string s
722  cdef vector[string] v
723  if _is_list_of_string(name_or_names):
724  v = name_or_names
725  self.wrapped.includeDecay(v)
726  elif _is_string(name_or_names):
727  s = name_or_names
728  self.wrapped.includeDecay(s)
729  else:
730  print("Invalid Type")
731 
732  def forbid_decay(self, name_or_names: Union[List[AnyStr], AnyStr]) -> None:
733  cdef string s
734  cdef vector[string] v
735  if _is_list_of_string(name_or_names):
736  v = name_or_names
737  self.wrapped.forbidDecay(v)
738  elif _is_string(name_or_names):
739  s = name_or_names
740  self.wrapped.forbidDecay(s)
741  else:
742  print("Invalid Type")
743 
744  def add_pure_ps_vertices(self, vertices: Set[AnyStr], what: WTerm = WTerm.NUMERATOR):
745  self.wrapped.addPurePSVertices(vertices, _to_cpp_wterm(what))
746 
747  def clear_pure_ps_vertices(self, what: WTerm):
748  self.wrapped.clearPurePSVertices(_to_cpp_wterm(what))
749 
750  def set_units(self, name: AnyStr = "GeV"):
751  self.wrapped.setUnits(name)
752 
753  def set_wilson_coefficients(self, process: AnyStr, values_or_settings: Union[List[complex], Dict[AnyStr, complex]], what = WTerm.NUMERATOR):
754  cdef string s1 = process
755  cdef vector[double complex] v
756  cdef cmap[string, double complex] d
757  if _is_vec_complex(values_or_settings):
758  v = values_or_settings
759  self.wrapped.setWilsonCoefficients(s1, v, _to_cpp_wterm(what))
760  elif _is_dict_complex(values_or_settings):
761  d = values_or_settings
762  self.wrapped.setWilsonCoefficients(s1, d, _to_cpp_wterm(what))
763  else:
764  print("Invalid Type")
765 
766  def set_wilson_coefficients_local(self, process: AnyStr, values_or_settings: Union[List[complex], Dict[AnyStr, complex]]):
767  cdef string s1 = process
768  cdef vector[double complex] v
769  cdef cmap[string, double complex] d
770  if _is_vec_complex(values_or_settings):
771  v = values_or_settings
772  self.wrapped.setWilsonCoefficientsLocal(s1, v)
773  elif _is_dict_complex(values_or_settings):
774  d = values_or_settings
775  self.wrapped.setWilsonCoefficientsLocal(s1, d)
776  else:
777  print("Invalid Type")
778 
779  def reset_wilson_coefficients(self, process: AnyStr, what: WTerm = WTerm.NUMERATOR):
780  self.wrapped.resetWilsonCoefficients(process, _to_cpp_wterm(what))
781 
782  def set_ff_eigenvectors(self, process: AnyStr, group: AnyStr, values_or_settings: Union[List[float], Dict[AnyStr, float]]):
783  cdef string s1 = process
784  cdef string s2 = group
785  cdef vector[double] v
786  cdef cmap[string, double] d
787  if _is_vec_float(values_or_settings):
788  v = values_or_settings
789  self.wrapped.setFFEigenvectors(s1, s2, v)
790  elif _is_dict_float(values_or_settings):
791  d = values_or_settings
792  self.wrapped.setFFEigenvectors(s1, s2, d)
793  else:
794  print("Invalid Type")
795 
796  def set_ff_eigenvectors_local(self, process: AnyStr, group: AnyStr, values_or_settings: Union[List[float], Dict[AnyStr, float]]):
797  cdef string s1 = process
798  cdef string s2 = group
799  cdef vector[double] v
800  cdef cmap[string, double] d
801  if _is_vec_float(values_or_settings):
802  v = values_or_settings
803  self.wrapped.setFFEigenvectorsLocal(s1, s2, v)
804  elif _is_dict_float(values_or_settings):
805  d = values_or_settings
806  self.wrapped.setFFEigenvectorsLocal(s1, s2, d)
807  else:
808  print("Invalid Type")
809 
810  def reset_ff_eigenvectors(self, process: AnyStr, group: AnyStr):
811  self.wrapped.resetFFEigenvectors(process, group)
812 
813  def get_weight(self, scheme: AnyStr, processes: Union[List[int], List[List[AnyStr]]] = []) -> float:
814  cdef string s1 = scheme
815  cdef vector[size_t] v1
816  cdef vector[vector[string]] v2
817  if _is_vec_int(processes):
818  v1 = processes
819  return self.wrapped.getWeight(s1, v1)
820  elif _is_list_of_list_of_string(processes):
821  v2 = processes
822  return self.wrapped.getWeight(s1, v2)
823  else:
824  print("Invalid Type")
825  return 0.
826 
827  def get_weights(self, scheme: AnyStr) -> Dict[int, float]:
828  return self.wrapped.getWeights(scheme)
829 
830  def get_rate(self, id_or_vertex: Union[int, AnyStr], scheme: AnyStr) -> float:
831  cdef string s2 = scheme
832  cdef string s1
833  cdef Py_ssize_t i1
834  if _is_string(id_or_vertex):
835  s1 = id_or_vertex
836  return self.wrapped.getRate(s1, s2)
837  elif type(id_or_vertex) is int:
838  i1 = int(id_or_vertex)
839  return self.wrapped.getRate(i1, s2)
840  else:
841  print("Invalid Type")
842  return 0.
843 
844  def get_rate(self, parent: int, daughters: List[int], scheme: AnyStr) -> float:
845  return self.wrapped.getRate(parent, daughters, scheme)
846 
847  def get_denominator_rate(self, id_or_vertex: Union[int, AnyStr]) -> float:
848  cdef string s1
849  cdef Py_ssize_t i1
850  if _is_string(id_or_vertex):
851  s1 = id_or_vertex
852  return self.wrapped.getDenominatorRate(s1)
853  elif type(id_or_vertex) is int:
854  i1 = int(id_or_vertex)
855  return self.wrapped.getDenominatorRate(i1)
856  else:
857  print("Invalid Type")
858  return 0.
859 
860  def get_denominator_rate(self, parent: int, daughters: List[int]) -> float:
861  return self.wrapped.getDenominatorRate(parent, daughters)
862 
863  def get_histogram(self, name: AnyStr, scheme: AnyStr) -> List[BinContents]:
864  result = self.wrapped.getHistogram(name, scheme)
865  return [BinContents.from_cpp(elem) for elem in result]
866 
867  def get_histograms(self, name: AnyStr, scheme: AnyStr):
868  cdef cpp_UMap[cset[cset[size_t]], vector[cpp_BinContents]] res
869  cdef cpp_UMap[cset[cset[size_t]], vector[cpp_BinContents]].iterator it
870  res = self.wrapped.getHistograms(name, scheme)
871  results = dict()
872  it = res.begin()
873  while (it != res.end()):
874  tmp_v = [BinContents.from_cpp(elem) for elem in deref(it).second]
875  tmp_k = _to_set_of_sets(deref(it).first)
876  results.update({tmp_k, tmp_v})
877  return results
878 
879  if HAVE_NUMPY:
880 
881  def get_numpy_histogram(self, name: AnyStr, scheme: AnyStr) -> List[BinContents]:
882  shape = self.wrapped.getHistogramShape(name)
883  res = self.wrapped.getHistogram(name, scheme)
884  results = np.array([BinContents.from_cpp(o) for o in res], dtype=BinContents)
885  results.reshape(list(shape))
886  return results
887 
888  def get_numpy_histograms(self, name: AnyStr, scheme: AnyStr):
889  cdef cpp_UMap[cset[cset[size_t]], vector[cpp_BinContents]] res
890  cdef cpp_UMap[cset[cset[size_t]], vector[cpp_BinContents]].iterator it
891  shape = self.wrapped.getHistogramShape(name)
892  res = self.wrapped.getHistograms(name, scheme)
893  results = dict()
894  it = res.begin()
895  while (it != res.end()):
896  tmp_v = np.array([BinContents.from_cpp(o) for o in deref(it).second], dtype=BinContents)
897  tmp_k = _to_set_of_sets(deref(it).first)
898  results.update({tmp_k, tmp_v})
899  return results
900 
901  def get_histogram_event_ids(self, name: AnyStr, scheme: AnyStr) -> EventUIDGroup:
902  return self.wrapped.getHistogramEventIds(name, scheme)
903 
904  def get_histogram_shape(self, name: AnyStr) -> List[int]:
905  return self.wrapped.getHistogramShape(name)
906 
907  def get_histogram_bin_edges(self, name: AnyStr) -> List[List[float]]:
908  return self.wrapped.getHistogramBinEdges(name)
909 
910  def histogram_has_under_over_flows(self, name: AnyStr) -> bool:
911  return self.wrapped.histogramHasUnderOverFlows(name)
912 
913 def version() -> str:
914  return str(cpp_version())
915 
916 class LogLevel(Enum):
917  TRACE = 0
918  DEBUG = 10
919  INFO = 20
920  WARN = 30
921  WARNING = 30
922  ERROR = 40
923  CRITICAL = 50
924  ALWAYS = 50
925 
926 def set_log_level(name: AnyStr, level: LogLevel):
927  cpp_Log.setLevel(name, int(level))
928 
929 def set_log_levels(level_dict: Dict[AnyStr, LogLevel]):
930  cpp_Log.setLevels(level_dict)
931 
932 def set_log_show_timestamp(value: bool):
933  cpp_Log.setShowTimestamp(value)
934 
935 def set_log_show_level(value: bool):
936  cpp_Log.setShowLevel(value)
937 
938 def set_log_show_logger_name(value: bool):
939  cpp_Log.setShowLoggerName(value)
940 
941 def set_log_use_colors(value: bool):
942  cpp_Log.setUseColors(value)
943 
944 def set_log_warning_max_count(name: AnyStr, max_count: int):
945  cpp_Log.setWarningMaxCount(name, max_count)
946 
947 def reset_log_warning_counters():
948  cpp_Log.resetWarningCounters()
std::string version()
Definition: Tools/Utils.hh:34
from typing import Dict
Definition: hammerlib.pyx:13
std::unordered_map< K, V, boost::hash< K >> UMap
Definition: Tools/Utils.hh:104
TensorData read(const Serial::FBTensor *msgreader)
Definition: Operations.cc:76
from typing import FrozenSet
Definition: hammerlib.pyx:13
from typing import Set
Definition: hammerlib.pyx:13
RecordType
Definition: IOTypes.hh:30
auto begin(reversion_wrapper< T > w)
Definition: Tools/Utils.hh:79
from typing import Any from numbers import Number EventUIDGroup
Definition: hammerlib.pyx:16
from typing import Union
Definition: hammerlib.pyx:13
from typing import AnyStr
Definition: hammerlib.pyx:13
from typing import Any from numbers import Number unpack
Definition: hammerlib.pyx:16
from libcpp map cimport map from libcpp set cimport set as cset from libcpp string cimport string from libcpp pair cimport pair from libcpp vector cimport vector from libcpp unordered_map cimport unordered_map from libcpp cimport bool from libc stdint cimport uint8_t
Definition: cppdefs.pxd:17
from typing import Optional
Definition: hammerlib.pyx:13
from typing import List
Definition: hammerlib.pyx:13
auto end(reversion_wrapper< T > w)
Definition: Tools/Utils.hh:84
from typing import Tuple
Definition: hammerlib.pyx:13