All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Namespaces | Classes | Typedefs | Functions | Variables
util Namespace Reference

Namespace for general, non-LArSoft-specific utilities. More...

Namespaces

 details
 
 fhicl
 
 flags
 Classes and functions to manage bit masks and flags.
 
 manip
 
 pre_std
 
 quantities
 Types of variables with a unit.
 
 ROOT
 

Classes

class  Binner
 Helper class binning values in a range. More...
 
class  FastAndPoorGauss
 Translates a number u uniformly distributed between 0 and 1 into a Gaussian distributed one z. More...
 
class  GaussianTransformer
 Transforms a standard normal number into one on a different normal distribution. More...
 
class  UniformSequence
 Samples the interval [ 0, 1 ] in sequence, cyclically. More...
 
class  NonRandomCounter
 Fast random engine which returns sequential numbers. More...
 
class  RandFastGauss
 Normal distribution focussing on speed. More...
 
class  SampledFunction
 Precomputed discrete sampling of a given function. More...
 
struct  identity
 Substitute for C++20 std::identity. More...
 
class  RegexDataProductSelector
 Matches products by regex on process, module label and instance name. More...
 
struct  ArtHandleTrackerInterface
 Interface to facilitate the use of util::ArtHandleTracker specializations. More...
 
class  ArtHandleTrackerManager
 Manages handle trackers for an easy call of removeCachedProduct(). More...
 
class  LocalArtHandleTrackerManager
 Variant of util::ArtHandleTrackerManager in local scope. More...
 
struct  addIndent
 Stream modifier that makes it "indented". More...
 
struct  PathPointInfo_t
 Data returned by findMiddlePointInPath(). More...
 
class  NormalDistribution
 
struct  collection_value_type
 Trait of value contained in the template collection Coll. More...
 
struct  collection_value_access_type
 Trait of type obtained by access to element of collection Coll. More...
 
struct  collection_value_constant_access_type
 Trait of type obtained by constant access to element of collection Coll. More...
 
struct  collection_reference_type
 Trait of a type that can be used to reference the collection Coll. More...
 
struct  collection_from_reference_type
 Trait with the type of collection referenced by collRef. More...
 
class  count_iterator
 An iterator dereferencing to a counter value. More...
 
struct  self_type
 Trait returning the very same type as in the template argument. More...
 
struct  always_false_type
 A std::false_type with a template argument. More...
 
struct  always_true_type
 A std::true_type with a template argument. More...
 
struct  find_next_type
 Trait: index of the first occurrence of T among the specified Types, starting from the one with index StartFrom. More...
 
struct  is_any_of
 Trait: whether T is among the specified Types. More...
 
struct  is_instance_of
 Trait describing whether T is a template instance of Template. More...
 
struct  is_STLarray
 Identifies whether the specified type is a STL array. More...
 
struct  is_character_type
 Trait: whether type T is a character type. More...
 
struct  is_string_type
 Trait: whether type T is a character string type. More...
 
struct  is_basic_string_type
 Trait: whether type T is a STL string type. More...
 
struct  is_basic_string_view_type
 Trait: whether type T is a std::string_view type. More...
 
struct  with_const_as
 Trait with type Base, plus the constantness as in Key. More...
 
struct  strip_referenceness_type
 Trait with type T stripped of all known reference types. More...
 
struct  reference_addresser
 Functor applying the proper referenced_address() function. More...
 
struct  lvalue_reference_into_wrapper_type
 Trait with type T into std::reference_wrapper if reference. More...
 
struct  is_STLarray< std::array< T, N > >
 
struct  AddressTaker
 Functor returning the address in memory of the operand. More...
 
struct  Dereferencer
 Functor dereferencing the operand. More...
 
struct  KeepByPositionFilterTag
 Tag for filters. More...
 
class  PositionInVolumeFilter
 Use to keep particles with at least part of trajectory in a volume. More...
 
struct  span_base
 Non-templated base class for span. More...
 
struct  span
 Simple class with a begin and an end. More...
 
class  UBDaqID
 
class  DatabaseUtil
 
class  GeometryUtilities
 
class  GridContainerIndicesBase1D
 Index manager for a container of data arranged on a >=1-dim grid. More...
 
class  GridContainerIndicesBase2D
 Index manager for a container of data arranged on a >=2-dim grid. More...
 
class  GridContainerIndicesBase3D
 Index manager for a container of data arranged on a >=3-dim grid. More...
 
class  GridContainerBase1D
 Base class for a container of data arranged on a 1D-grid. More...
 
class  GridContainerBase2D
 Base class for a container of data arranged on a 2D-grid. More...
 
class  GridContainerBase3D
 Base class for a container of data arranged on a 3D-grid. More...
 
class  LArFFT
 
class  LArFFTW
 
class  LArFFTWPlan
 
class  PxHitConverter
 
class  PxPoint
 
class  PxHit
 
class  PxLine
 
class  UniqueRangeSet
 std::set of util::Range, which does not allow any overlap in contained element. std::set<Range> w/ modified insert/emplace function. Original std::set does not allow
modification of element. I assume what we're interested in is "find if the range already \n exists, and merge if it exists". The insert function does that by recursively looking up
overlapping elements w.r.t. input argument of insert function.
More...
 
class  Range
 represents a "Range" w/ notion of ordering. A range is defined by a pair of "start" and "end" values. This is stored in std::pair
attribute util::Range::_window. This attribute is protected so that the start/end cannot
be changed w/o a check that start is always less than end. Note the specialization
requires a template class T to have less operator implemented.
More...
 
struct  RangeForWrapperTag
 Tag marking the use of RangeForWrapperBox. More...
 
class  SignalShaper
 
class  SignalShaping
 
struct  TensorIndicesBasicTypes
 Types for TensorIndices class. More...
 
class  TensorIndices
 Converts a tensor element specification into a linear index. More...
 
class  TensorIndices< 1U >
 
struct  count_type_in_tuple
 Holds whether the Target type is element of the specified std::tuple. More...
 
struct  extract_to_tuple_type
 Returns type TargetClass<U...> from a SrcTuple<T...>. More...
 
struct  index_of_extracted_type
 Returns the index of the element in Tuple with the specified type. More...
 
struct  has_extracted_type
 Trait holding whether an element in Tuple type contains Target. More...
 
struct  has_duplicate_extracted_types
 Traits holding whether elements of Tuple have duplicate types. More...
 
struct  count_extracted_types
 Counts the elements of a tuple-like type containing a Target type. More...
 
struct  TaggedType
 A type with a specified tag. More...
 
struct  add_tag
 
struct  remove_tag
 Trait holding the type contained in a TaggedType (or the type itself). More...
 
struct  remove_tag< TaggedType< T, Tag > >
 
struct  TagN
 Tag class parametrized by a sequence of numbers. More...
 
struct  TagExtractor
 Extracts the tag from a type. More...
 
struct  count_type_in_tuple< Target, std::tuple< T...> >
 
class  UtilException
 
class  LArPropTest
 
struct  MappedContainerBase
 Non-template base class for MappedContainer. More...
 
class  MappedContainer
 A meta-container providing transparent mapping on top of another. More...
 
class  MultipleChoiceSelectionBase
 Base class of util::MultipleChoiceSelection with basics independent of the option type. More...
 
class  MultipleChoiceSelection
 Helper to select one among multiple choices via strings. More...
 
class  LazyVector
 A contiguous data container expanded on write. More...
 
class  SumSecondFunction
 
class  VectorMap
 
class  EventChangeTracker_t
 Detects the presence of a new event. More...
 
class  DataProductChangeTracker_t
 Detects the presence of a new event or data product. More...
 
class  PlaneDataChangeTracker_t
 Detects the presence of a new event, data product or wire plane. More...
 
class  GaussianEliminationAlg
 
class  FileSpec
 
class  FileCatalogMetadataSBN
 
class  MetadataSBN
 
class  SignalShapingServiceSBND
 

Typedefs

template<typename Handle >
using ArtHandleData_t = typename Handle::element_type::value_type
 Type of data in a art handle to vector data product. More...
 
template<typename T >
using DataProductPointerMap_t = details::DataProductPointerMap_t< T >
 Type of map for data product pointers to art pointers. More...
 
template<typename Coll >
using collection_value_t = typename collection_value_type< Coll >::type
 Type contained in the collection Coll. More...
 
template<typename Coll >
using collection_value_access_t = typename collection_value_access_type< Coll >::type
 Type obtained by constant access to element of collection Coll. More...
 
template<typename Coll >
using collection_value_constant_access_t = typename collection_value_constant_access_type< Coll >::type
 Type obtained by constant access to element of collection Coll. More...
 
template<typename Coll >
using collection_reference_t = typename collection_reference_type< Coll >::type
 The type contained in util::collection_reference_type trait. More...
 
template<typename Cont >
using collection_from_reference_t = typename collection_from_reference_type< Cont >::type
 Type contained in util::collection_from_reference_type trait. More...
 
template<typename T >
using self_t = typename self_type< T >::type
 The very same type as in the template argument. More...
 
using type_traits = std::bool_constant< Value >
 
template<typename A , typename B >
using is_not_same = std::negation< std::is_same< A, B >>
 The negation of std::is_same. More...
 
template<typename T , typename... Types>
using find_type = find_next_type< T, 0U, Types...>
 Trait: index of the first occurrence of T among the specified Types. More...
 
template<typename T >
using is_reference_wrapper = is_instance_of< std::reference_wrapper, T >
 Identifies whether the specified type is a std::reference_wrapper. More...
 
template<typename T >
using is_unique_ptr = is_instance_of< std::unique_ptr, T >
 Identifies whether the specified type is a std::unique_ptr. More...
 
template<typename Base , typename Key >
using with_const_as_t = typename with_const_as< Base, Key >::type
 The type Base, plus the constantness as in Key. More...
 
template<typename T >
using strip_referenceness_t = typename strip_referenceness_type< T >::type
 The type T stripped of all known reference types. More...
 
template<typename T >
using lvalue_reference_into_wrapper_t = typename lvalue_reference_into_wrapper_type< T >::type
 The type T stripped of all known reference types. More...
 
typedef int UBLArSoftCh_t
 
typedef std::map< UBDaqID,
UBLArSoftCh_t
UBChannelMap_t
 
typedef std::map
< UBLArSoftCh_t, UBDaqID
UBChannelReverseMap_t
 
using GridContainer2DIndices = GridContainerIndicesBase2D<>
 Index manager for a container of data arranged on a 2D grid. More...
 
using GridContainer3DIndices = GridContainerIndicesBase3D<>
 Index manager for a container of data arranged on a 3D grid. More...
 
template<typename DATUM >
using GridContainer2D = GridContainerBase2D< DATUM, GridContainer2DIndices >
 Container allowing 2D indexing. More...
 
template<typename DATUM >
using GridContainer3D = GridContainerBase3D< DATUM, GridContainer3DIndices >
 Container allowing 3D indexing. More...
 
using MatrixIndices = TensorIndices< 2U >
 Type for indexing a 2D-tensor (matrix) More...
 
template<typename SrcTuple , template< typename T, typename...> class Extractor, template< typename...> class TargetClass = std::tuple>
using extract_to_tuple_type_t = typename extract_to_tuple_type< SrcTuple, Extractor, TargetClass >::type
 Direct access to the type in extract_to_tuple_type. More...
 
template<typename Tuple , template< typename...> class TargetClass = std::tuple>
using to_tuple = extract_to_tuple_type< Tuple, self_type, TargetClass >
 
template<typename Tuple , template< typename...> class TargetClass = std::tuple>
using to_tuple_t = typename to_tuple< Tuple, TargetClass >::type
 Direct access to the type in to_tuple. More...
 
template<typename Target , typename Tuple >
using index_of_type = index_of_extracted_type< self_type, Target, Tuple >
 
template<template< typename T, typename...> class Extractor, typename Target , typename Tuple >
using type_with_extracted_type = std::tuple_element< index_of_extracted_type_v< Extractor, Target, Tuple >, Tuple >
 Returns the element type in Tuple with the specified type. More...
 
template<template< typename T, typename...> class Extractor, typename Target , typename Tuple >
using type_with_extracted_type_t = typename type_with_extracted_type< Extractor, Target, Tuple >::type
 Direct access to the value in type_with_extracted_type. More...
 
template<typename Target , typename Tuple >
using has_type = has_extracted_type< self_type, Target, Tuple >
 
template<typename Tuple >
using has_duplicate_types = has_duplicate_extracted_types< self_type, Tuple >
 
template<typename Target , typename Tuple >
using count_types = count_extracted_types< self_type, Target, Tuple >
 
template<typename T , typename Tag >
using add_tag_t = typename add_tag< T, Tag >::type
 
template<typename Tagged >
using remove_tag_t = typename remove_tag< Tagged >::type
 Direct access to the type contained in remove_tag. More...
 
template<typename Tagged >
using tag_of = TagExtractor< Tagged >
 Trait holding the tag of Tagged as type. More...
 
template<typename Tagged >
using tag_of_t = typename tag_of< Tagged >::type
 Direct access to the type in tag_of. More...
 
template<typename SrcTuple >
using extract_tags = extract_to_tuple_type< SrcTuple, TagExtractor >
 Returns a tuple with all the tags from SrcTuple. More...
 
template<typename SrcTuple >
using extract_tags_t = typename extract_tags< SrcTuple >::type
 Direct access to the type in extract_tags. More...
 
template<typename Tag , typename Tuple >
using index_of_tag = index_of_extracted_type< TagExtractor, Tag, Tuple >
 Trait holding the index of the element of Tuple with tag Tag. More...
 
template<typename Tag , typename Tuple >
using type_with_tag = type_with_extracted_type< TagExtractor, Tag, Tuple >
 Trait holding the type of the element of Tuple with tag Tag. More...
 
template<typename Tag , typename Tuple >
using type_with_tag_t = typename type_with_tag< Tag, Tuple >::type
 Direct access to the value in type_with_tag. More...
 
template<typename Tag , typename Tuple >
using has_tag = has_extracted_type< TagExtractor, Tag, Tuple >
 Trait informing if there are elements in Tuple with tag Tag. More...
 
template<typename Tag , typename Tuple >
using count_tags = count_extracted_types< TagExtractor, Tag, Tuple >
 Trait counting the elements in Tuple with tag Tag. More...
 
template<typename Tuple >
using has_duplicate_tags = has_duplicate_extracted_types< TagExtractor, Tuple >
 Trait reporting if multiple elements in Tuple have the same tag. More...
 

Functions

template<typename T >
std::ostream & operator<< (std::ostream &, Binner< T > const &)
 
template<typename Event >
art::InputTag inputTagOf (Event const &event, art::ProductID const &productID)
 Reads and returns the input tag of the producer of productID. More...
 
template<typename Event , typename Handle >
std::enable_if_t
< std::is_void_v< std::void_t
< typename Handle::HandleTag >
>, art::InputTag > 
inputTagOf (Event const &event, Handle const &handle)
 Reads and returns the input tag of the product with the specified handle. More...
 
template<typename Event , typename T >
art::InputTag inputTagOf (Event const &event, art::Ptr< T > const &ptr)
 Reads and returns the input tag of the product ptr points to. More...
 
template<typename Coll , typename KeyOp , typename CmpOp , typename RefOp , typename KeySortOp >
auto clusterBy (Coll const &objs, KeyOp keyFunc, CmpOp sameGroup, RefOp objRef, KeySortOp keySort)
 Performs a simple clustering. More...
 
template<typename Coll , typename KeyOp , typename CmpOp , typename KeySortOp >
auto clusterBy (Coll const &objs, KeyOp keyFunc, CmpOp sameGroup, KeySortOp keySort)
 A version of clusterBy() storing a copy of each object as "reference". More...
 
template<typename BIter , typename EIter , typename Key , typename Sorter = std::less<void>>
auto sortBy (BIter begin, EIter end, Key key, Sorter sorter={})
 Returns a vectors to pointers to coll elements, sorted by key. More...
 
template<typename Coll , typename Key , typename Sorter = std::less<void>>
auto sortCollBy (Coll &coll, Key key, Sorter sorter={})
 Returns a vectors to pointers to coll elements, sorted by key. More...
 
template<typename Handle >
DataProductPointerMap_t
< ArtHandleData_t< Handle > > 
mapDataProductPointers (art::Event const &event, Handle const &handle)
 Creates a map from address of data product element to art pointer to it. More...
 
std::map
< fhicl::ParameterSetID,
fhicl::ParameterSet > 
readConfigurationFromArtFile (TFile &file)
 Reads and returns the art configuration stored in sourceDir. More...
 
template<typename Principal >
std::map< std::string,
fhicl::ParameterSet > 
readConfigurationFromArtPrincipal (Principal const &principal)
 Reads and returns the complete art configuration in the principal. More...
 
template<typename Stream >
auto operator<< (Stream &&out, addIndent &&adder)
 Helper function for addIndent (. More...
 
template<typename FIter , typename LIter >
PathPointInfo_t< FIter > findMiddlePointInPath (FIter itFirst, LIter itLast, double relTarget=0.5)
 Returns information to identify the middle of the specified path. More...
 
template<typename FIter , typename LIter >
auto pathMiddlePoint (FIter itFirst, LIter itLast, double relTarget=0.5)
 Returns the geometric point in the middle of the specified path. More...
 
template<typename BIter , typename EIter >
double pathLength (BIter begin, EIter end)
 Returns the total length of the specified path. More...
 
template<typename BIter , typename EIter >
std::vector< double > partialPathLengths (BIter begin, EIter end)
 Returns a sequences of partial lengths for the specified path. More...
 
template<typename Iter , typename SideFunc >
std::pair< Iter, Iter > findCrossingSegment (Iter begin, Iter end, SideFunc sideOf)
 Returns a path segment with ends on different sides than path ends. More...
 
template<typename Coll >
auto make_collection_reference (Coll &&coll)
 Returns an object referencing to the data contained in coll. More...
 
template<typename CollRef >
decltype(auto) collection_from_reference (CollRef &collRef)
 Returns the object referenced by collRef as a C++ reference. More...
 
template<typename Coll , typename Extractor >
decltype(auto) makeValueIndex (Coll const &coll, Extractor getter)
 Returns a map of value to index. More...
 
template<typename Coll >
auto makeValueIndex (Coll const &coll)
 
template<typename Ref >
auto referenced_address (Ref &&ref)
 Returns the address of the referenced object. More...
 
template<typename T >
auto lvalue_reference_into_wrapper (T &&obj)
 Converts a l-value reference object into a std::reference_wrapper. More...
 
decltype(auto) takeAddress ()
 Returns a functor that returns the address of its argument. More...
 
decltype(auto) dereference ()
 Returns a functor that returns *ptr of its argument ptr. More...
 
template<typename Coll >
auto makePointerVector (Coll &coll)
 Creates a STL vector with pointers to data from another collection. More...
 
template<typename Coll , typename PtrColl >
void MoveFromPointers (Coll &dest, PtrColl &src)
 Moves the content from a collection of pointers to one of data. More...
 
template<typename Coll , typename Sorter >
void SortByPointers (Coll &coll, Sorter sorter)
 Applies sorting indirectly, minimizing data copy. More...
 
template<typename Coll , typename Sorter >
void SortUniquePointers (Coll &coll, Sorter &&sorter)
 Sorts a vector of unique pointers using a C pointer sorter. More...
 
template<typename T = double>
constexpr T pi ()
 Returns the constant pi (up to 35 decimal digits of precision) More...
 
template<typename T >
constexpr T DegreesToRadians (T angle)
 Converts the argument angle from degrees into radians. More...
 
template<typename T >
constexpr T RadiansToDegrees (T angle)
 Converts the argument angle from radians into degrees ( $ \pi \rightarrow 180 $) More...
 
template<typename Stream , typename Left , typename Right , typename Data >
void DumpAssociationsIntro (Stream &&out, art::Assns< Left, Right, Data > const &assns)
 Dumps a short introduction about specified association. More...
 
template<class T , class U >
bool CreateAssn (art::Event &evt, std::vector< T > const &a, art::Ptr< U > const &b, art::Assns< U, T > &assn, std::string a_instance, size_t index=UINT_MAX)
 Creates a single one-to-one association. More...
 
template<class T , class U >
bool CreateAssn (art::Event &evt, std::vector< T > const &a, art::Ptr< U > const &b, art::Assns< U, T > &assn, size_t index=UINT_MAX)
 Creates a single one-to-one association. More...
 
template<class T , class U >
bool CreateAssn (art::Event &evt, art::Ptr< T > const &a, art::Ptr< U > const &b, art::Assns< U, T > &assn)
 Creates a single one-to-one association. More...
 
template<class T , class U >
bool CreateAssn (art::Event &evt, std::vector< T > const &a, art::PtrVector< U > const &b, art::Assns< T, U > &assn, size_t index=UINT_MAX)
 Creates a single one-to-many association. More...
 
template<class T , class U >
bool CreateAssn (art::Event &evt, art::Ptr< T > const &a, std::vector< art::Ptr< U >> const &b, art::Assns< T, U > &assn)
 Creates a single one-to-many association. More...
 
template<class T , class U >
bool CreateAssn (art::Event &evt, std::vector< T > const &a, std::vector< art::Ptr< U >> const &b, art::Assns< T, U > &assn, size_t index=UINT_MAX)
 Creates a single one-to-many association. More...
 
template<class T , class U >
bool CreateAssn (art::Event &evt, std::vector< T > const &a, std::vector< U > const &b, art::Assns< T, U > &assn, size_t startU, size_t endU, size_t index=UINT_MAX)
 Creates a single one-to-many association. More...
 
template<class T , class U >
bool CreateAssn (art::Event &evt, std::vector< T > const &a, std::vector< U > const &b, art::Assns< T, U > &assn, std::vector< size_t > const &indices, size_t index=UINT_MAX)
 Creates a single one-to-many association. More...
 
template<typename T , typename U , typename Iter >
bool CreateAssn (art::Event &evt, art::Assns< T, U > &assn, size_t first_index, Iter from_second_index, Iter to_second_index)
 Creates a single one-to-many association. More...
 
template<class T , class U >
std::vector< const U * > FindUNotAssociatedToT (art::Handle< U > b, art::Event const &evt, std::string const &label)
 
template<class T , class U >
std::vector< art::Ptr< U > > FindUNotAssociatedToTP (art::Handle< U > b, art::Event const &evt, std::string const &label)
 
template<class T , class U >
std::vector< size_t > GetAssociatedVectorOneI (art::Handle< art::Assns< T, U > > h, art::Handle< std::vector< T > > index_p)
 
template<class T , class U >
std::vector< const U * > GetAssociatedVectorOneP (art::Handle< art::Assns< T, U > > h, art::Handle< std::vector< T > > index_p)
 
template<class T , class U >
std::vector< std::vector
< size_t > > 
GetAssociatedVectorManyI (art::Handle< art::Assns< T, U > > h, art::Handle< std::vector< T > > index_p)
 
template<class T , class U >
std::vector< std::vector
< const U * > > 
GetAssociatedVectorManyP (art::Handle< art::Assns< T, U > > h, art::Handle< std::vector< T > > index_p)
 
template<typename Producer , typename... Args>
std::enable_if_t
< std::is_base_of_v
< art::EDProducer, Producer >
, bool > 
CreateAssn (Producer const &, Args &&...args)
 
template<typename Producer , typename... Args>
std::enable_if_t
< std::is_base_of_v
< art::EDProducer, Producer >
, bool > 
CreateAssnD (Producer const &, Args &&...args)
 
template<typename Range , typename Pred >
auto filterRangeFor (Range &&range, Pred &&pred) -> decltype(auto)
 Provides iteration only through elements passing a condition. More...
 
template<class A , class F >
void for_each_associated_group (A const &assns, F &func)
 Helper functions to access associations in order. More...
 
template<class A >
auto associated_groups (A const &assns)
 Helper functions to access associations in order. More...
 
template<class A >
auto associated_groups_with_left (A const &assns)
 Helper functions to access associations in order, also with key. More...
 
template<typename Groups >
auto groupByIndex (Groups &&groups, std::size_t index) -> decltype(auto)
 Returns the group within groups with the specified index. More...
 
template<typename Coll , typename KeyOf >
std::vector< size_t > MakeIndex (Coll const &data, KeyOf key_of=KeyOf())
 Creates a map of indices from an existing collection. More...
 
template<typename Coll , typename KeyOf >
auto MakeMap (Coll const &data, KeyOf key_of=KeyOf()) -> std::vector< decltype(key_of(*(data.begin()))) const * >
 Creates a map of objects from an existing collection. More...
 
template<typename Range >
auto wrapRangeFor (Range &&range) -> decltype(auto)
 Wraps an object for use in a range-for loop. More...
 
template<typename Range >
auto operator| (Range &&range, RangeForWrapperTag) -> decltype(auto)
 Transforms a range so that it can be used in a range-for loop. More...
 
template<unsigned int RANK1, unsigned int RANK2, typename = std::enable_if_t<(RANK1 != RANK2), bool>>
bool operator== (TensorIndices< RANK1 > const &a, TensorIndices< RANK2 > const &b)
 Comparison operator with tensors of different rank. More...
 
template<unsigned int RANK1, unsigned int RANK2, typename = std::enable_if_t<(RANK1 != RANK2), bool>>
bool operator!= (TensorIndices< RANK1 > const &a, TensorIndices< RANK2 > const &b)
 Comparison operator with tensors of different rank. More...
 
template<typename... DIMS>
auto makeTensorIndices (DIMS...dims)
 Instantiates a TensorIndices class with the specified dimensions. More...
 
template<template< typename T, typename...> class Extractor, typename Target , typename Tuple >
auto getByExtractedType (Tuple const &data) -> decltype(auto)
 Returns the value of the element containing the specified type. More...
 
template<typename Tag , typename T >
auto makeTagged (T &obj) -> decltype(auto)
 "Converts" obj to an object with tag Tag. More...
 
template<typename Tag , typename T >
auto makeTagged (T const &obj) -> decltype(auto)
 "Converts" obj to an object with tag Tag. More...
 
template<typename Tag , typename T >
auto makeTagged (T const &&obj) -> decltype(auto)
 "Converts" obj to an object with tag Tag. More...
 
template<typename Tag , typename T >
auto makeTagged (T &&obj) -> decltype(auto)
 "Converts" obj to an object with tag Tag. More...
 
template<typename Tagged >
auto removeTag (Tagged &tagged) -> decltype(auto)
 "Converts" a tagged type back to its original type. More...
 
template<typename Tagged >
auto removeTag (Tagged const &tagged) -> decltype(auto)
 "Converts" a tagged type back to its original type. More...
 
template<typename Tagged >
auto removeTag (Tagged const &&tagged) -> decltype(auto)
 "Converts" a tagged type back to its original type. More...
 
template<typename Tagged >
auto removeTag (Tagged &&tagged) -> decltype(auto)
 "Converts" a tagged type back to its original type. More...
 
template<typename Tag , typename Tuple >
auto getByTag (Tuple const &data) -> decltype(auto)
 Returns the object with the specified tag. More...
 
template<typename Cont , typename Mapping >
auto mapContainer (Cont cont, Mapping mapping)
 Returns a container-like object mapping the content of cont. More...
 
template<typename Cont , typename Mapping , typename Container , typename Reference >
MappedContainer< Cont, Mapping >
::template IteratorBase
< Container, Reference > 
operator+ (typename MappedContainer< Cont, Mapping >::template IteratorBase< Container, Reference >::difference_type n, typename MappedContainer< Cont, Mapping >::template IteratorBase< Container, Reference > const &it)
 
template<typename _Key , typename _Tp , typename _Compare >
bool operator== (const VectorMap< _Key, _Tp, _Compare > &__x, const VectorMap< _Key, _Tp, _Compare > &__y)
 
template<typename _Key , typename _Tp , typename _Compare >
bool operator< (const VectorMap< _Key, _Tp, _Compare > &__x, const VectorMap< _Key, _Tp, _Compare > &__y)
 
template<typename _Key , typename _Tp , typename _Compare >
bool operator!= (const VectorMap< _Key, _Tp, _Compare > &__x, const VectorMap< _Key, _Tp, _Compare > &__y)
 Based on operator==. More...
 
template<typename _Key , typename _Tp , typename _Compare >
bool operator> (const VectorMap< _Key, _Tp, _Compare > &__x, const VectorMap< _Key, _Tp, _Compare > &__y)
 Based on operator<. More...
 
template<typename _Key , typename _Tp , typename _Compare >
bool operator<= (const VectorMap< _Key, _Tp, _Compare > &__x, const VectorMap< _Key, _Tp, _Compare > &__y)
 Based on operator<. More...
 
template<typename _Key , typename _Tp , typename _Compare >
bool operator>= (const VectorMap< _Key, _Tp, _Compare > &__x, const VectorMap< _Key, _Tp, _Compare > &__y)
 Based on operator<. More...
 
template<typename _Key , typename _Tp , typename _Compare >
void swap (VectorMap< _Key, _Tp, _Compare > &__x, VectorMap< _Key, _Tp, _Compare > &__y)
 See VectorMap::swap(). More...
 
std::ostream & operator<< (std::ostream &out, EventChangeTracker_t const &trk)
 
std::ostream & operator<< (std::ostream &out, DataProductChangeTracker_t const &trk)
 
std::ostream & operator<< (std::ostream &out, PlaneDataChangeTracker_t const &trk)
 
def root_env
 
def wait
 
def write
 
def with_input_args
 
def filespec
 
def get_tobject
 
def with_text_args
 
def draw_text
 
def with_display_args
 
def with_io_args
 
def with_graphsize_args
 
def with_histosize_args
 
def resize_graph
 
def resize_histo
 
def int_pair
 
def with_histostyle_args
 
def optstat
 
def style
 
def fillcolors
 
def namecolors
 
def comma_separated
 
def draw_potlabel
 
def draw_sbnlabel
 
def draw_iclabel
 
def draw_sbndlabel
 
def legend_position
 
def histo_list
 
def validate_hists
 
double ECCQE (const TVector3 &l_momentum, double l_energy)
 
double ContainedLength (const TVector3 &v0, const TVector3 &v1, const std::vector< geo::BoxBoundedGeo > &boxes)
 
double MCParticleLength (const simb::MCParticle &particle)
 
double MCParticleContainedLength (const simb::MCParticle &particle, const std::vector< geo::BoxBoundedGeo > &active_volumes)
 
template<typename Stream >
auto makeIndented (Stream &&out, std::string indent, std::string firstIndent)
 Creates an indented stream wrapper. More...
 
template<typename Stream >
auto makeIndented (Stream &&out, std::string const &indent)
 
Counted iterations
template<typename T >
auto counter (T begin, T end)
 Returns an object to iterate values from begin to end in a range-for loop. More...
 
template<typename T >
auto counter (T end)
 
template<typename T = std::size_t>
auto infinite_counter (T begin=T{})
 Version of util::counter() starting at begin and never ending. More...
 
Enumerated iterations
template<std::size_t Lead, typename... Iterables>
auto enumerate (Iterables &&...iterables)
 Range-for loop helper tracking the number of iteration. More...
 
template<typename... Iterables>
auto enumerate (Iterables &&...iterables)
 This version of enumerate implicitly uses the first iterable as lead. More...
 
Transformed iterations
template<std::size_t... Indices, typename Coll >
decltype(auto) get_elements (Coll &&coll)
 Range-for loop helper iterating across some of the element of each value in the specified collection. More...
 
template<std::size_t... Indices, typename Coll >
decltype(auto) get_const_elements (Coll &&coll)
 Range-for loop helper iterating across the constant values of the specified collection. More...
 
template<typename Coll >
decltype(auto) values (Coll &&coll)
 Range-for loop helper iterating across the values of the specified collection. More...
 
template<typename Coll >
decltype(auto) const_values (Coll &&coll)
 Range-for loop helper iterating across the constant values of the specified collection. More...
 
template<typename T >
void staticDumpClassName ()
 Helper to determine the type of a variable at compilation time. More...
 
template<typename T >
void staticDumpClassName (T)
 
template<typename A , typename B >
constexpr auto absDiff (A const &a, B const &b)
 Returns the absolute value of the difference between two values. More...
 
Span helper functions
template<typename BIter , typename EIter >
auto make_span (BIter begin, EIter end)
 Creates a span from specified iterators (can use constructor instead). More...
 
template<typename Cont >
auto make_span (Cont &cont)
 Creates a span from a container type. More...
 
template<typename Cont >
auto make_const_span (Cont &cont)
 Creates a span with constant iterator access from a container type. More...
 
Adapted span helper functions
template<typename BIter , typename EIter , typename Adaptor >
auto make_adapted_span (BIter begin, EIter end, Adaptor &&adaptor)
 
template<typename Cont , typename Adaptor >
auto make_adapted_span (Cont &cont, Adaptor &&adaptor)
 Creates a span from specified collection via an adaptor. More...
 
template<typename Cont , typename Adaptor >
auto make_adapted_const_span (Cont &cont, Adaptor &&adaptor)
 Creates constant iteration span from specified collection via an adaptor. More...
 
Transformed span helper functions
template<typename BIter , typename EIter , typename Op >
auto make_transformed_span (BIter begin, EIter end, Op &&op)
 
template<typename Cont , typename Op >
auto make_transformed_span (Cont &cont, Op &&op)
 Creates a span from specified collection via an adaptor. More...
 
template<typename Cont , typename Op >
auto make_transformed_const_span (Cont &cont, Op &&op)
 
C++ standard library customization for user-defined classes.
template<typename T >
decltype(auto) constexpr to_string (T &&obj)
 ADL-aware version of std::to_string. More...
 
template<typename T >
decltype(auto) constexpr begin (T &&obj)
 ADL-aware version of std::begin. More...
 
template<typename T >
decltype(auto) constexpr end (T &&obj)
 ADL-aware version of std::end. More...
 
template<typename T >
decltype(auto) constexpr cbegin (T &&obj)
 ADL-aware version of std::cbegin. More...
 
template<typename T >
decltype(auto) constexpr cend (T &&obj)
 ADL-aware version of std::cend. More...
 
template<typename T >
decltype(auto) constexpr size (T &&obj)
 ADL-aware version of std::size. More...
 
template<typename T >
decltype(auto) constexpr empty (T &&obj)
 ADL-aware version of std::empty. More...
 
template<std::size_t I, typename T >
decltype(auto) get (T &&obj)
 
Parallel iterations
template<std::size_t Lead, typename... Iterables>
auto zip (Iterables &&...iterables)
 Range-for loop helper iterating across many collections at the same time. More...
 
template<typename... Iterables>
auto zip (Iterables &&...iterables)
 Version of zip() with first iterator implicitly leading the iteration. More...
 
template<typename T , typename U , typename D >
bool CreateAssnD (art::Event &evt, art::Assns< T, U, D > &assn, size_t first_index, size_t second_index, typename art::Assns< T, U, D >::data_t &&data)
 Creates a single one-to-one association with associated data. More...
 
template<typename T , typename U , typename D >
bool CreateAssnD (art::Event &evt, art::Assns< T, U, D > &assn, size_t first_index, size_t second_index, typename art::Assns< T, U, D >::data_t const &data)
 
Simple mathematical functions
template<typename T >
constexpr auto abs (T v)
 Returns the absolute value of the argument. More...
 
template<class T >
sqr (T x)
 More efficient square function than pow(x,2) More...
 
template<class T >
cube (T x)
 More efficient cube function than pow(x,3) More...
 
template<class T >
ipow (T x, unsigned int n)
 More efficient exponentiation function than pow(x,n) for small n. More...
 
double pythag (double x, double y)
 2D Euclidean distance More...
 
double pythag (double x, double y, double z)
 3D Euclidean distance More...
 
Create and query associations
template<class T , class U >
static bool CreateAssn (art::EDProducer const &prod, art::Event &evt, std::vector< T > &a, art::Ptr< U > b, art::Assns< T, U > &assn, size_t indx=UINT_MAX, std::string const &instance=std::string())
 Create a 1 to 1 association between a new product and one already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDProducer const &prod, art::Event &evt, std::vector< T > &a, art::Ptr< U > b, art::Assns< T, U > &assn, size_t begin_indx, size_t end_indx, std::string const &instance=std::string())
 Create a 1 to 1 association between each of a series of new products and one already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDProducer const &prod, art::Event &evt, art::Ptr< T > &a, art::Ptr< U > b, art::Assns< T, U > &assn)
 Create a 1 to 1 association between two products already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDProducer const &prod, art::Event &evt, std::vector< T > &a, art::PtrVector< U > b, art::Assns< T, U > &assn, size_t indx=UINT_MAX, std::string const &instance=std::string())
 Create a 1 to many association between a new product and a PtrVector already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDProducer const &prod, art::Event &evt, art::Ptr< T > &a, std::vector< art::Ptr< U > > b, art::Assns< T, U > &assn)
 Create a 1 to many association between products already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDProducer const &prod, art::Event &evt, std::vector< T > &a, std::vector< art::Ptr< U > > b, art::Assns< T, U > &assn, size_t indx=UINT_MAX, std::string const &instance=std::string())
 Create a 1 to many association between a new product and a vector of Ptrs already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDProducer const &prod, art::Event &evt, std::vector< T > &a, std::vector< U > &b, art::Assns< T, U > &assn, size_t startU, size_t endU, size_t indx=UINT_MAX, std::string const &instancea=std::string(), std::string const &instanceb=std::string())
 Create a 1 to many association between new products. More...
 
template<class T , class U >
static bool CreateAssn (art::EDProducer const &prod, art::Event &evt, art::Assns< T, U > &assn, std::vector< T > &a, std::vector< U > &b, size_t indxb=UINT_MAX, size_t indxa=UINT_MAX, std::string const &instancea=std::string(), std::string const &instanceb=std::string())
 Create a 1 to 1 between new products. More...
 
template<class T , class U >
static std::vector< const U * > FindUNotAssociatedToT (art::Handle< U > b, art::Event const &evt, std::string const &label)
 Return all objects of type U that are not associated to objects of type T. More...
 
template<class T , class U >
static std::vector< art::Ptr< U > > FindUNotAssociatedToTP (art::Handle< U > b, art::Event const &evt, std::string const &label)
 Return all objects of type U that are not associated to objects of type T. More...
 
template<class T , class U >
static bool CreateAssn (art::EDFilter const &prod, art::Event &evt, std::vector< T > &a, art::Ptr< U > b, art::Assns< T, U > &assn, size_t indx=UINT_MAX, std::string const &instance=std::string())
 Create a 1 to 1 association between a new product and one already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDFilter const &prod, art::Event &evt, std::vector< T > &a, art::Ptr< U > b, art::Assns< T, U > &assn, size_t begin_indx, size_t end_indx, std::string const &instance=std::string())
 Create a 1 to 1 association between each of a series of new products and one already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDFilter const &prod, art::Event &evt, art::Ptr< T > &a, art::Ptr< U > b, art::Assns< T, U > &assn)
 Create a 1 to 1 association between two products already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDFilter const &prod, art::Event &evt, std::vector< T > &a, art::PtrVector< U > b, art::Assns< T, U > &assn, size_t indx=UINT_MAX, std::string const &instance=std::string())
 Create a 1 to many association between a new product and a PtrVector already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDFilter const &prod, art::Event &evt, art::Ptr< T > &a, std::vector< art::Ptr< U > > b, art::Assns< T, U > &assn)
 Create a 1 to many association between products already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDFilter const &prod, art::Event &evt, std::vector< T > &a, std::vector< art::Ptr< U > > b, art::Assns< T, U > &assn, size_t indx=UINT_MAX, std::string const &instance=std::string())
 Create a 1 to many association between a new product and a vector of Ptrs already in the event. More...
 
template<class T , class U >
static bool CreateAssn (art::EDFilter const &prod, art::Event &evt, std::vector< T > &a, std::vector< U > &b, art::Assns< T, U > &assn, size_t startU, size_t endU, size_t indx=UINT_MAX, std::string const &instancea=std::string(), std::string const &instanceb=std::string())
 Create a 1 to many association between new products. More...
 
template<class T , class U >
static bool CreateAssn (art::EDFilter const &prod, art::Event &evt, art::Assns< T, U > &assn, std::vector< T > &a, std::vector< U > &b, size_t indxb=UINT_MAX, size_t indxa=UINT_MAX, std::string const &instancea=std::string(), std::string const &instanceb=std::string())
 Create a 1 to 1 between new products. More...
 

Variables

template<typename XType , typename Func , typename UntilFunc >
 SampledFunction< XType, XType >
 
template<typename >
constexpr bool always_false_v = false
 A templated constant, always false. More...
 
template<typename >
constexpr bool always_true_v = true
 A template constant always true. More...
 
template<typename T , std::size_t StartFrom, typename... Types>
constexpr std::size_t find_next_type_v = find_next_type<T, StartFrom, Types...>::value
 
template<typename T , typename... Types>
constexpr std::size_t find_type_v = find_type<T, Types...>::value
 
template<typename T , typename... Types>
constexpr bool is_any_of_v = is_any_of<T, Types...>::value
 Whether T is among the specified Types (see util::is_any_of). More...
 
template<typename T , typename U >
constexpr auto is_same_decay_v = std::is_same_v<std::decay_t<T>, std::decay_t<U>>
 Whether T and U are the same type, after being applied std::decay. More...
 
template<template< typename...> typename Template, typename T >
constexpr bool is_instance_of_v = is_instance_of<Template, T>::value
 
template<typename T >
constexpr bool is_STLarray_v = is_STLarray<T>::value
 A constant describing whether the specified type is a STL array. More...
 
template<typename T >
constexpr bool is_reference_wrapper_v = is_reference_wrapper<T>::value
 A constant describing whether the specified type is a std::reference_wrapper. More...
 
template<typename T >
constexpr bool is_unique_ptr_v = is_unique_ptr<T>::value
 A constant describing whether the specified type is a std::unique_ptr. More...
 
template<typename T >
constexpr bool is_character_type_v = is_character_type<T>::value
 Whether type T is a character type (see util::is_character_type). More...
 
template<typename T >
constexpr bool is_string_type_v = is_string_type<T>::value
 Whether type T is a character string type (see util::is_string_type). More...
 
template<typename T >
constexpr bool is_basic_string_type_v = is_basic_string_type<T>::value
 
template<typename T >
constexpr bool is_basic_string_view_type_v = is_basic_string_view_type<T>::value
 
constexpr double kGeVToElectrons = 4.237e7
 23.6eV per ion pair, 1e9 eV/GeV More...
 
constexpr double kc = 29.9792458
 Speed of light in vacuum in LArSoft units [cm/ns]. More...
 
constexpr double kMeterToCentimeter = 1.e2
 1 m = 100 cm More...
 
constexpr double kCentimeterToMeter = 1./kMeterToCentimeter
 
constexpr double kMeterToKilometer = 1.e-3
 1000 m = 1 km More...
 
constexpr double kKilometerToMeter = 1./kMeterToKilometer
 
constexpr double keVToMeV = 1.e-6
 1e6 eV = 1 MeV More...
 
constexpr double kMeVToeV = 1./keVToMeV
 
constexpr double kBogusD = -999.
 obviously bogus double value More...
 
constexpr int kBogusI = -999
 obviously bogus integer value More...
 
constexpr float kBogusF = -999.
 obviously bogus float value More...
 
constexpr double quietCompiler = kBogusD*kBogusI*kBogusF*kRecombA*kRecombk*kGeVToElectrons
 
constexpr double kINVALID_DOUBLE = std::numeric_limits<Double_t>::max()
 
constexpr RangeForWrapperTag range_for
 
template<template< typename T, typename...> class Extractor, typename Target , typename Tuple >
constexpr std::size_t index_of_extracted_type_v = index_of_extracted_type<Extractor, Target, Tuple>()
 Direct access to the value in index_of_extracted_type. More...
 
template<typename Target , typename Tuple >
constexpr std::size_t index_of_type_v = index_of_type<Target, Tuple>()
 Direct access to the value in index_of_type. More...
 
template<template< typename T, typename...> class Extractor, typename Target , typename Tuple >
constexpr bool has_extracted_type_v = has_extracted_type<Extractor, Target, Tuple>()
 Direct access to the value in has_extracted_type. More...
 
template<typename Target , typename Tuple >
constexpr bool has_type_v = has_type<Target, Tuple>()
 Direct access to the value in has_type. More...
 
template<template< typename T, typename...> class Extractor, typename Tuple >
constexpr bool has_duplicate_extracted_types_v = has_duplicate_extracted_types<Extractor, Tuple>()
 Direct access to the value in has_duplicate_extracted_types. More...
 
template<typename Tuple >
constexpr bool has_duplicate_types_v = has_duplicate_types<Tuple>()
 Direct access to the value in has_duplicate_types. More...
 
template<template< typename T, typename...> class Extractor, typename Target , typename Tuple >
constexpr unsigned int count_extracted_types_v = count_extracted_types<Extractor, Target, Tuple>()
 Direct access to the value in count_extracted_types. More...
 
template<typename Target , typename Tuple >
constexpr unsigned int count_types_v = count_types<Target, Tuple>()
 Direct access to the value in count_extracted_types. More...
 
template<typename Tag , typename Tuple >
constexpr std::size_t index_of_tag_v = index_of_tag<Tag, Tuple>()
 Direct access to the value in index_of_tag. More...
 
template<typename Tag , typename Tuple >
constexpr bool has_tag_v = has_tag<Tag, Tuple>()
 Direct access to the value in has_tag. More...
 
template<typename Tag , typename Tuple >
constexpr unsigned int count_tags_v = count_tags<Tag, Tuple>()
 Direct access to the value in count_tags. More...
 
template<typename Tuple >
constexpr bool has_duplicate_tags_v = has_duplicate_tags<Tuple>()
 Direct access to the value in has_duplicate_tags. More...
 
const float SQRT_TWO_PI = 2.506628
 
Recombination factor coefficients (NIM).
See Also
sim::ISCalculationSeparate::CalculateIonizationAndScintillation()

Recombination factor coefficients come from Nucl.Instrum.Meth.A523:275-286,2004

  • $ dE/dx $ is given by the voxel energy deposition, but have to convert it to MeV/cm from GeV/voxel width
  • electric field: $ E $ in kV/cm
  • $ R = A/(1 + (dE/dx)*k/E) $
  • $ A = 0.800 \pm 0.003 $
  • $ k = 0.0486 $ needs to be scaled with Electric field
constexpr double kRecombA = 0.800
 A constant. More...
 
constexpr double kRecombk = 0.0486
 
Recombination factor coefficients (modified box, ArguNeuT JINST).
See Also
sim::ISCalculationSeparate::CalculateIonizationAndScintillation()

Recombination factor coefficients come from Nucl.Instrum.Meth.A523:275-286,2004

  • $ dE/dx $ is given by the voxel energy deposition, but have to convert it to MeV/cm from GeV/voxel width
  • electric field: $ E $ in kV/cm
  • kModBoxB needs to be scaled with the electric field.
constexpr double kModBoxA = 0.930
 Modified Box Alpha. More...
 
constexpr double kModBoxB = 0.212
 Modified Box Beta in g/(MeV cm)*kV/cm. More...
 
template<typename Target , typename... T>
using count_type_in_list = details::count_type_in_list_impl< Target, T...>
 Returns how many of the types in T exactly match Target. More...
 
template<std::size_t N, typename... T>
using typelist_element_type = std::tuple_element< N, std::tuple< T...>>
 Returns the N type of the type list. More...
 
template<std::size_t N, typename... T>
using typelist_element_t = typename typelist_element_type< N, T...>::type
 Direct access to the value in typelist_element_type. More...
 
template<typename Target , typename... T>
using type_is_in = details::type_is_in_impl< Target, T...>
 Holds whether the Target type is among the ones in the T pack. More...
 
template<typename Target , typename... T>
constexpr unsigned int count_type_in_list_v = count_type_in_list<Target, T...>()
 Direct access to the value in count_type_in_list. More...
 
template<typename Target , typename... T>
constexpr bool type_is_in_v = type_is_in<Target, T...>()
 Direct access to the value in type_is_in. More...
 

Detailed Description

Namespace for general, non-LArSoft-specific utilities.

Namespace for general, not LArSoft-specific utilities.

General LArSoft Utilities.

Generic namespace of utility functions generally independent of LArSoft.

Some physical constants are also included here. As a reminder, the "standard" units in LArSoft are:

SumSecondFunction 28-Jul-2009 William Seligman selig.nosp@m.man@.nosp@m.nevis.nosp@m..col.nosp@m.umbia.nosp@m..edu When using STL, maps, and the std::accumulate function, there's one function I keep coding over and over again: accumulate the second member of a pair.

To save myself time (and others who know and use STL), here's a complete STL-compatible implementation of that function. To use it, assume you have an object:

std::map<K,V> myMap;

To sum all the V's in the map:

V sum = std::accumulate( myMap.begin(),myMap.end(),V(),SumSecondFunction<K,V>() );

(Yes, I know there are other, better ways to do this, if one has access to BOOST. Unfortunately, we're not supposed to use BOOST in LArSoft, since as of Jul-2009 it's not universally installed on FNAL machines.)

VectorMap 17-Apr-2008 William Seligman selig.nosp@m.man@.nosp@m.nevis.nosp@m..col.nosp@m.umbia.nosp@m..edu

This class is an implementation of a concept discussion in "Effective STL" by Scott Meyers:

STL maps are useful because their contents are always sorted, so they're effective for fast searches. However, in almost every other respect vectors are superior: They take up less space, and they use random-access iterators.

This class implements "sorted vector maps," that is, an STL-style map implemented as a sorted STL vector of pairs. I've done my best to implement all aspects of the std::map interface in this class, with some additions; if you've defined the following:

VectorMap<key_type, data_type> svm;

INCREDIBLY IMPORTANT NOTE: The "key type" of a VectorMap cannot be a "const" type (unlike maps); it won't even compile. When you do an insert, the underlying vector has to move things around within its list, and it uses the assignment operator=() (or "vector{i+1)=vector(i)" if you like). You can't do that if either the key or the data is const.

As with a map, there's no way to insert items at a specific location in a VectorMap. The insertion methods (including operator[]) all operate on a sorted sequence according to the key. Because of this, insertions take a long time.

However, for our processing, this doesn't matter much; for almost all our maps, we typically have:

For this usage, a sorted vector is generally superior to a map.

This class just implements the equivalent of an STL map, not a multimap, set, nor a multiset. If there's a need, I may create additional classes.

Is there any map feature that's not implemented? Yes:

Advanced implementation note: Depending on the application, it might be possible to speed up this class by using "lazy evaluation"; that is, we wouldn't actually sort the vector until the user actually tries to access its contents. I'm not going to do this, because:

A) I don't think my programming skills are up to the task.

B) In the primary application for which I plan to use this class (Monte-Carlo particle tracks), we're performing at least one search after every insert; lazy evaluation wouldn't be much of a speed improvement.

Feb-2011 WGS: VectorMap mostly looks like a map, but there are some memory-management issues that relate to it being a vector. Include the vector-based routines reserve() and capacity().

Title: GaussianEliminationAlg Class Author: Wes Ketchum (wketc.nosp@m.hum@.nosp@m.lanl..nosp@m.gov)

Description: Class that solves system of linear equations via Gaussian Elimination. Intended for use with RFFHitFitter

Typedef Documentation

template<typename Handle >
using util::ArtHandleData_t = typedef typename Handle::element_type::value_type

Type of data in a art handle to vector data product.

Definition at line 42 of file DataProductPointerMap.h.

template<typename T >
using util::DataProductPointerMap_t = typedef details::DataProductPointerMap_t<T>

Type of map for data product pointers to art pointers.

Definition at line 46 of file DataProductPointerMap.h.

template<typename DATUM >
using util::GridContainer2D = typedef GridContainerBase2D<DATUM, GridContainer2DIndices>

Container allowing 2D indexing.

Template Parameters
DATUMtype of contained data
See Also
GridContainer2DIndices

This is an alias for GridContainerBase2D, with a proper index manager. See the documentation of GridContainerBase2D.

Definition at line 267 of file GridContainers.h.

Index manager for a container of data arranged on a 2D grid.

Definition at line 181 of file GridContainerIndices.h.

template<typename DATUM >
using util::GridContainer3D = typedef GridContainerBase3D<DATUM, GridContainer3DIndices>

Container allowing 3D indexing.

Template Parameters
DATUMtype of contained data
See Also
GridContainer3DIndices

This is an alias for GridContainerBase3D, with a proper index manager. See the documentation of GridContainerBase3D.

Definition at line 279 of file GridContainers.h.

Index manager for a container of data arranged on a 3D grid.

Definition at line 184 of file GridContainerIndices.h.

using util::MatrixIndices = typedef TensorIndices<2U>

Type for indexing a 2D-tensor (matrix)

Definition at line 551 of file TensorIndices.h.

Definition at line 48 of file DatabaseUtil.h.

Definition at line 49 of file DatabaseUtil.h.

typedef int util::UBLArSoftCh_t

Definition at line 46 of file DatabaseUtil.h.

Function Documentation

template<typename T >
constexpr auto util::abs ( v)

Returns the absolute value of the argument.

Template Parameters
Ttype of the argument
Parameters
vvalue to be processed
Returns
the absolute value of v

If the value v is negative, its opposite is returned. Note that this implementation does not work with data types that are not comparable (like std::complex).

Requirements

  • constexpr construction of a T value from the literal 0
  • operator- (T) constexpr
  • operator< (T, T) constexpr convertible to bool

Definition at line 40 of file constexpr_math.h.

40 { return (-T(0) < v)? v: -v; }
template<typename A , typename B >
constexpr auto util::absDiff ( A const &  a,
B const &  b 
)

Returns the absolute value of the difference between two values.

Template Parameters
Atype of the first value
Btype of the second value (must actually be as A)
Parameters
athe first value
bthe second value
Returns
the difference between the largest and the smallest of a and b

The pecularity of this implementation is that it always avoids taking the difference between the smallest and the largest of a and b. An equivalent implementation is:

return std::max(a, b) - std::min(a, b);

It still assumes that the difference is representable in A; for example, this assumption will fail for int types with a a very large number and b a very small (i.e. negative) number.

Requirements:

  • A and B must be the same type

Definition at line 43 of file NumericUtils.h.

44  {
45  static_assert(
46  std::is_same<std::decay_t<A>, std::decay_t<B>>(),
47  "Arguments of util::absDiff() have to be of the same type."
48  );
49  return (b > a)? (b - a): (a - b);
50  }
process_name gaushit a
template<class A >
auto util::associated_groups ( A const &  assns)

Helper functions to access associations in order.

Template Parameters
Atype of association being read
Parameters
assnsthe association being read
See Also
for_each_associated_group()

This function provides a functionality equivalent to art::for_each_group(), but it grants the caller additional control on the external loop and on the function.

Example: assuming that a module with input tag stored in fTrackTag has created associations of each track to its hits, the total charge for each track can be extracted by:

auto assns = art::getValidHandle<art::Assns<recob::Track, recob::Hit>>
(fTrackTag);
std::vector<double> totalCharge;
for (auto const& hits: util::associated_groups(*assns)) {
double total = 0.;
for (art::Ptr<recob::Hit> const& hit: hits)
total += hit->Integral();
totalCharge.push_back(total);
} // for

A number of important points need to be realised about this example:

  • the requirements of this function on its input association are the same as for art::for_each_group()
  • we can code the action on each group of hits directly in a loop, if like in this case the code is succinct
  • again, there is one outer loop iteration for every track;
  • the value of hits is an object representing a range of art pointers (art::Ptr<recob::Hit>) which can be navigated with the begin()/end() free functions, or in a range-for loop;
  • on each iteration, the information of which track the hits are associated to is not available; if that is also needed, use util::associated_groups_with_left() instead.

Definition at line 94 of file ForEachAssociatedGroup.h.

94  {
95  return assns |
96  ranges::views::all |
97  ranges::views::group_by([](auto a1, auto a2) { return a1.first == a2.first;}) |
98  ranges::views::transform([] (auto pairs) {return pairs | ranges::views::values | util::range_for;}) |
100  ;
101  } // associated_groups()
static constexpr Sample_t transform(Sample_t sample)
#define a2
constexpr RangeForWrapperTag range_for
#define a1
template<class A >
auto util::associated_groups_with_left ( A const &  assns)

Helper functions to access associations in order, also with key.

Template Parameters
Atype of association being read
Parameters
assnsthe association being read
See Also
for_each_associated_group()

This function provides a functionality equivalent to art::for_each_group_with_left(), but it grants the caller additional control on the external loop and on the function.

Example: assuming that a module with input tag stored in fTrackTag has created associations of each track to its hits, the total charge for each track can be extracted by:

auto assns = art::getValidHandle<art::Assns<recob::Track, recob::Hit>>
(fTrackTag);
std::map<int, double> totalCharge;
for (auto const& trackWithHits: util::associated_groups_with_left(*assns))
{
art::Ptr<recob::Track> const& track = trackWithHits.first;
auto const& hits = trackWithHits.second;
if (totalCharge.count(track->ID()) > 0) {
throw art::Exception(art::errors::LogicError)
<< "Multiple tracks have ID " << track->ID() << "!\n";
}
double& total = totalCharge[track->ID()];
total = 0.0;
for (art::Ptr<recob::Hit> const& hit: hits)
total += hit->Integral();
} // for

A number of important points need to be realised about this example:

  • the requirements of this function on its input association are the same as for art::for_each_group_with_left()
  • we can code the action on each group of hits directly in a loop, if like in this case the code is succinct
  • again, there is one outer loop iteration for every track;
  • the value of hits is an object representing a range of art pointers (art::Ptr<recob::Hit>) which can be navigated with the begin()/end() free functions, or in a range-for loop.

Definition at line 152 of file ForEachAssociatedGroup.h.

152  {
153  return assns
154  | ranges::views::all
155  | ranges::views::group_by([](auto a1, auto a2) { return a1.first == a2.first;})
156  | ranges::views::transform([] (auto pairs)
157  {
158  return std::make_pair(
159  pairs.front().first, // assuming they're all the same, pick first
161  );
162  })
164  ;
165  } // associated_groups_with_left()
static constexpr Sample_t transform(Sample_t sample)
#define a2
constexpr RangeForWrapperTag range_for
#define a1
template<typename Coll , typename KeyOp , typename CmpOp , typename RefOp , typename KeySortOp >
auto util::clusterBy ( Coll const &  objs,
KeyOp  keyFunc,
CmpOp  sameGroup,
RefOp  objRef,
KeySortOp  keySort 
)

Performs a simple clustering.

Template Parameters
Colltype of collection of objects to cluster
KeyOptype of operation extracting the relevant key for clustering
CmpOptype of operation determining if object belongs to a cluster
RefOptype of operation extracting the object to store in cluster
KeySortOptype of operation sorting the clustering keys
Parameters
collcollection of objects to cluster
keyFuncoperation extracting the relevant key for clustering
sameGroupoperation determining if an object belongs to a cluster
objRefoperation extracting the object to store in the cluster
keySortoperation sorting the clustering keys
Returns
a STL vector of clusters of object "references"

The algorithm clusters objects whose key is compatible. The key must be sortable (keySort). Each cluster is assigned a key value, and all the unclustered objects whose key (keyFunc) is compatible (sameGroup) with that cluster key are added to that cluster. The objects from coll are considered in order of key value, with the order being defined by keySort. Each cluster contains a derivative of the original object (objRef), which may be for example a pointer to the original object, a copy of it, or in fact anything objRef returns.

The return value is in the form of a std::vector in which each element represents a cluster. Each of these clusters is a std::vector of the derivative objects.

Requirements

  • Coll: an iterable collection of objects of type Object_t;
  • KeyOp: a functor returning the key of an object, like Key_t keyFunc(Object_t const&);
  • KeySortOp: a functor like bool keySort(Key_t a, Key_t b) returning strict ordering between key values a and b;
  • CmpOp: a functor like bool keySort(Key_t a, Key_t b) returning if an object with key b should belong to a cluster with key a;
  • RefOp: a functor returning the object to store in the cluster starting from an object in the original collection: ObjRef_t objRef(Object_t); note that the result should probably not be a C++ reference since they don't go along well with containers.

Definition at line 118 of file icarusalg/icarusalg/Utilities/SimpleClustering.h.

121  {
122 
123  /*
124  * 1. create a list of object key (`keyFunc`) and object reference (`objRef`)
125  * 2. sort that list by key (`keySort`)
126  * 3. cluster object references with nearby keys (`sameGroup`)
127  *
128  * A new cluster is started every time for a new object `sameGroup` return
129  * `false` when applied on the key of the first object in the current cluster
130  * and the key of the new object.
131  *
132  */
133 
134  //
135  // some definitions
136  //
137  using Object_t = typename Coll::value_type;
138  using ObjectRef_t = std::decay_t<decltype(objRef(std::declval<Object_t>()))>;
139  using Cluster_t = std::vector<ObjectRef_t>;
140  using Clusters_t = std::vector<Cluster_t>;
141 
142  auto makeKeyAndObjRef = [keyFunc, objRef](auto&& obj)
143  { return std::make_pair(keyFunc(obj), objRef(obj)); };
144 
145  using KeyAndObjRef_t = decltype(makeKeyAndObjRef(*(util::begin(objs))));
146 
147  //
148  // working data: "map" of objects by key
149  //
150  std::vector<KeyAndObjRef_t> KeysAndObjRefs;
151  KeysAndObjRefs.reserve(objs.size());
153  util::begin(objs), util::end(objs), std::back_inserter(KeysAndObjRefs),
154  makeKeyAndObjRef
155  );
156 
157  // sort the map by key
158  std::sort(
159  util::begin(KeysAndObjRefs), util::end(KeysAndObjRefs),
160  details::makeTupleElementOp<0U>(keySort)
161  );
162 
163  //
164  // cluster the objects in the map by key proximity
165  //
166  Clusters_t clusters;
167  if (KeysAndObjRefs.empty()) return clusters;
168 
169  auto iKeyAndObjRef = util::begin(KeysAndObjRefs);
170  auto const end = util::end(KeysAndObjRefs);
171 
172  auto startCluster = [](auto& keyAndObjRef)
173  {
174  return
175  std::make_pair(keyAndObjRef.first, Cluster_t{ keyAndObjRef.second });
176  };
177  auto addToCluster = [](auto& cluster, auto& keyAndObjRef)
178  { cluster.second.push_back(std::move(keyAndObjRef.second)); };
179 
180  auto currentCluster = startCluster(*iKeyAndObjRef);
181  while(++iKeyAndObjRef != end) {
182 
183  if (sameGroup(iKeyAndObjRef->first, currentCluster.first)) {
184  addToCluster(currentCluster, *iKeyAndObjRef);
185  }
186  else {
187  clusters.push_back(std::move(currentCluster.second));
188  currentCluster = startCluster(*iKeyAndObjRef);
189  }
190 
191  } // while
192  clusters.push_back(std::move(currentCluster.second));
193 
194  return clusters;
195 
196 } // util::clusterBy(Coll, KeyOp, CmpOp, RefOp, KeySortOp)
static constexpr Sample_t transform(Sample_t sample)
process_name cluster
Definition: cheaterreco.fcl:51
decltype(auto) constexpr end(T &&obj)
ADL-aware version of std::end.
Definition: StdUtils.h:77
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
decltype(auto) constexpr begin(T &&obj)
ADL-aware version of std::begin.
Definition: StdUtils.h:72
template<typename Coll , typename KeyOp , typename CmpOp , typename KeySortOp >
auto util::clusterBy ( Coll const &  objs,
KeyOp  keyFunc,
CmpOp  sameGroup,
KeySortOp  keySort 
)

A version of clusterBy() storing a copy of each object as "reference".

Definition at line 202 of file icarusalg/icarusalg/Utilities/SimpleClustering.h.

203 {
204  return clusterBy(objs,
205  std::move(keyFunc), std::move(sameGroup),
206  [](auto const& obj){ return obj; },
207  std::move(keySort)
208  );
209 } // util::clusterBy(Coll, KeyOp, CmpOp, KeySortOp)
auto clusterBy(Coll const &objs, KeyOp keyFunc, CmpOp sameGroup, RefOp objRef, KeySortOp keySort)
Performs a simple clustering.
def util.comma_separated (   inp)

Definition at line 287 of file util.py.

288 def comma_separated(inp):
289  return inp.split(",")
def comma_separated
Definition: util.py:287
template<typename Coll >
decltype(auto) util::const_values ( Coll &&  coll)

Range-for loop helper iterating across the constant values of the specified collection.

See Also
util::values()

This function is equivalent to util::values() but the values are extracted as if the specified collection were constant.

double util::ContainedLength ( const TVector3 &  v0,
const TVector3 &  v1,
const std::vector< geo::BoxBoundedGeo > &  boxes 
)

Calculate length between two points contained in a list of (non-overlapping) volumes. Units are abitrary, but must be consistent between the three inputs.

Parameters
v0The first point
v1The second point
boxesA list of non-overlapping boxes through which the contained length will be calculated.
Returns
The contained length in units of the inputs

Definition at line 28 of file Interaction.cxx.

29  {
30  // if points are the same, return 0
31  if ((v0 - v1).Mag() < 1e-6) return 0;
32 
33  double length = 0;
34 
35  // total contained length is sum of lengths in all boxes
36  // assuming they are non-overlapping
37  for (auto const &box: boxes) {
38  int n_contained = box.ContainsPosition(v0) + box.ContainsPosition(v1);
39  // both points contained -- length is total length (also can break out of loop)
40  if (n_contained == 2) {
41  length = (v1 - v0).Mag();
42  break;
43  }
44  // one contained -- have to find intersection point (which must exist)
45  else if (n_contained == 1) {
46  std::vector<TVector3> intersections = box.GetIntersections(v0, v1);
47  assert(intersections.size() == 1); // should only have one intersection point
48  // get the length
49  length += ( box.ContainsPosition(v0) ? (v0 - intersections[0]).Mag() : (v1 - intersections[0]).Mag() );
50  }
51  else if (n_contained == 0) {
52  std::vector<TVector3> intersections = box.GetIntersections(v0, v1);
53  // should have 0 or 2
54  if (intersections.size() == 2) {
55  length += (intersections[0] - intersections[1]).Mag();
56  }
57  else assert(intersections.size() == 0);
58  }
59  else assert(false); // bad
60  }
61 
62  return length;
63 }
do i e
template<typename T >
auto util::counter ( begin,
end 
)

Returns an object to iterate values from begin to end in a range-for loop.

Template Parameters
Ttype of counter value
Returns
a control object for range-for loop
See Also
util::count_iterator

An example of usage:

std::vector<std::size_t> data;
for (auto i: util::counter(4, 8)) {
data.push_back(i);
}

will insert in data the numbers from 4 to 7, just like:

for (std::size_t i = 4; i < 8; ++i) {
data.push_back(i);
}

would.

Definition at line 285 of file counter.h.

286  { return util::span(count_iterator(begin), count_iterator(end)); }
Simple class with a begin and an end.
Definition: span.h:125
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename T >
auto util::counter ( end)

Version of util::counter() starting at default-constructed T (usually some form of 0).

Definition at line 184 of file counter.h.

184 { return counter(T{}, end); }
auto counter(T begin, T end)
Returns an object to iterate values from begin to end in a range-for loop.
Definition: counter.h:285
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
template<class T , class U >
static bool util::CreateAssn ( art::EDProducer const &  prod,
art::Event &  evt,
std::vector< T > &  a,
art::Ptr< U >  b,
art::Assns< T, U > &  assn,
size_t  indx = UINT_MAX,
std::string const &  instance = std::string() 
)
static

Create a 1 to 1 association between a new product and one already in the event.

Parameters
aThe collection about to be added to the event
bThe product already in the event
indxWhich element of a to associate. By default the last one.
instanceinstance label for product, defaulted to be an empty string
template<class T , class U >
static bool util::CreateAssn ( art::EDProducer const &  prod,
art::Event &  evt,
std::vector< T > &  a,
art::Ptr< U >  b,
art::Assns< T, U > &  assn,
size_t  begin_indx,
size_t  end_indx,
std::string const &  instance = std::string() 
)
static

Create a 1 to 1 association between each of a series of new products and one already in the event.

Parameters
aThe collection about to be added to the event
bThe product already in the event
begin_indxWhich element of a to associate first.
end_indxOne more than the index of the last element to associate
instanceinstance label for product, defaulted to be an empty string
template<class T , class U >
static bool util::CreateAssn ( art::EDProducer const &  prod,
art::Event &  evt,
art::Ptr< T > &  a,
art::Ptr< U >  b,
art::Assns< T, U > &  assn 
)
static

Create a 1 to 1 association between two products already in the event.

Parameters
aA product already in the event
bAnother product already in the event
template<class T , class U >
static bool util::CreateAssn ( art::EDProducer const &  prod,
art::Event &  evt,
std::vector< T > &  a,
art::PtrVector< U >  b,
art::Assns< T, U > &  assn,
size_t  indx = UINT_MAX,
std::string const &  instance = std::string() 
)
static

Create a 1 to many association between a new product and a PtrVector already in the event.

Parameters
aThe collection about to be added to the event
bThe products already in the event
indxWhich element of a to associate. By default the last one.
instanceinstance label for product, defaulted to be an empty string
template<class T , class U >
static bool util::CreateAssn ( art::EDProducer const &  prod,
art::Event &  evt,
art::Ptr< T > &  a,
std::vector< art::Ptr< U > >  b,
art::Assns< T, U > &  assn 
)
static

Create a 1 to many association between products already in the event.

Parameters
aA product already in the event
bA vector of products already in the event (the many)
template<class T , class U >
static bool util::CreateAssn ( art::EDProducer const &  prod,
art::Event &  evt,
std::vector< T > &  a,
std::vector< art::Ptr< U > >  b,
art::Assns< T, U > &  assn,
size_t  indx = UINT_MAX,
std::string const &  instance = std::string() 
)
static

Create a 1 to many association between a new product and a vector of Ptrs already in the event.

Parameters
aThe collection about to be added to the event
bThe products already in the event
indxWhich element of a to associate. By default the last one.
instanceinstance label for product, defaulted to be an empty string
template<class T , class U >
static bool util::CreateAssn ( art::EDProducer const &  prod,
art::Event &  evt,
std::vector< T > &  a,
std::vector< U > &  b,
art::Assns< T, U > &  assn,
size_t  startU,
size_t  endU,
size_t  indx = UINT_MAX,
std::string const &  instancea = std::string(),
std::string const &  instanceb = std::string() 
)
static

Create a 1 to many association between new products.

Parameters
aA collection about to be added to the event
bAnother collection about to be added to the event
startUThe first element of b to associate
endUThe last element of b to associate +1 (like STL begin() and end())
indxWhich element of a to associate. By default the last one.
instanceainstance label for product a, defaulted to be an empty string
instancebinstance label for product b, defaulted to be an empty string
template<class T , class U >
static bool util::CreateAssn ( art::EDProducer const &  prod,
art::Event &  evt,
art::Assns< T, U > &  assn,
std::vector< T > &  a,
std::vector< U > &  b,
size_t  indxb = UINT_MAX,
size_t  indxa = UINT_MAX,
std::string const &  instancea = std::string(),
std::string const &  instanceb = std::string() 
)
static

Create a 1 to 1 between new products.

Parameters
aA collection about to be added to the event
bAnother collection about to be added to the event
indxbWhich element of b to associate. By default the last one.
indxaWhich element of a to associate. By default the last one.
instanceainstance label for product a, defaulted to be an empty string
instancebinstance label for product b, defaulted to be an empty string
template<class T , class U >
bool util::CreateAssn ( art::Event &  evt,
std::vector< T > const &  a,
art::Ptr< U > const &  b,
art::Assns< U, T > &  assn,
std::string  a_instance,
size_t  index = UINT_MAX 
)

Creates a single one-to-one association.

Template Parameters
Ttype of the new object to associate
Utype of the object already in the data product or art::Ptr
Parameters
evtreference to the current event
avector of data products that are in, or will be put into, evt
bart::Ptr to the (new) object to be associated to the one in a
assnreference to association object where the new one will be put
a_instancename of the instance that will be used for a in evt
indexindex of the element in a to be associated with b (default: the last element)
Returns
whether the operation was successful (can it ever fail??)

As example of usage: create a wire/raw digit association. This code should live in the art::EDProduce::produce() method. The raw::RawDigit product was created already by a DigitModuleLabel module. The code is supposed to produce one recob::Wire for each existing raw::RawDigit, and contextually associate the new wire to the source digit. We are also assuming that there might be different RawDigit sets produced by the same producer: we identify the one we care of by the string spill_name and we create wires and associations with the same label for convenience.

// this is the original list of digits, thawed from the event
art::Handle< std::vector<raw::RawDigit>> digitVecHandle;
evt.getByLabel(DigitModuleLabel, spill_name, digitVecHandle);

// the collection of wires that will be written as data product
std::unique_ptr<std::vector<recob::Wire>> wirecol(new std::vector<recob::Wire>);
// ... and an association set
std::unique_ptr<art::Assns<raw::RawDigit,recob::Wire>> WireDigitAssn
  (new art::Assns<raw::RawDigit,recob::Wire>);

for(size_t iDigit = 0; iDigit < digitVecHandle->size(); ++iDigit) {
  // turn the digit into a art::Ptr:
  art::Ptr<raw::RawDigit> digit_ptr(digitVecHandle, iDigit);

  // store the wire in its final position in the data product;
  // the new wire is currently the last of the list
  wirecol->push_back(std::move(wire));

  // add an association between the last object in wirecol
  // (that we just inserted) and digit_ptr
  if (!util::CreateAssn(*this, evt, *wirecol, digit_ptr, *WireDigitAssn, spill_name)) {
    throw art::Exception(art::errors::ProductRegistrationFailure)
      << "Can't associate wire #" << (wirecol->size() - 1)
      << " with raw digit #" << digit_ptr.key();
  } // if failed to add association

} // for digits

evt.put(std::move(wirecol), spill_name);
evt.put(std::move(WireDigitAssn), spill_name);

Definition at line 586 of file lardata/lardata/Utilities/AssociationUtil.h.

594 {
595  if (index == UINT_MAX) index = a.size()-1;
596 
597  try{
598  assn.addSingle(b, art::PtrMaker<T>{evt, a_instance}(index));
599  return true;
600  }
601  catch(cet::exception &e){
602  mf::LogWarning("AssociationUtil")
603  << "unable to create requested art:Assns, exception thrown: " << e;
604  return false;
605  }
606 
607 } // util::CreateAssn() [01]
do i e
TCEvent evt
Definition: DataStructs.cxx:8
template<class T , class U >
static bool util::CreateAssn ( art::EDFilter const &  prod,
art::Event &  evt,
std::vector< T > &  a,
art::Ptr< U >  b,
art::Assns< T, U > &  assn,
size_t  indx = UINT_MAX,
std::string const &  instance = std::string() 
)
static

Create a 1 to 1 association between a new product and one already in the event.

Parameters
aThe collection about to be added to the event
bThe product already in the event
indxWhich element of a to associate. By default the last one.
instanceinstance label for product, defaulted to be an empty string
template<class T , class U >
static bool util::CreateAssn ( art::EDFilter const &  prod,
art::Event &  evt,
std::vector< T > &  a,
art::Ptr< U >  b,
art::Assns< T, U > &  assn,
size_t  begin_indx,
size_t  end_indx,
std::string const &  instance = std::string() 
)
static

Create a 1 to 1 association between each of a series of new products and one already in the event.

Parameters
aThe collection about to be added to the event
bThe product already in the event
begin_indxWhich element of a to associate first.
end_indxOne more than the index of the last element to associate
instanceinstance label for product, defaulted to be an empty string
template<class T , class U >
bool util::CreateAssn ( art::Event &  evt,
std::vector< T > const &  a,
art::Ptr< U > const &  b,
art::Assns< U, T > &  assn,
size_t  index = UINT_MAX 
)
inline

Creates a single one-to-one association.

Template Parameters
Ttype of the new object to associate
Utype of the object already in the data product or art::Ptr
Parameters
evtreference to the current event
avector of data products that are in, or will be put into, evt
bart::Ptr to the (new) object to be associated to the one in a
assnreference to association object where the new one will be put
indexindex of the element in a to be associated with b (default: the last element)
Returns
whether the operation was successful (can it ever fail??)

The instance name of the product a will be in is assumed empty. Example of usage:

// this is the original list of digits, thawed from the event
art::Handle< std::vector<raw::RawDigit>> digitVecHandle;
evt.getByLabel(DigitModuleLabel, digitVecHandle);

// the collection of wires that will be written as data product
std::unique_ptr<std::vector<recob::Wire>> wirecol(new std::vector<recob::Wire>);
// ... and an association set
std::unique_ptr<art::Assns<raw::RawDigit,recob::Wire>> WireDigitAssn
  (new art::Assns<raw::RawDigit,recob::Wire>);

for(size_t iDigit = 0; iDigit < digitVecHandle->size(); ++iDigit) {
  // turn the digit into a art::Ptr:
  art::Ptr<raw::RawDigit> digit_ptr(digitVecHandle, iDigit);

  // store the wire in its final position in the data product;
  // the new wire is currently the last of the list
  wirecol->push_back(std::move(wire));

  // add an association between the last object in wirecol
  // (that we just inserted) and digit_ptr
  if (!util::CreateAssn(*this, evt, *wirecol, digit_ptr, *WireDigitAssn)) {
    throw art::Exception(art::errors::ProductRegistrationFailure)
      << "Can't associate wire #" << (wirecol->size() - 1)
      << " with raw digit #" << digit_ptr.key();
  } // if failed to add association

} // for digits

evt.put(std::move(wirecol));
evt.put(std::move(WireDigitAssn));

Definition at line 214 of file lardata/lardata/Utilities/AssociationUtil.h.

219  { return CreateAssn(evt, a, b, assn, std::string(), index); }
bool CreateAssn(art::Event &evt, std::vector< T > const &a, art::Ptr< U > const &b, art::Assns< U, T > &assn, std::string a_instance, size_t index=UINT_MAX)
Creates a single one-to-one association.
TCEvent evt
Definition: DataStructs.cxx:8
template<class T , class U >
static bool util::CreateAssn ( art::EDFilter const &  prod,
art::Event &  evt,
art::Ptr< T > &  a,
art::Ptr< U >  b,
art::Assns< T, U > &  assn 
)
static

Create a 1 to 1 association between two products already in the event.

Parameters
aA product already in the event
bAnother product already in the event
template<class T , class U >
static bool util::CreateAssn ( art::EDFilter const &  prod,
art::Event &  evt,
std::vector< T > &  a,
art::PtrVector< U >  b,
art::Assns< T, U > &  assn,
size_t  indx = UINT_MAX,
std::string const &  instance = std::string() 
)
static

Create a 1 to many association between a new product and a PtrVector already in the event.

Parameters
aThe collection about to be added to the event
bThe products already in the event
indxWhich element of a to associate. By default the last one.
instanceinstance label for product, defaulted to be an empty string
template<class T , class U >
bool util::CreateAssn ( art::Event &  evt,
art::Ptr< T > const &  a,
art::Ptr< U > const &  b,
art::Assns< U, T > &  assn 
)

Creates a single one-to-one association.

Template Parameters
Ttype of one object to associate
Utype of the other object to associate
Parameters
evtreference to the current event
aart::Ptr to the first object in the association
bart::Ptr to the object to be associated to the one in a
assnreference to association object where the new one will be put
Returns
whether the operation was successful (can it ever fail??)

This is the simplest way ever. Neither the event not the producer references are used.

Definition at line 613 of file lardata/lardata/Utilities/AssociationUtil.h.

618  {
619 
620  try{
621  assn.addSingle(b, a);
622  }
623  catch(cet::exception &e){
624  mf::LogWarning("AssociationUtil")
625  << "unable to create requested art:Assns, exception thrown: " << e;
626  return false;
627  }
628 
629  return true;
630 } // util::CreateAssn() [03]
process_name gaushit a
do i e
template<class T , class U >
static bool util::CreateAssn ( art::EDFilter const &  prod,
art::Event &  evt,
art::Ptr< T > &  a,
std::vector< art::Ptr< U > >  b,
art::Assns< T, U > &  assn 
)
static

Create a 1 to many association between products already in the event.

Parameters
aA product already in the event
bA vector of products already in the event (the many)
template<class T , class U >
static bool util::CreateAssn ( art::EDFilter const &  prod,
art::Event &  evt,
std::vector< T > &  a,
std::vector< art::Ptr< U > >  b,
art::Assns< T, U > &  assn,
size_t  indx = UINT_MAX,
std::string const &  instance = std::string() 
)
static

Create a 1 to many association between a new product and a vector of Ptrs already in the event.

Parameters
aThe collection about to be added to the event
bThe products already in the event
indxWhich element of a to associate. By default the last one.
instanceinstance label for product, defaulted to be an empty string
template<class T , class U >
bool util::CreateAssn ( art::Event &  evt,
std::vector< T > const &  a,
art::PtrVector< U > const &  b,
art::Assns< T, U > &  assn,
size_t  index = UINT_MAX 
)

Creates a single one-to-many association.

Template Parameters
Ttype of the new object to associate
Utype of the many objects already in the data product or art::Ptr
Parameters
evtreference to the current event
avector of data products that are in, or will be put into, evt
bart::PtrVector to the (new) objects to be associated to the one in a
assnreference to association object where the new one will be put
indexindex of the element in a to be associated with all the ones in b (default: the last element)
Returns
whether the operation was successful (can it ever fail??)

A "one-to-many" association is actually a number of one-to-one associations. If you want to keep the information of the order of the many, you may have to use an association with a data member (the third template parameter that we pretent not to exist).

Definition at line 636 of file lardata/lardata/Utilities/AssociationUtil.h.

642  {
643  if(index == UINT_MAX) index = a.size() - 1;
644 
645  try{
646  auto const aptr = art::PtrMaker<T>{evt}(index);
647  for(art::Ptr<U> const& b_item: b) assn.addSingle(aptr, b_item);
648  }
649  catch(cet::exception &e){
650  mf::LogWarning("AssociationUtil")
651  << "unable to create requested art:Assns, exception thrown: " << e;
652  return false;
653  }
654 
655  return true;
656 } // util::CreateAssn() [04]
do i e
TCEvent evt
Definition: DataStructs.cxx:8
template<class T , class U >
static bool util::CreateAssn ( art::EDFilter const &  prod,
art::Event &  evt,
std::vector< T > &  a,
std::vector< U > &  b,
art::Assns< T, U > &  assn,
size_t  startU,
size_t  endU,
size_t  indx = UINT_MAX,
std::string const &  instancea = std::string(),
std::string const &  instanceb = std::string() 
)
static

Create a 1 to many association between new products.

Parameters
aA collection about to be added to the event
bAnother collection about to be added to the event
startUThe first element of b to associate
endUThe last element of b to associate +1 (like STL begin() and end())
indxWhich element of a to associate. By default the last one.
instanceainstance label for product a, defaulted to be an empty string
instancebinstance label for product b, defaulted to be an empty string
template<class T , class U >
static bool util::CreateAssn ( art::EDFilter const &  prod,
art::Event &  evt,
art::Assns< T, U > &  assn,
std::vector< T > &  a,
std::vector< U > &  b,
size_t  indxb = UINT_MAX,
size_t  indxa = UINT_MAX,
std::string const &  instancea = std::string(),
std::string const &  instanceb = std::string() 
)
static

Create a 1 to 1 between new products.

Parameters
aA collection about to be added to the event
bAnother collection about to be added to the event
indxbWhich element of b to associate. By default the last one.
indxaWhich element of a to associate. By default the last one.
instanceainstance label for product a, defaulted to be an empty string
instancebinstance label for product b, defaulted to be an empty string
template<class T , class U >
bool util::CreateAssn ( art::Event &  evt,
art::Ptr< T > const &  a,
std::vector< art::Ptr< U >> const &  b,
art::Assns< T, U > &  assn 
)

Creates a single one-to-many association.

Template Parameters
Ttype of the new object to associate
Utype of the many objects already in the data product or art::Ptr
Parameters
evtreference to the current event
aart::Ptr to the item to be associated with many
bvector to art::Ptr to the (new) objects to be associated to a
assnreference to association object where the new one will be put
Returns
whether the operation was successful (can it ever fail??)

A "one-to-many" association is actually a number of one-to-one associations. If you want to keep the information of the order of the many, you may have to use an association with a data member (the third template parameter that we pretent not to exist).

Definition at line 661 of file lardata/lardata/Utilities/AssociationUtil.h.

666  {
667 
668  try{
669  for (art::Ptr<U> const& b_item: b) assn.addSingle(a, b_item);
670  }
671  catch(cet::exception const& e){
672  mf::LogWarning("AssociationUtil")
673  << "unable to create requested art:Assns, exception thrown: " << e;
674  return false;
675  }
676 
677  return true;
678 } // util::CreateAssn() [05]
process_name gaushit a
do i e
template<class T , class U >
bool util::CreateAssn ( art::Event &  evt,
std::vector< T > const &  a,
std::vector< art::Ptr< U >> const &  b,
art::Assns< T, U > &  assn,
size_t  index = UINT_MAX 
)

Creates a single one-to-many association.

Template Parameters
Ttype of the new object to associate
Utype of the many objects already in the data product or art::Ptr
Parameters
evtreference to the current event
avector of data products that are in, or will be put into, evt
bvector to art::Ptr to the (new) objects to be associated to the one in a
assnreference to association object where the new one will be put
indexindex of the element in a to be associated with all the ones in b (default: the last element)
Returns
whether the operation was successful (can it ever fail??)

A "one-to-many" association is actually a number of one-to-one associations. If you want to keep the information of the order of the many, you may have to use an association with a data member (the third template parameter that we pretent not to exist).

Definition at line 683 of file lardata/lardata/Utilities/AssociationUtil.h.

689  {
690 
691  if (index == UINT_MAX) index = a.size() - 1;
692 
693  try{
694  auto const aptr = art::PtrMaker<T>{evt}(index);
695  for (art::Ptr<U> const& b_item: b) assn.addSingle(aptr, b_item);
696  }
697  catch(cet::exception &e){
698  mf::LogWarning("AssociationUtil")
699  << "unable to create requested art:Assns, exception thrown: " << e;
700  return false;
701  }
702 
703  return true;
704 } // util::CreateAssn() [06]
do i e
TCEvent evt
Definition: DataStructs.cxx:8
template<class T , class U >
bool util::CreateAssn ( art::Event &  evt,
std::vector< T > const &  a,
std::vector< U > const &  b,
art::Assns< T, U > &  assn,
size_t  startU,
size_t  endU,
size_t  index = UINT_MAX 
)

Creates a single one-to-many association.

Template Parameters
Ttype of the new object to associate
Utype of the many objects already in the data product or art::Ptr
Parameters
evtreference to the current event
avector of data products that are in, or will be put into, evt
bvector of the (new) objects to be associated to the one in a
assnreference to association object where the new one will be put
startUindex in b of the first element to be associated to the one in a
endUindex in b after the last element to be associated to the one in a
indexindex of the element in a to be associated with all the ones in b (default: the last element)
Returns
whether the operation was successful (can it ever fail??)

Use this when the objects in b are not yet stored in the event and are in a std::vector collection instead.

The method gets the product id for those as well as for the element in a. Also specify the range of entries to use from the std::vector collection of U objects.

A "one-to-many" association is actually a number of one-to-one associations. If you want to keep the information of the order of the many, you may have to use an association with a data member (the third template parameter that we pretent not to exist).

Definition at line 709 of file lardata/lardata/Utilities/AssociationUtil.h.

717  {
718 
719  if(index == UINT_MAX) index = a.size() - 1;
720 
721  try{
722  auto const aptr = art::PtrMaker<T>{evt}(index);
723  art::PtrMaker<U> const make_bptr{evt};
724  for(size_t i = startU; i < endU; ++i){
725  assn.addSingle(aptr, make_bptr(i));
726  }
727  }
728  catch(cet::exception &e){
729  mf::LogWarning("AssociationUtil")
730  << "unable to create requested art:Assns, exception thrown: " << e;
731  return false;
732  }
733 
734  return true;
735 } // util::CreateAssn() [07]
do i e
TCEvent evt
Definition: DataStructs.cxx:8
template<class T , class U >
bool util::CreateAssn ( art::Event &  evt,
std::vector< T > const &  a,
std::vector< U > const &  b,
art::Assns< T, U > &  assn,
std::vector< size_t > const &  indices,
size_t  index = UINT_MAX 
)

Creates a single one-to-many association.

Template Parameters
Ttype of the new object to associate
Utype of the many objects already in the data product or art::Ptr
Parameters
evtreference to the current event
avector of data products that are in, or will be put into, evt
bvector of the (new) objects to be associated to the one in a
assnreference to association object where the new one will be put
indicesindices of the elements in b to be associated to the one in a
indexindex of the element in a to be associated with all the ones in b (default: the last element)
Returns
whether the operation was successful (can it ever fail??)

Use this when the objects in b are not yet stored in the event and are in a std::vector collection instead.

The method gets the product id for those as well as for the element in a. Also specify the entries to use from the std::vector collection of U objects.

A "one-to-many" association is actually a number of one-to-one associations. If you want to keep the information of the order of the many, you may have to use an association with a data member (the third template parameter that we pretent not to exist).

Definition at line 740 of file lardata/lardata/Utilities/AssociationUtil.h.

747  {
748 
749  if(index == UINT_MAX) index = a.size() - 1;
750 
751  try{
752  auto const aptr = art::PtrMaker<T>{evt}(index);
753  art::PtrMaker<U> const make_bptr{evt};
754  for(size_t index: indices){
755  assn.addSingle(aptr, make_bptr(index));
756  }
757  }
758  catch(cet::exception &e){
759  mf::LogWarning("AssociationUtil")
760  << "unable to create requested art:Assns, exception thrown: " << e;
761  return false;
762  }
763 
764  return true;
765 } // util::CreateAssn() [07a]
do i e
TCEvent evt
Definition: DataStructs.cxx:8
template<typename T , typename U , typename Iter >
bool util::CreateAssn ( art::Event &  evt,
art::Assns< T, U > &  assn,
size_t  first_index,
Iter  from_second_index,
Iter  to_second_index 
)

Creates a single one-to-many association.

Template Parameters
Ttype of the new object to associate
Utype of the many objects already in the data product or art::Ptr
Iteriterator to size_t-compatible elements
Parameters
evtreference to the current event
assnreference to association object where the new one will be put
first_indexindex of the object of type T to be associated to all the others
from_second_indexiterator pointing to the first of the indices of U type objects to be associated to the one of the first type
to_second_indexiterator pointing after the last of the indices of U type objects to be associated to the one of the first type
Returns
whether the operation was successful (can it ever fail??)

A "one-to-many" association is actually a number of one-to-one associations. If you want to keep the information of the order of the many, you may have to use an association with a data member (the third template parameter that we pretent not to exist).

Use this if the objects that have to be associated to the one of type T are sparse, spread across a to-be-data-product, but you have a list of the indices in the data product of the elements to associate to the one of type T. In other words, given that you have a data product "a" of type std::vector<T> and a data product "b" of type std::vector<U>, this method creates an association betweena[first_index]and b[*(from_second_index)], another between a[first_index] and b[*(from_second_index + 1)], etc.

The surprising concept here is that you don't need to specify neither of the collections of T or U elements. The data product is uniquely defined by its type, producer, process and product label. Here we assume that the type of the products are std::vector<T> and std::vector<U>, and that the products have empty product labels, and that the producer is prod for both of them.

Definition at line 770 of file lardata/lardata/Utilities/AssociationUtil.h.

776  {
777 
778  try{
779  // we declare here that we want to associate the element first_index of the
780  // (only) data product of type std::vector<T> with other objects.
781  // This is the pointer to that element:
782  auto const first_ptr = art::PtrMaker<T>{evt}(first_index);
783 
784  // we are going to associate that element in a with a number of elements
785  // of the only data product of type std::vector<U>
786  art::PtrMaker<U> const make_second_ptr{evt};
787  for (; from_second_index != to_second_index; ++from_second_index) {
788  assn.addSingle(first_ptr, make_second_ptr(*from_second_index));
789  } // while
790  }
791  catch(cet::exception &e){
792  mf::LogWarning("AssociationUtil")
793  << "unable to create requested art:Assns, exception thrown: " << e;
794  return false;
795  }
796 
797  return true;
798 } // util::CreateAssn() [08]
do i e
TCEvent evt
Definition: DataStructs.cxx:8
template<typename Producer , typename... Args>
std::enable_if_t<std::is_base_of_v<art::EDProducer, Producer>, bool> util::CreateAssn ( Producer const &  ,
Args &&...  args 
)

Definition at line 973 of file lardata/lardata/Utilities/AssociationUtil.h.

973  {
974  return CreateAssn(std::forward<Args>(args)...);
975  }
bool CreateAssn(art::Event &evt, std::vector< T > const &a, art::Ptr< U > const &b, art::Assns< U, T > &assn, std::string a_instance, size_t index=UINT_MAX)
Creates a single one-to-one association.
template<typename T , typename U , typename D >
bool util::CreateAssnD ( art::Event &  evt,
art::Assns< T, U, D > &  assn,
size_t  first_index,
size_t  second_index,
typename art::Assns< T, U, D >::data_t &&  data 
)

Creates a single one-to-one association with associated data.

Template Parameters
Ttype of the new object to associate
Utype of the many objects already in the data product or art::Ptr
Dtype of the "metadata" coupled to this pair association
Parameters
evtreference to the current event
assnreference to association object where the new one will be put
first_indexindex of the object of type T to be associated
second_indexindex of the object of type U to be associated
data"metadata" to be store in this association
Returns
whether the operation was successful (can it ever fail??)

Use this if you want some metadata to travel together with the association. An example may be the order of the second element within a list:

size_t a_index = 2;
std::vector<size_t> b_indices{ 6, 9, 18, 12 };
for (size_t i = 0; i < b_indices.size(); ++i)
  CreateAssn(prod, evt, assn, a_index, b_index[i], i);

In this way, the association between the element #2 of "a" (a vector that is not specified – nor needed – in this snippet of code) and the element #18 will be remembered as being the third (metadata value of 2). In this example metadata is of type size_t the association would be declared as art::Assn<A, B, size_t>. A FindMany query of that association might look like:

art::Handle<std::vector<A>> a_list; // read this from the event

art::FindMany<B, size_t> Query(a_list, event, ModuleLabel);

// search for the last of the objects associated to the third element:
size_t a_index = 2; // this means third element

std::vector<size_t const*> const& metadata = Query.data(a_index);
size_t largest_index = 0, last_item = 0;
for (size_t iB = 0; iB < metadata.size(); ++iB) {
  if (largest_index >= *(metadata[iB])) continue;
  largest_index = *(metadata[iB]);
  last_item = iB;
} // for iB
B const& lastB = Query.at(last_item);

In alternative, the elements and their metadata can be fetched simultaneously with:

std::vector<art::Ptr<B>> const& Bs;
std::vector<size_t const*> const& metadata;

size_t a_index = 2; // this means third element
size_t nMatches = Query.get(a_index, Bs, metadata);

Definition at line 804 of file lardata/lardata/Utilities/AssociationUtil.h.

810  {
811 
812  try{
813  // we declare here that we want to associate the element first_index of the
814  // (only) data product of type std::vector<T> with the other object
815  auto const first_ptr = art::PtrMaker<T>{evt}(first_index);
816 
817  // the same to associate the element second_index of the (only)
818  // data product of type std::vector<U> with the first object.
819  auto const second_ptr = art::PtrMaker<U>{evt}(second_index);
820 
821  assn.addSingle(first_ptr, second_ptr, std::move(data));
822  }
823  catch(cet::exception &e){
824  mf::LogWarning("AssociationUtil")
825  << "unable to create requested art:Assns, exception thrown: " << e;
826  return false;
827  }
828 
829  return true;
830 } // util::CreateAssnD() [01a]
do i e
TCEvent evt
Definition: DataStructs.cxx:8
template<typename T , typename U , typename D >
bool util::CreateAssnD ( art::Event &  evt,
art::Assns< T, U, D > &  assn,
size_t  first_index,
size_t  second_index,
typename art::Assns< T, U, D >::data_t const &  data 
)

Definition at line 833 of file lardata/lardata/Utilities/AssociationUtil.h.

839  {
840 
841  try{
842  // we declare here that we want to associate the element first_index of the
843  // (only) data product of type std::vector<T> with the other object
844  auto const first_ptr = art::PtrMaker<T>{evt}(first_index);
845 
846  // the same to associate the element second_index of the (only)
847  // data product of type std::vector<U> with the first object.
848  auto const second_ptr = art::PtrMaker<U>{evt}(second_index);
849 
850  assn.addSingle(first_ptr, second_ptr, data);
851  }
852  catch(cet::exception &e){
853  mf::LogWarning("AssociationUtil")
854  << "unable to create requested art:Assns, exception thrown: " << e;
855  return false;
856  }
857 
858  return true;
859 } // util::CreateAssnD() [01b]
do i e
TCEvent evt
Definition: DataStructs.cxx:8
template<typename Producer , typename... Args>
std::enable_if_t<std::is_base_of_v<art::EDProducer, Producer>, bool> util::CreateAssnD ( Producer const &  ,
Args &&...  args 
)

Definition at line 979 of file lardata/lardata/Utilities/AssociationUtil.h.

979  {
980  return CreateAssnD(std::forward<Args>(args)...);
981  }
bool CreateAssnD(art::Event &evt, art::Assns< T, U, D > &assn, size_t first_index, size_t second_index, typename art::Assns< T, U, D >::data_t &&data)
Creates a single one-to-one association with associated data.
template<class T >
T util::cube ( x)
inline

More efficient cube function than pow(x,3)

Definition at line 26 of file MathUtil.h.

26 {return x*x*x;}
process_name opflash particleana ie x
template<typename T >
constexpr T util::DegreesToRadians ( angle)
inline

Converts the argument angle from degrees into radians.

Definition at line 84 of file PhysicalConstants.h.

84 { return angle / 180 * pi<T>(); }
finds tracks best matching by angle
decltype(auto) util::dereference ( )

Returns a functor that returns *ptr of its argument ptr.

See Also
util::Dereferencer

Example:

std::vector<int> values(ptrs.size());
(ptrs.cbegin(), ptrs.cend(), values.begin(), util::dereference());

will fill the vector values with the values pointed by the elements in ptrs.

Definition at line 125 of file operations.h.

125 { return Dereferencer(); }
def util.draw_iclabel ( )

Definition at line 305 of file util.py.

306 def draw_iclabel():
307  exp = ROOT.TLatex(0.22,0.91,"ICARUS Sample")
308  exp.SetNDC()
309  exp.SetTextSize(18)
310  exp.SetTextAlign(12)
311  exp.Draw()
def draw_iclabel
Definition: util.py:305
def util.draw_potlabel ( )

Definition at line 290 of file util.py.

291 def draw_potlabel():
292  pot = ROOT.TLatex(0.925,0.88,"1x10^{20} POT normalized")
293  pot.SetNDC()
294  pot.SetTextSize(18)
295  pot.SetTextAlign(32)
296  pot.Draw()
def draw_potlabel
Definition: util.py:290
def util.draw_sbndlabel ( )

Definition at line 312 of file util.py.

313 def draw_sbndlabel():
314  exp = ROOT.TLatex(0.22,0.91,"SBND Sample")
315  exp.SetNDC()
316  exp.SetTextSize(18)
317  exp.SetTextAlign(12)
318  exp.Draw()
def draw_sbndlabel
Definition: util.py:312
def util.draw_sbnlabel ( )

Definition at line 297 of file util.py.

298 def draw_sbnlabel():
299  sbn = ROOT.TLatex(.95, .92, "SBN Simulation")
300  sbn.SetTextColor(kGray+1)
301  sbn.SetNDC()
302  sbn.SetTextSize(20)
303  sbn.SetTextAlign(32)
304  sbn.Draw()
def draw_sbnlabel
Definition: util.py:297
def util.draw_text (   args)

Definition at line 62 of file util.py.

62 
63 def draw_text(args):
64  textbox = None
65  if args.text:
66  textbox = ROOT.TPaveText(*[float(x) for x in args.text_position])
67  textbox.SetOption("NDC")
68  for text in args.text:
69  textbox.AddText(text)
70  textbox.SetMargin(0)
71  textbox.SetBorderSize(0)
72  textbox.SetTextFont(args.text_font)
73  textbox.SetTextSize(args.text_size)
74  textbox.SetTextColor(args.text_color)
75  textbox.SetFillStyle(0)
76  textbox.Draw()
77  return textbox
78 
def draw_text
Definition: util.py:62
template<typename Stream , typename Left , typename Right , typename Data >
void util::DumpAssociationsIntro ( Stream &&  out,
art::Assns< Left, Right, Data > const &  assns 
)

Dumps a short introduction about specified association.

Template Parameters
Streamtype of output stream
Leftfirst type in the association
Rightsecond type in the association
Datametadata type in the association
Parameters
outoutput stream
assnsthe associations to be dumped

Definition at line 33 of file DumpAssociations.h.

34  {
35  out << "Association between '" << cet::demangle_symbol(typeid(Left).name())
36  << "' and '" << cet::demangle_symbol(typeid(Right).name()) << "'";
37  if (std::is_same<Data, void>()) {
38  out << " with '" << cet::demangle_symbol(typeid(Data).name())
39  << "' metadata";
40  }
41  if (assns.size() > 0) {
42  out << " contains " << assns.size() << " relations";
43  }
44  else {
45  out << " is empty";
46  }
47  } // DumpAssociationsIntro<Data>()
then echo fcl name
double util::ECCQE ( const TVector3 &  l_momentum,
double  l_energy 
)

Calculate CCQE energy from associated lepton information.

Parameters
l_momentumLepton momentum (any units, used only to get angle info)
l_energyLepton energy in GeV
Returns
CCQE energy in GeV.

Definition at line 7 of file Interaction.cxx.

7  {
8  // Based on D. Kaleko, LowEnergyExcess LArLite module ECCQECalculator
9  double M_n = 0.939565; // GeV/c^2
10  double M_p = 0.938272; // GeV/c^2
11  double M_e = 0.000511; // GeV/c^2
12  double bindingE = 0.0300; // GeV
13 
14  double mp2 = M_p * M_p;
15  double me2 = M_e * M_e;
16  double mnb = M_n - bindingE;
17 
18  TVector3 v(l_momentum);
19  double l_mom = sqrt(l_energy * l_energy - me2);
20  double l_theta = \
21  acos(v.Pz() / sqrt(v.Px()*v.Px() + v.Py()*v.Py() + v.Pz()*v.Pz()));
22  double enu_top = mp2 - mnb*mnb - me2 + 2.0 * mnb * l_energy;
23  double enu_bot = 2.0 * (mnb - l_energy + l_mom * cos(l_theta));
24 
25  return enu_top / enu_bot;
26 }
template<std::size_t Lead, typename... Iterables>
auto util::enumerate ( Iterables &&...  iterables)

Range-for loop helper tracking the number of iteration.

Template Parameters
Leadindex of the parameter driving the start and end of the loop
Iterablestype of objects to be iterated together
Parameters
iterablesall iterable objects to be iterated together
Returns
an object suitable for range-for loop

In the range-for loop, at each iteration this object yields a tuple of values, each of the type returned by dereferencing begin(iterable). For example:

constexpr std::size_t N = 4;
std::array<int, N> twice;
std::vector<double> thrice(N + 1);
for (auto&& [i, a, b]: util::enumerate(twice, thrice)) {
a = 2 * i;
b = 3.0 * i;
} // for

In this example, N iterations will be run because that is the size of the first iterable given to enumerate. If a different leading iterable is needed, that has to be specified as an argument. The following loop is completely equivalent to the former one:

for (auto&& [i, b, a]: util::enumerate<1U>(thrice, twice)) {
a = 2 * i;
b = 3.0 * i;
} // for

(the index is zero-based, so 1U refers to the second argument).

Definition at line 69 of file enumerate.h.

70  {
71  return zip<Lead + 1>
72  (infinite_counter(), std::forward<Iterables>(iterables)...);
73  }
auto infinite_counter(T begin=T{})
Version of util::counter() starting at begin and never ending.
Definition: counter.h:291
template<typename... Iterables>
auto util::enumerate ( Iterables &&...  iterables)

This version of enumerate implicitly uses the first iterable as lead.

Definition at line 77 of file enumerate.h.

78  { return enumerate<0U>(std::forward<Iterables>(iterables)...); }
def util.filespec (   inp)

Definition at line 40 of file util.py.

40 
41 def filespec(inp):
42  split = inp.split(":")
43  if len(split) == 1:
44  return ("input", ROOT.TFile(split[0]))
45  else:
46  return (split[0], ROOT.TFile(split[1]))
def filespec
Definition: util.py:40
def util.fillcolors (   index)

Definition at line 272 of file util.py.

273 def fillcolors(index):
274  colors = [ROOT.kRed, ROOT.kGreen]
275  return colors[index]
def fillcolors
Definition: util.py:272
template<typename Range , typename Pred >
auto util::filterRangeFor ( Range &&  range,
Pred &&  pred 
) -> decltype(auto)

Provides iteration only through elements passing a condition.

Template Parameters
Rangethe data to be iterated
Predthe type of the predicate to be fulfilled
Parameters
rangethe data to be iterated through
predthe predicate to be tested
Returns
an object suitable to be used in a range-for loop

This adapter makes the range for loop iterate only through the elements of range which fulfil the predicate pred.

This example will print: "0 3 6 9 ":

std::vector<int> data = { 0, 1, 2, 3, 4, 5, 6 ,7, 8, 9 };
for (int v: util::filterRangeFor(data, [](int v){ return v % 3 == 0; })) {
std::cout << v << " ";
} // for
std::cout << std::endl;

Note that pred may be copied (range will not be).

Requirements

Definition at line 137 of file filterRangeFor.h.

138  {
139  return details::FilterRangeForStruct<Range, Pred>
140  (std::forward<Range>(range), std::forward<Pred>(pred));
141  }
template<typename Iter , typename SideFunc >
std::pair< Iter, Iter > util::findCrossingSegment ( Iter  begin,
Iter  end,
SideFunc  sideOf 
)

Returns a path segment with ends on different sides than path ends.

Template Parameters
Itertype of iterator to the points in the path
SideFunctype of functor returning the side of a point
Parameters
beginiterator to the first point of the path
enditerator past the last point of the path
sideOffunctor returning the side of the point in argument
Returns
a pair of iterators pointing to the points found, { end, end } if the path does not change side at all

The path is defined as a sequence of positions of arbitrary types. The functor sideOf takes as argument one such position, and returns an also arbitrary value representing the side of that position. This algorithm returns a pair with the first point where the side changes, and the point after the last side change. The two points match only if there is no side change at all (in which case a pair with two end iterators is returned). The two returned iterators are adjacent only if there is only one change of side.

Note that this algorithm is effectively not specific to a space path but it's rather a generic classification algorithm: given an ordered sequence, it finds the first and the last change of class.

Requirements

Definition at line 455 of file TrajectoryUtils.h.

456 {
457 
458  // find the place from start where the side first changes
459  Iter itStart = begin;
460  auto const startSide = sideOf(*itStart);
461  while (++itStart != end) {
462  if (sideOf(*itStart) != startSide) break; // changed side
463  }
464 
465  if (itStart == end) return { end, end }; // path is not crossing side at all
466  --itStart; // let have itStart point to the last point on the original side
467 
468  // find the place from end where the side last changes
469  // (if it starts from the same side as the other end, it's weird but we
470  // pretend nothing happened)
471  Iter itEnd = std::prev(end);
472  auto const endSide = sideOf(*itEnd);
473  while (--itEnd != itStart) {
474  if (sideOf(*itEnd) != endSide) break; // changed side
475  }
476  ++itEnd; // ... and itEnd points to the last point on the end original side
477 
478  return { itStart, itEnd };
479 
480 } // util::findCrossingSegment()
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename FIter , typename LIter >
PathPointInfo_t<FIter> util::findMiddlePointInPath ( FIter  itFirst,
LIter  itLast,
double  relTarget = 0.5 
)

Returns information to identify the middle of the specified path.

Template Parameters
FItertype of iterator to a point in the path
LItertype of iterator to a point in the path
Parameters
itFirstiterator to the first point in the path
itLastiterator to the last point in the path (must be valid point)
relTarget(default: 0.5) fraction of the total length to pursue
Returns
information to identify the desired point

The sequence between the iterators itFirst and itLast, both included, defines a path. This function returns the point that cuts that path into two subpaths of the same length. The point usually does not match any of the points in the sequence, but rather is in between two of them.

The path is considered a sequence of straight segments connecting the points.

Example of use with a LArSoft recob::Track object (track):

auto const& path = track.Trajectory().Positions();
geo::Point_t const middle
= util::PathMiddlePoint(path.begin(), std::prev(path.end()));

(note that here the function actually returns a recob::tracking::Point_t).

Requirements

The FIter type is a forward iterator, the type LIter is a backward iterator.

The type Point must satisfy the following operations.

LArSoft geo::Point_t type is known to satisfy the requirements of Point (geo::Vector_t being its corresponding Vector type). The modulus function geo::vect::norm() is provided for geo::Vector_t in the LArSoft header larcorealg/CoreUtils/geo_vector_utils.h.

template<class T , class U >
static std::vector<const U*> util::FindUNotAssociatedToT ( art::Handle< U >  b,
art::Event const &  evt,
std::string const &  label 
)
static

Return all objects of type U that are not associated to objects of type T.

Label is the module label that would have produced the associations and likely the objects of type T this method assumes there is a one to many relationship between T and U for example if you want to get all rb::CellHits that are not associated to rb::Clusters std::vector<const rb::CellHit*> hits = FindUNotAssociatedToU<rb::Cluster>(art::Handle<rb::CellHit>, ...);

template<class T , class U >
std::vector< const U * > util::FindUNotAssociatedToT ( art::Handle< U >  b,
art::Event const &  evt,
std::string const &  label 
)
inline

Definition at line 864 of file lardata/lardata/Utilities/AssociationUtil.h.

867 {
868  // Do a FindOne for type T for each object of type U
869  // If the FindOne returns an invalid maybe ref, add the pointer
870  // of object type U to the return vector
871 
872  std::vector<const U*> notAssociated;
873 
874  art::FindOne<T> const fa(b, evt, label);
875 
876  for(size_t u = 0; u < b->size(); ++u){
877  cet::maybe_ref<T const> t(fa.at(u));
878  if( !t.isValid() ){
879  art::Ptr<U> ptr(b, u);
880  notAssociated.push_back(ptr.get());
881  }
882  }
883 
884  return notAssociated;
885 }
TCEvent evt
Definition: DataStructs.cxx:8
template<class T , class U >
static std::vector< art::Ptr<U> > util::FindUNotAssociatedToTP ( art::Handle< U >  b,
art::Event const &  evt,
std::string const &  label 
)
static

Return all objects of type U that are not associated to objects of type T.

Label is the module label that would have produced the associations and likely the objects of type T this method assumes there is a one to many relationship between T and U for example if you want to get all rb::CellHits that are not associated to rb::Clusters std::vector<art::Ptr<rb::CellHit> > hits = FindUNotAssociatedToTP<rb::Cluster>(art::Handle<rb::CellHit>, ...);

template<class T , class U >
std::vector< art::Ptr< U > > util::FindUNotAssociatedToTP ( art::Handle< U >  b,
art::Event const &  evt,
std::string const &  label 
)
inline

Definition at line 890 of file lardata/lardata/Utilities/AssociationUtil.h.

893 {
894  // Do a FindOneP for type T for each object of type U
895  // If the FindOne returns an invalid maybe ref, add the pointer
896  // of object type U to the return vector
897 
898  std::vector< art::Ptr<U> > notAssociated;
899 
900  art::FindOneP<T> const fa(b, evt, label);
901 
902  for(size_t u = 0; u < b->size(); ++u){
903  cet::maybe_ref<T const> t(fa.at(u));
904  if( !t.isValid() ){
905  notAssociated.emplace_back(b, u);
906  }
907  }
908 
909  return notAssociated;
910 }
TCEvent evt
Definition: DataStructs.cxx:8
template<class A , class F >
void util::for_each_associated_group ( A const &  assns,
F func 
)

Helper functions to access associations in order.

Template Parameters
Atype of association being read
Ftype of functor to be called on each associated group
Parameters
assnsthe association being read
funcfunctor to be called on each associated group
See Also
associated_groups() art::for_each_group()
Deprecated:
Moved into canvas: art::for_each_group().

Definition at line 49 of file ForEachAssociatedGroup.h.

50  { art::for_each_group(assns, func); }
template<std::size_t... Indices, typename Coll >
decltype(auto) util::get_const_elements ( Coll &&  coll)

Range-for loop helper iterating across the constant values of the specified collection.

See Also
util::values()

This function is equivalent to util::values() but the values are extracted as if the specified collection were constant.

template<std::size_t... Indices, typename Coll >
decltype(auto) util::get_elements ( Coll &&  coll)

Range-for loop helper iterating across some of the element of each value in the specified collection.

Template Parameters
Indicesindices of the elements to extract
Colltype of the collection to iterate through
Parameters
collthe collection to iterate through
Returns
an object suitable for range-for loop
See Also
util::get_const_elements()

This function enables range-for loops with a selection of elements from a container of tuple (or anything responding to util::get()).

The following example fills a map using as key the first element (0U) of a tuple and as value the third element (2U):

std::vector<std::tuple<char, int, float>> data
{ { 'z', 0, 1.0F }, { 'o', 1, 3.0F }, { 't', 2, 9.0F } };
std::map<char, double> factors;
for (auto const& [ letter, factor ]: util::get_elements<0U, 2U>(data)) {
factors.emplace(letter, factor);
}

If only one index is specified, the loop will not use structured binding, but rather a simple variable:

std::vector<int> exponents;
for (int exponent: util::get_elements<1U>(data)) {
exponents.push_back(exponent);
}

While the examples do not demonstrate changing the values in the data collection, that is also supported.

Note
This function also works with associative containers based on std::pair (std::map and the likes).
def util.get_tobject (   args,
  name 
)

Definition at line 47 of file util.py.

47 
48 def get_tobject(args, name):
49  if ":" in name:
50  fname = name.split(":")[0]
51  else:
52  fname = "input"
53  return getattr(args, fname).Get(name.split(":")[-1])
def get_tobject
Definition: util.py:47
template<class T , class U >
std::vector< std::vector< size_t > > util::GetAssociatedVectorManyI ( art::Handle< art::Assns< T, U > >  h,
art::Handle< std::vector< T > >  index_p 
)
inline

Definition at line 938 of file lardata/lardata/Utilities/AssociationUtil.h.

940 {
941  std::vector< std::vector<size_t> > associated_indices(index_p->size());
942  for(auto const& pair : *h)
943  associated_indices.at(pair.first.key()).push_back(pair.second.key());
944  return associated_indices;
945 }
while getopts h
template<class T , class U >
std::vector< std::vector< const U * > > util::GetAssociatedVectorManyP ( art::Handle< art::Assns< T, U > >  h,
art::Handle< std::vector< T > >  index_p 
)
inline

Definition at line 949 of file lardata/lardata/Utilities/AssociationUtil.h.

951 {
952  std::vector< std::vector<const U*> > associated_pointers(index_p->size());
953  for(auto const& pair : *h)
954  associated_pointers.at(pair.first.key()).push_back( &(*(pair.second)) );
955  return associated_pointers;
956 }
while getopts h
template<class T , class U >
std::vector< size_t > util::GetAssociatedVectorOneI ( art::Handle< art::Assns< T, U > >  h,
art::Handle< std::vector< T > >  index_p 
)
inline

Definition at line 916 of file lardata/lardata/Utilities/AssociationUtil.h.

918 {
919  std::vector<size_t> associated_index(index_p->size());
920  for(auto const& pair : *h)
921  associated_index.at(pair.first.key()) = pair.second.key();
922  return associated_index;
923 }
while getopts h
template<class T , class U >
std::vector< const U * > util::GetAssociatedVectorOneP ( art::Handle< art::Assns< T, U > >  h,
art::Handle< std::vector< T > >  index_p 
)
inline

Definition at line 927 of file lardata/lardata/Utilities/AssociationUtil.h.

929 {
930  std::vector<const U*> associated_pointer(index_p->size());
931  for(auto const& pair : *h)
932  associated_pointer.at(pair.first.key()) = &(*(pair.second));
933  return associated_pointer;
934 }
while getopts h
template<typename Groups >
auto util::groupByIndex ( Groups &&  groups,
std::size_t  index 
) -> decltype(auto)

Returns the group within groups with the specified index.

Template Parameters
Groupsthe type of collection of groups
Parameters
groupsthe collection of all groups
indexthe index of the group to be accessed
Returns
the group with specified index (may be a reference)
See Also
associated_groups()

The groups argument is expected to be the one returned by associated_groups.

Definition at line 180 of file ForEachAssociatedGroup.h.

181  { return *(std::next(groups.begin(), index)); }
def util.histo_list (   inp)

Definition at line 331 of file util.py.

332 def histo_list(inp):
333  inp = inp.split(",")
334  in_parens = False
335  out = []
336  for name in inp:
337  if name.startswith("("):
338  assert(not in_parens)
339  in_parens = True
340  name = name.lstrip("(")
341  out.append([name])
342  elif name.endswith(")"):
343  assert(in_parens)
344  in_parens = False
345  name = name.rstrip(")")
346  out[-1].append(name)
347  elif in_parens:
348  out[-1].append(name)
349  else:
350  out.append([name])
351  return out
def histo_list
Definition: util.py:331
template<typename T = std::size_t>
auto util::infinite_counter ( begin = T{})

Version of util::counter() starting at begin and never ending.

Template Parameters
Ttype of counter value
Parameters
beginthe count to start from (default-constructed, usually some form of 0, by default)
Returns
a control object for range-for loop

An example of usage:

std::vector<unsigned char> data;
for (auto ch: util::infinite_counter<unsigned char>()) {
if (data.size() >= 512U) break;
data.push_back(ch);
}

This loop runs through the full range of a character (8 bits, supposedly) twice before being broken.

Definition at line 291 of file counter.h.

292 {
293  return util::span
294  (count_iterator(begin), details::infinite_endcount_iterator<T>());
295 } // util::infinite_counter()
Simple class with a begin and an end.
Definition: span.h:125
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename Event >
art::InputTag util::inputTagOf ( Event const &  event,
art::ProductID const &  productID 
)

Reads and returns the input tag of the producer of productID.

Template Parameters
Eventtype of event to read data from (art::Event interface)
Parameters
eventevent to read data products from
productIDreference data product
Returns
the input tag of the producer of productID
Exceptions
art::Exception(error code: art::errors::ProductNotFound) if no input tag could be found

This utility facilitates the traversal of associations. Assuming that a pointer to a data product element is available, we may need to read another data product from the same producer (e.g. from a pointer to a recob::Track from a collection, we want to learn the associations of that track to recob::Hit, assuming that the same module that produced the tracks also produced their associations to hit). This is trivial if the input tag of the data product element is known, but it's not if that data product is instead known only by a pointer/association. In that case, this function discovers the needed input tag. Example:

auto const& assns
= event.getProduct<std::vector<recob::Hit>>(inputTagOf(trackPtr.id()));

where trackPtr is a art::Ptr<recob::Track> that may come for example from a recob::PFParticle/recob::Track association.

Definition at line 108 of file CanvasUtils.h.

109 {
110 
111  cet::exempt_ptr<art::BranchDescription const> metaDescr
112  = event.getProductDescription(productID);
113  if (metaDescr) return metaDescr->inputTag();
114 
115  throw art::Exception(art::errors::ProductNotFound)
116  << "Branch (and input tag) not found for product ID " << productID;
117 
118 } // util::inputTagOf()
template<typename Event , typename Handle >
std::enable_if_t< std::is_void_v<std::void_t<typename Handle::HandleTag> >, art::InputTag > util::inputTagOf ( Event const &  event,
Handle const &  handle 
)

Reads and returns the input tag of the product with the specified handle.

Template Parameters
Eventtype of event to read data from (art::Event interface)
Handletype of handle
Parameters
eventevent to read data products from
handledata product handle
Returns
the input tag of the producer of data product at handle
Exceptions
art::Exception(error code: art::errors::ProductNotFound) if no input tag could be found
See Also
inputTag(Event const&, art::ProductID const&)

This utility is a wrapper of the version working on product ID.

Definition at line 75 of file CanvasUtils.h.

76  { return inputTagOf(event, handle.id()); }
art::InputTag inputTagOf(Event const &event, art::ProductID const &productID)
Reads and returns the input tag of the producer of productID.
Definition: CanvasUtils.h:108
template<typename Event , typename T >
art::InputTag util::inputTagOf ( Event const &  event,
art::Ptr< T > const &  ptr 
)

Reads and returns the input tag of the product ptr points to.

Template Parameters
Eventtype of event to read data from (art::Event interface)
Ttype of the datum pointed by the pointer
Parameters
eventevent to read data products from
ptrart pointer to the data product element
Returns
the input tag of the producer of data product of ptr
Exceptions
art::Exception(error code: art::errors::ProductNotFound) if no input tag could be found
See Also
inputTag(Event const&, art::ProductID const&)

This utility is a wrapper of the version working on product ID.

Definition at line 93 of file CanvasUtils.h.

94  { return inputTagOf(event, ptr.id()); }
art::InputTag inputTagOf(Event const &event, art::ProductID const &productID)
Reads and returns the input tag of the producer of productID.
Definition: CanvasUtils.h:108
def util.int_pair (   inp)

Definition at line 217 of file util.py.

218 def int_pair(inp):
219  return [int(i) for i in inp.split(",")][:2]
def int_pair
Definition: util.py:217
template<class T >
T util::ipow ( x,
unsigned int  n 
)
inline

More efficient exponentiation function than pow(x,n) for small n.

Definition at line 29 of file MathUtil.h.

30  {
31  T ret = 1;
32  if (n == 0) return ret;
33  for(unsigned int i = 1; i <= n; ++i) ret *= x;
34  return ret;
35  }
process_name opflash particleana ie x
def util.legend_position (   inp)

Definition at line 319 of file util.py.

320 def legend_position(inp):
321  if inp == "ur":
322  return [0.75,0.75,0.95,0.95]
323  elif inp == "ul":
324  return [0.35,0.75,0.15,0.95]
325  elif inp == "um":
326  return [0.4, 0.69, 0.6, 0.89]
327  elif inp == "lr":
328  return [0.75,0.15,0.95,0.35]
329  else:
330  return [float(x) for x in inp.split(",")][:4]
def legend_position
Definition: util.py:319
template<typename Cont , typename Adaptor >
auto util::make_adapted_const_span ( Cont &  cont,
Adaptor &&  adaptor 
)

Creates constant iteration span from specified collection via an adaptor.

Definition at line 269 of file span.h.

270  {
271  return make_adapted_span(
272  span_base::get_cbegin(cont), span_base::get_cend(cont),
273  std::forward<Adaptor>(adaptor)
274  );
275  }
auto make_adapted_span(BIter begin, EIter end, Adaptor &&adaptor)
Definition: span.h:223
template<typename BIter , typename EIter , typename Adaptor >
auto util::make_adapted_span ( BIter  begin,
EIter  end,
Adaptor &&  adaptor 
)

Creates a span from specified iterators via an adaptor.

See Also
make_adapted_span(Cont&, Adaptor&&)

Definition at line 223 of file span.h.

224  { return util::span(adaptor(begin), adaptor(end)); }
Simple class with a begin and an end.
Definition: span.h:125
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename Cont , typename Adaptor >
auto util::make_adapted_span ( Cont &  cont,
Adaptor &&  adaptor 
)

Creates a span from specified collection via an adaptor.

Parameters
contcollection to be iterated through
adapteriterator transformation to be applied on cont
Returns
a util::span object iterating via an adapter to cont
See Also
make_adapted_span(BIter, EIter, Adaptor&&), make_adapted_const_span(Cont, Adaptor&&)

This interface is just a little help on using iterator adapters. Note that adapter transforms the iterators of cont, not its values. The adapter needs to be written aside and it's in general not trivial. An example of iterating through a collection of objects (actually, just float for simplicity) stored as unique pointers in a collection:

float accumulate(std::vector<std::unique_ptr<float>> const& v) {
using src_iterator = std::vector<std::unique_ptr<float>>::const_iterator;
float sum = 0.0F;
for (float v: util::make_adapted_span(v, boost::make_indirect_iterator<src_iterator>))
sum += v;
return sum;
} // accumulate()

This example shows the usage of util::make_adapted_span(). In the specific example, it would have been more explicit to use the constant counterpart, util::make_adapted_const_span(). The adaptor helper boost::make_indirect_iterator() is provided in boost/iterator/indirect_iterator.hpp.

Definition at line 258 of file span.h.

259  {
260  return make_adapted_span(
261  span_base::get_begin(cont), span_base::get_end(cont),
262  std::forward<Adaptor>(adaptor)
263  );
264  }
auto make_adapted_span(BIter begin, EIter end, Adaptor &&adaptor)
Definition: span.h:223
template<typename Cont >
auto util::make_const_span ( Cont &  cont)

Creates a span with constant iterator access from a container type.

Definition at line 206 of file span.h.

207  {
208  return span{ span_base::get_cbegin(cont), span_base::get_cend(cont) };
209  }
template<typename BIter , typename EIter >
auto util::make_span ( BIter  begin,
EIter  end 
)

Creates a span from specified iterators (can use constructor instead).

Definition at line 197 of file span.h.

197 { return util::span(begin, end); }
Simple class with a begin and an end.
Definition: span.h:125
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename Cont >
auto util::make_span ( Cont &  cont)

Creates a span from a container type.

Definition at line 201 of file span.h.

202  { return span{ span_base::get_begin(cont), span_base::get_end(cont) }; }
template<typename Cont , typename Op >
auto util::make_transformed_const_span ( Cont &  cont,
Op &&  op 
)

Creates constant iteration span from specified collection via a transformation op.

Definition at line 353 of file span.h.

354  { return make_transformed_span(std::as_const(cont), std::forward<Op>(op)); }
auto make_transformed_span(BIter begin, EIter end, Op &&op)
Definition: span.h:294
template<typename BIter , typename EIter , typename Op >
auto util::make_transformed_span ( BIter  begin,
EIter  end,
Op &&  op 
)

Creates a span from specified iterators via an adaptor.

See Also
make_transformed_span(Cont&, Op&&)

Definition at line 294 of file span.h.

295  {
296  auto adaptor
297  = [&op](auto iter){ return boost::make_transform_iterator(iter, op); };
298  return util::make_adapted_span(begin, end, adaptor);
299  }
auto make_adapted_span(BIter begin, EIter end, Adaptor &&adaptor)
Definition: span.h:223
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename Cont , typename Op >
auto util::make_transformed_span ( Cont &  cont,
Op &&  op 
)

Creates a span from specified collection via an adaptor.

Parameters
contcollection to be iterated through
adapteriterator transformation to be applied on cont
Returns
a util::span object iterating via an adapter to cont
See Also
make_transformed_span(BIter, EIter, Op&&), make_transformed_const_span(Cont, Op&&), make_adapted_span(),

This function transforms as directed by the unary operation op the result of each iteration cycle, so that instead of cont[i], a op(cont[i]) is assigned to the iteration control variable. An example of iterating through a collection of objects (actually, just float for simplicity) stored as unique pointers in a collection:

float accumulate(std::vector<std::unique_ptr<float>> const& v) {
float sum = 0.0F;
for (float v: util::make_transformed_span(v, [](auto& ptr){ return *ptr; }))
sum += v;
return sum;
} // accumulate()

This example shows the usage of util::make_transformed_span(). In the specific example, it would have been more explicit to use the constant counterpart, util::make_transformed_const_span(). Note that in the example the dereference result is copied into v. For have it by reference, the operation op must be properly written:

void scale(std::vector<std::unique_ptr<float>>& v, float factor) {
for (float& v: util::make_transformed_span(v, [](auto& ptr) -> float& { return *ptr; }))
v *= factor;
} // scale()

Definition at line 341 of file span.h.

342  {
343  return make_transformed_span(
344  span_base::get_begin(cont), span_base::get_end(cont),
345  std::forward<Op>(op)
346  );
347  }
auto make_transformed_span(BIter begin, EIter end, Op &&op)
Definition: span.h:294
template<typename Stream >
auto util::makeIndented ( Stream &&  out,
std::string  indent,
std::string  firstIndent 
)

Creates an indented stream wrapper.

Template Parameters
Streamthe type of stream being wrapped
Parameters
outthe stream to wrap
indentstring inserted at the beginning of each new line
firstIndentstring inserted at the beginning of the first line
Returns
an indented stream wrapper
See Also
addIndent()

The use of the wrapper stream is explained in addIndent().

This function wraps a stream out, stealing it if it's a temporary, and returns the wrapping object. This object can be used for indented output to out until it is destroyed (if out is referenced as opposed to stolen, out itself needs to stay valid).

If not specified, firstIndent is assigned to be the same as indent.

The equivalent two-line example of addIndent() becomes:

auto out = util::makeIndented(std::cout, "> ", "$ ");
out << "First line: indented with '$ '."
<< "\nSecond line: indented with '> '."
;

Definition at line 176 of file StreamIndenter.h.

177 {
178  return details::IndentAdder
179  { std::forward<Stream>(out), std::move(indent), std::move(firstIndent) };
180 }
template<typename Stream >
auto util::makeIndented ( Stream &&  out,
std::string const &  indent 
)

Definition at line 185 of file StreamIndenter.h.

186  { return makeIndented(out, indent, indent); }
auto makeIndented(Stream &&out, std::string indent, std::string firstIndent)
Creates an indented stream wrapper.
template<typename Coll , typename KeyOf >
std::vector<size_t> util::MakeIndex ( Coll const &  data,
KeyOf  key_of = KeyOf() 
)

Creates a map of indices from an existing collection.

Template Parameters
Colltype of the collection
KeyOftype of the extractor of the key
Parameters
datathe data collection
key_ofinstance of a functor extracting a key value from a datum
Returns
a vector with indices corresponding to the data keys

This function maps the index of the items in data to an integral key extracted from each item. For example, if the items are wires and the key_of function extracts their channel ID, the resulting vector will contain for each channel ID the index in data of the wire with that channel ID.

The key is converted into a unsigned integer (size_t). If multiple items have the same key, the outcome for that key is undefined. If no items has a specific key, the index of that key is assigned as

std::numeric_limits<size_t>::max()

, i.e. an index larger than the size of the original data collection.

The returned vector is big enough to accommodate indices corresponding to the keys of all the items in data. It may contain "holes" (that is, some keys that have no corresponding items have a

std::numeric_limits<size_t>::max()

value). The memory allocated for the vector may be larger than necessary (if that is a problem, std::vector::shrink_to_fit() can be used, but it may create more problems than it solves).

Definition at line 43 of file MakeIndex.h.

43  {
44 
45  // we start the index with the best guess that all the items will have
46  // a unique key and they are contiguous:
47  // the index would have the same size as the data
48  std::vector<size_t> Index(data.size(), std::numeric_limits<size_t>::max());
49 
50  size_t min_size = 0; // minimum size needed to hold all keys
51 
52  size_t iDatum = 0;
53  for (auto const& datum: data) {
54  size_t key = size_t(key_of(datum));
55  if (key >= min_size) min_size = key + 1;
56  if (Index.size() <= key) {
57  // make room for the entry: double the size
58  Index.resize(
59  std::max(key + 1, Index.size() * 2),
60  std::numeric_limits<size_t>::max()
61  );
62  } // if expand index
63  Index[key] = iDatum;
64  ++iDatum;
65  } // for datum
66  Index.resize(min_size);
67  return Index;
68  } // MakeIndex()
template<typename Coll , typename KeyOf >
auto util::MakeMap ( Coll const &  data,
KeyOf  key_of = KeyOf() 
) -> std::vector<decltype(key_of(*(data.begin()))) const*>

Creates a map of objects from an existing collection.

Template Parameters
Colltype of the collection
KeyOftype of the extractor of the key
Parameters
datathe data collection
key_ofinstance of a functor extracting a key value from a datum
Returns
a vector with pointers to data corresponding to their keys

This function maps the items in data to an integral key extracted from each of them. For example, if the items are wires and the key_of function extracts their channel ID, the resulting vector will contain for each channel ID the pointer to the wire with that channel ID.

The key is converted into a unsigned integer (size_t). If multiple items have the same key, the outcome for that key is undefined. If no items has a specific key, the index of that key is assigned a null pointer.

The returned vector is big enough to accommodate pointers corresponding to the keys of all the items in data. It may contain "holes" (that is, some keys that have no corresponding items have a null pointer value). The memory allocated for the vector may be larger than necessary (if that is a problem, std::vector::shrink_to_fit() can be used, but it may create more problems than it solves).

Definition at line 99 of file MakeIndex.h.

101  {
102  using Mapped_t = decltype(key_of(*(data.begin())));
103  using Ptr_t = Mapped_t const*;
104  using Map_t = std::vector<Ptr_t>;
105 
106  // we start the index with the best guess that all the items will have
107  // a unique key and they are contiguous:
108  // the index would have the same size as the data
109  Map_t Index(data.size(), nullptr);
110 
111  size_t min_size = 0; // minimum size needed to hold all keys
112 
113  for (auto const& datum: data) {
114  size_t key = size_t(key_of(datum));
115  if (key >= min_size) min_size = key + 1;
116  if (Index.size() <= key) {
117  // make room for the entry: double the size
118  Index.resize(std::max(key + 1, Index.size() * 2), nullptr);
119  } // if expand index
120  Index[key] = &datum;
121  } // for datum
122  Index.resize(min_size);
123  return Index;
124  } // MakeMap()
template<typename Coll >
auto util::makePointerVector ( Coll &  coll)

Creates a STL vector with pointers to data from another collection.

Template Parameters
Colltype of collection of data
Parameters
colldata collection
Returns
a STL vector with pointers to coll data elements, with same order

Definition at line 198 of file SortByPointers.h.

199  { return details::PointerVectorMaker<Coll>::make(coll); }
template<typename... DIMS>
auto util::makeTensorIndices ( DIMS...  dims)

Instantiates a TensorIndices class with the specified dimensions.

Template Parameters
DIMStypes for each of the arguments
Parameters
dimssize of each of the dimensions
Returns
a TensorIndices object with properly initialised dimensions

The rank of the tensor is determined by the number of arguments; example:

will initialise a TensorIndices<2> (that's matrix indices), for a 3 x 4 (3 rows, 4 columns) disposition.

Definition at line 543 of file TensorIndices.h.

544  {
545  return TensorIndices<sizeof...(DIMS)>
546  { TensorIndicesBasicTypes::DimSize_t(dims)... };
547  }
template<typename Coll , typename Extractor >
decltype(auto) util::makeValueIndex ( Coll const &  coll,
Extractor  getter 
)

Returns a map of value to index.

Template Parameters
Colltype of container
Extractortype of value extraction function
Parameters
collcontainer to get the map of
getterfunction applied to each element to extract the value for map
Returns
a value-to-index associative container
Exceptions
std::runtime_errorif multiple elements yield the same value

The collection coll is navigated in sequence from begin() to end(), and a map is created where to each key, getter(coll[i]), the index i is associated. The value returned by getter() is copied into the key. Therefore that value needs to satisfy all the requirements of the key of the STL associative container std::map. Duplicate values will trigger an exception.

Requirements

The collection type Coll must have:

template<typename Coll >
auto util::makeValueIndex ( Coll const &  coll)

Definition at line 61 of file makeValueIndex.h.

62  { return makeValueIndex(coll, util::pre_std::identity()); }
Transparent functor that returns its argument just as passed.
decltype(auto) makeValueIndex(Coll const &coll, Extractor getter)
Returns a map of value to index.
template<typename Cont , typename Mapping >
auto util::mapContainer ( Cont  cont,
Mapping  mapping 
)

Returns a container-like object mapping the content of cont.

Template Parameters
Conttype of the original container
Mappingtype of mapping object
Parameters
contthe container
mappingthe mapping to be applied
Returns
a util::MappedContainer object transparently applying the mapping

See util::MappedContainer for the details on the format of the mapping, the ownership of the container and the supported operations.

Definition at line 441 of file MappedContainer.h.

442  { return MappedContainer<Cont, Mapping>(cont, mapping); }
template<typename Handle >
DataProductPointerMap_t<ArtHandleData_t<Handle> > util::mapDataProductPointers ( art::Event const &  event,
Handle const &  handle 
)

Creates a map from address of data product element to art pointer to it.

Template Parameters
Handletype of handle to data product (e.g. art::ValidHandle)
Parameters
handleart handle to the data product
eventthe art event the data product belongs to
Returns
a map from data product element pointer to art pointer

Returns a map from the address of any of the objects in the data product in event pointed by handle and the art pointer to those objects. Provided that the type in the data product is T, the returned map is an object guaranteed to have:

Example: with event a art::Event object and waveformHandle an handle to a std::vector<raw::OpDetWaveform> data product in event:

DataProductPointerMap_t<raw::OpDetWaveform> const& opDetWavePtrs
= util::mapDataProductPointers(event, waveformHandle);
for (raw::OpDetWaveform const& waveform: *waveformHandle) {
art::Ptr<raw::OpDetWaveform> const& ptr = opDetWavePtrs.at(&waveform);
// ...
} // for

in the loop the art::Ptr of each waveform is tracked without carrying around the index of the waveform in the original data product.

There are alternative approaches to this: one can rely on the contiguous memory model of std::vector and carry around the address of the first waveform, &(waveformHandle->front()), and a properly initialized art::PtrMaker which can then invoked as ptrMaker(&waveform - waveform0ptr); or work directly with art::Ptr. This approach is more factorised than the first alternative (knowledge of the event is not required any more during the iteration) and arguably faster than the second, where art pointer dereferencing always has a small overhead, but it uses more memory.

Note
The returned object is currently a C++ STL data container. Optimizations are possible using a different data structure (for example, a vector-based container with index based on the difference described in the example above) and they may in future be implemented. Because of this reason, it is recommended that the produced map is stored in variables declared with an auto const& type or as a DataProductPointerMap_t instance, rather than with the currently underlying data type.
double util::MCParticleContainedLength ( const simb::MCParticle &  particle,
const std::vector< geo::BoxBoundedGeo > &  active_volumes 
)

Calculated length of an MCParticle trajectory through a list of (non-overlapping) volumes.

Parameters
particleThe particle to calculate the length for
active_volumesA list of non-overlapping volumes through which the contained length will be calculated
Returns
The length of the MCParticle trajectory contained in the active_volumes. Returns 0 if the list of volumes is empty or the particle does not contain trajectory points.

Definition at line 77 of file Interaction.cxx.

77  {
78  double contained_length = 0;
79  bool outside_AV = true;
80  TVector3 start = particle.Position().Vect();
81 
82  // keep track of the containment position
83  int volume_index = -1;
84  // now check the active volumes
85  for (int i = 0; i < active_volumes.size(); i++) {
86  if (outside_AV && active_volumes[i].ContainsPosition(start)) {
87  outside_AV = false;
88  volume_index = i;
89  break;
90  }
91  }
92 
93  // if outside AV, set length to 0
94  if (outside_AV) return 0.;
95 
96  // keep track of the containment volume
97  std::vector<geo::BoxBoundedGeo> volume { active_volumes.at(volume_index) };
98 
99  TVector3 last = start;
100  for (int i = 1; i < particle.NumberTrajectoryPoints(); i++) {
101  TVector3 current = particle.Position(i).Vect();
102  if (!volume[0].ContainsPosition(current)) {
103  break;
104  }
105  contained_length += ContainedLength(last, current, volume);
106  last = current;
107  }
108 
109  return contained_length;
110 }
double ContainedLength(const TVector3 &v0, const TVector3 &v1, const std::vector< geo::BoxBoundedGeo > &boxes)
Definition: Interaction.cxx:28
double util::MCParticleLength ( const simb::MCParticle &  particle)

Calculate length of an MCParticle trajectory

Parameters
particlethe MCParticle
Returns
The length travelled by the particle. Returns 0 if the particle does not contain trajectory points.

Definition at line 65 of file Interaction.cxx.

65  {
66  double length = 0;
67  TVector3 last = particle.Position().Vect();
68  for (int i = 1; i < particle.NumberTrajectoryPoints(); i++) {
69  TVector3 current = particle.Position(i).Vect();
70  length += (current - last).Mag();
71  last = current;
72  }
73 
74  return length;
75 }
template<typename Coll , typename PtrColl >
void util::MoveFromPointers ( Coll &  dest,
PtrColl &  src 
)

Moves the content from a collection of pointers to one of data.

Template Parameters
Colltype of collection of data
PtrColltype of collection of pointers to data
Parameters
destcollection to be filled
srccollection with the pointers to data to be moved

The data pointed from each pointer in src is moved into dest. The destination collection is cleared first, and Coll must support both clear() and push_back()

Definition at line 61 of file SortByPointers.h.

62  { details::MoveFromPointersImpl<Coll, PtrColl>::move(dest, src); }
def util.namecolors (   name)

Definition at line 276 of file util.py.

277 def namecolors(name):
278  colors = {
279  "CC": ROOT.kPink+2,
280  "Cosmic": ROOT.kGray+1,
281  "Intime Cosmic": ROOT.kGray+1,
282  "Outtime Cosmic": ROOT.kGray+2,
283  "NC": ROOT.kAzure+3,
284  "Other": ROOT.kRed+2
285  }
286  return colors[name]
def namecolors
Definition: util.py:276
template<typename _Key , typename _Tp , typename _Compare >
bool util::operator!= ( const VectorMap< _Key, _Tp, _Compare > &  __x,
const VectorMap< _Key, _Tp, _Compare > &  __y 
)
inline

Based on operator==.

Definition at line 513 of file VectorMap.h.

515  {
516  return !(__x == __y);
517  }
template<unsigned int RANK1, unsigned int RANK2, typename = std::enable_if_t<(RANK1 != RANK2), bool>>
bool util::operator!= ( TensorIndices< RANK1 > const &  a,
TensorIndices< RANK2 > const &  b 
)

Comparison operator with tensors of different rank.

Definition at line 525 of file TensorIndices.h.

526  { return true; }
template<typename Cont , typename Mapping , typename Container , typename Reference >
MappedContainer<Cont, Mapping>::template IteratorBase<Container, Reference> util::operator+ ( typename MappedContainer< Cont, Mapping >::template IteratorBase< Container, Reference >::difference_type  n,
typename MappedContainer< Cont, Mapping >::template IteratorBase< Container, Reference > const &  it 
)

Definition at line 703 of file MappedContainer.h.

707  { return it + n; }
template<typename _Key , typename _Tp , typename _Compare >
bool util::operator< ( const VectorMap< _Key, _Tp, _Compare > &  __x,
const VectorMap< _Key, _Tp, _Compare > &  __y 
)
inline

Definition at line 501 of file VectorMap.h.

503  {
504  return std::lexicographical_compare(__x.sortedVectorMap.begin(),
505  __x.sortedVectorMap.end(),
506  __y.sortedVectorMap.begin(),
507  __y.sortedVectorMap.end(),
508  __x.valueCompare);
509  }
template<typename T >
std::ostream & util::operator<< ( std::ostream &  out,
Binner< T > const &  binner 
)

Definition at line 218 of file Binner.h.

218  {
219 
220  out << "[ " << binner.lower() << " -- " << binner.upper() << " ] ("
221  << binner.nBins() << "x " << binner.step() << ")";
222  return out;
223 
224 } // operator<< (Binner<>)
std::ostream& util::operator<< ( std::ostream &  out,
EventChangeTracker_t const &  trk 
)
inline

Definition at line 105 of file ChangeTrackers.h.

106  { out << std::string(trk); return out; }
template<typename Stream >
auto util::operator<< ( Stream &&  out,
addIndent &&  adder 
)

Helper function for addIndent (.

See Also
addIndent).

Definition at line 191 of file StreamIndenter.h.

191  {
192  return details::IndentAdder{
193  std::forward<Stream>(out),
194  std::move(adder.indent), std::move(adder.firstIndent)
195  };
196 } // operator<< (Stream, addIndent)
std::ostream& util::operator<< ( std::ostream &  out,
DataProductChangeTracker_t const &  trk 
)
inline

Definition at line 206 of file ChangeTrackers.h.

207  { out << std::string(trk); return out; }
std::ostream& util::operator<< ( std::ostream &  out,
PlaneDataChangeTracker_t const &  trk 
)
inline

Definition at line 319 of file ChangeTrackers.h.

320  { out << std::string(trk); return out; }
template<typename _Key , typename _Tp , typename _Compare >
bool util::operator<= ( const VectorMap< _Key, _Tp, _Compare > &  __x,
const VectorMap< _Key, _Tp, _Compare > &  __y 
)
inline

Based on operator<.

Definition at line 529 of file VectorMap.h.

531  {
532  return !(__y < __x);
533  }
template<typename _Key , typename _Tp , typename _Compare >
bool util::operator== ( const VectorMap< _Key, _Tp, _Compare > &  __x,
const VectorMap< _Key, _Tp, _Compare > &  __y 
)
inline

Definition at line 494 of file VectorMap.h.

496  {
497  return __x.sortedVectorMap == __y.sortedVectorMap;
498  }
template<unsigned int RANK1, unsigned int RANK2, typename = std::enable_if_t<(RANK1 != RANK2), bool>>
bool util::operator== ( TensorIndices< RANK1 > const &  a,
TensorIndices< RANK2 > const &  b 
)

Comparison operator with tensors of different rank.

Definition at line 517 of file TensorIndices.h.

518  { return false; }
template<typename _Key , typename _Tp , typename _Compare >
bool util::operator> ( const VectorMap< _Key, _Tp, _Compare > &  __x,
const VectorMap< _Key, _Tp, _Compare > &  __y 
)
inline

Based on operator<.

Definition at line 521 of file VectorMap.h.

523  {
524  return __y < __x;
525  }
template<typename _Key , typename _Tp , typename _Compare >
bool util::operator>= ( const VectorMap< _Key, _Tp, _Compare > &  __x,
const VectorMap< _Key, _Tp, _Compare > &  __y 
)
inline

Based on operator<.

Definition at line 537 of file VectorMap.h.

539  {
540  return !(__x < __y);
541  }
template<typename Range >
auto util::operator| ( Range &&  range,
RangeForWrapperTag   
) -> decltype(auto)

Transforms a range so that it can be used in a range-for loop.

Template Parameters
Rangethe type of range to be transformed
Parameters
rangethe range to be transformed
Returns
an equivalent range object to be used in a range-for loop

This is necessary only when the argument provides different types for the begin-of-range and end-of-range iterators. This is also superfluous for compilers adhering to C++ 2017 standard, which accepts iterators of different types by requirement. Example of usage:

Range data; // initialization
for (auto&& value: data | util::range_for) // ...

where data is supposed to gave begin and end iterators of different types.

Definition at line 458 of file RangeForWrapper.h.

459  { return wrapRangeFor(std::forward<Range>(range)); }
auto wrapRangeFor(Range &&range) -> decltype(auto)
Wraps an object for use in a range-for loop.
def util.optstat (   args)

Definition at line 233 of file util.py.

234 def optstat(args):
235  if args.optstat:
236  ROOT.gStyle.SetOptStat(args.optstat)
def optstat
Definition: util.py:233
template<typename BIter , typename EIter >
std::vector< double > util::partialPathLengths ( BIter  begin,
EIter  end 
)

Returns a sequences of partial lengths for the specified path.

Template Parameters
BItertype of iterator to the start of the trajectory
EItertype of iterator to the end of the trajectory
Parameters
beginiterator to the first point of the trajectory
enditerator past the last point of the trajectory
Returns
a sequence of partial lengths, one per point
See Also
pathLength()

The sequence of partial lengths is returned, with one entry per point. A partial length up to the point i is the sum of the distances between adjacent points starting from the first point (*begin) to the i-th, included. The first entry of the sequence is always 0.

The length are in the same units as the input point coordinates.

Requirements

The BIter type is a forward iterator.

The type Point must satisfy the following operations.

Definition at line 437 of file TrajectoryUtils.h.

437  {
438  if (!(begin != end)) return {};
439  std::vector<double> lengths;
440  lengths.reserve(std::distance(begin, end));
441  double totalLength = 0.0;
442  BIter it = begin, prev = begin;
443  do {
444  totalLength += geo::vect::norm(*it - *prev);
445  lengths.push_back(totalLength);
446  prev = it;
447  } while (++it != end);
448  return lengths;
449 } // util::partialPathLengths()
double distance(geo::Point_t const &point, CathodeDesc_t const &cathode)
Returns the distance of a point from the cathode.
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto norm(Vector const &v)
Return norm of the specified vector.
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename BIter , typename EIter >
double util::pathLength ( BIter  begin,
EIter  end 
)

Returns the total length of the specified path.

Template Parameters
BItertype of iterator to the start of the trajectory
EItertype of iterator to the end of the trajectory
Parameters
beginiterator to the first point of the trajectory
enditerator past the last point of the trajectory
Returns
the length of the path
See Also
partialPathLengths()

The sequence of partial lengths is returned, with one entry per point. The length is the sum of the distances between adjacent points of the sequence. Empty sequences and sequences of a single points have length 0.

The length are in the same units as the input point coordinates.

Requirements

The BIter type is a forward iterator.

The type Point must satisfy the following operations.

Definition at line 420 of file TrajectoryUtils.h.

420  {
421 
422  if (!(begin != end)) return 0.0;
423 
424  double totalLength = 0.0;
425  BIter it = begin, prev = begin;
426  while (++it != end) {
427  totalLength += geo::vect::norm(*it - *prev);
428  prev = it;
429  }
430  return totalLength;
431 
432 } // util::pathLength()
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto norm(Vector const &v)
Return norm of the specified vector.
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename FIter , typename LIter >
auto util::pathMiddlePoint ( FIter  itFirst,
LIter  itLast,
double  relTarget = 0.5 
)

Returns the geometric point in the middle of the specified path.

Template Parameters
FItertype of iterator to a point in the path
LItertype of iterator to a point in the path
Parameters
itFirstiterator to the first point in the path
itLastiterator to the last point in the path (must be valid point)
relTarget(default: 0.5) fraction of the total length to pursue
Returns
the geometric middle point of the path

The sequence between the iterators itFirst and itLast, both included, defines a path. This function returns the point that cuts that path into two subpaths, the first of which has relTarget fraction of the length of the total path (hence, with the default relTarget value of 0.5 the two subpaths have the same length). The point usually does not match any of the points in the sequence, but rather is in between two of them.

The path is considered a sequence of straight segments connecting the points.

Example of use with a LArSoft recob::Track object (track):

auto const& path = track.Trajectory().Positions();
geo::Point_t const middle
= util::PathMiddlePoint(path.begin(), std::prev(path.end()));

(note that here the function actually returns a recob::tracking::Point_t).

Requirements

The FIter type is a forward iterator, the type LIter is a backward iterator.

The type Point must satisfy the following operations.

The returned object is an instance of Point.

LArSoft geo::Point_t type is known to satisfy the requirements of Point (geo::Vector_t being its corresponding Vector type). The modulus function geo::vect::norm() is provided for geo::Vector_t in the LArSoft header larcorealg/CoreUtils/geo_vector_utils.h.

Definition at line 399 of file TrajectoryUtils.h.

400 {
401 
402  // We don't check that `LIter` also points to `Point_t`.
403  // The return value will be `Point_t` anyway.
404 
405  PathPointInfo_t<FIter> const targetInfo
406  = findMiddlePointInPath(itFirst, itLast, relTarget);
407 
408  // "next" point might be not there (e.g. if length is 0):
409  // let's not use it if possible
410  if (targetInfo.frac == 0.0) return *(targetInfo.itPoint);
411 
412  auto const delta = *std::next(targetInfo.itPoint) - *(targetInfo.itPoint);
413  return *(targetInfo.itPoint) + delta * targetInfo.frac;
414 
415 } // util::pathMiddlePoint()
PathPointInfo_t< FIter > findMiddlePointInPath(FIter itFirst, LIter itLast, double relTarget=0.5)
Returns information to identify the middle of the specified path.
template<typename T = double>
constexpr T util::pi ( )
inline

Returns the constant pi (up to 35 decimal digits of precision)

Definition at line 80 of file PhysicalConstants.h.

80 { return 3.14159265358979323846264338327950288L; }
double util::pythag ( double  x,
double  y 
)
inline

2D Euclidean distance

Definition at line 39 of file MathUtil.h.

40  {
41  return sqrt(sqr(x)+sqr(y));
42  }
process_name opflash particleana ie x
process_name opflash particleana ie ie y
constexpr T sqr(T v)
double util::pythag ( double  x,
double  y,
double  z 
)
inline

3D Euclidean distance

Definition at line 45 of file MathUtil.h.

46  {
47  return sqrt(sqr(x)+sqr(y)+sqr(z));
48  }
process_name opflash particleana ie ie ie z
process_name opflash particleana ie x
process_name opflash particleana ie ie y
constexpr T sqr(T v)
template<typename T >
constexpr T util::RadiansToDegrees ( angle)
inline

Converts the argument angle from radians into degrees ( $ \pi \rightarrow 180 $)

Definition at line 88 of file PhysicalConstants.h.

88 { return angle / pi<T>() * 180; }
finds tracks best matching by angle
std::map< fhicl::ParameterSetID, fhicl::ParameterSet > util::readConfigurationFromArtFile ( TFile &  file)

Reads and returns the art configuration stored in sourceDir.

Parameters
fileROOT file where the configuration is stored
Returns
the full configuration
Exceptions
cet::exception(category: "readConfigurationFromArtFile") on error
See Also
readConfigurationFromArtPrincipal()

The configuration is expected to be stored by art in the way it does for art ROOT files.

The configuration is returned as a map of parameter set ID to parameter set.

Definition at line 21 of file ReadArtConfiguration.cxx.

22 {
23  /*
24  * This code is ripped from `fhiclcpp/ParameterSetRegistry.h` and
25  * `lardata/DetectorInfoServices/DetectorClocksServiceStandard_service.cc`
26  * (LArSoft v 9.17.0).
27  *
28  * The special wrapped defines hooks to support a "virtual file system"
29  * within a ROOT file data base, in the way that art knows and I do not.
30  * So we bite it and accept a dependency against art_root_io.
31  */
32  art::SQLite3Wrapper sqliteDB(&file, "RootFileDB");
33 
34  auto* db = static_cast<sqlite3*>(sqliteDB);
35 
36  auto const throwOnSQLiteNotOK = [&db](std::string const& msg = {})
37  {
38  if (db == nullptr) {
39  throw cet::exception("readConfigurationFromArtFile")
40  << "Can't open SQLite database.";
41  }
42  auto const errcode = sqlite3_errcode(db);
43  // Caller's responsibility to make sure this really is an error
44  // and not (say) SQLITE_ROW or SQLITE_DONE:
45  if (errcode == SQLITE_OK) return;
46  throw cet::exception("readConfigurationFromArtFile")
47  << "SQLite3 error (code" << errcode << "): "
48  << sqlite3_errstr(errcode) << (msg.empty() ? "" : (": " + msg))
49  << "\n";
50  };
51 
52 
53  sqlite3_stmt* stmt = nullptr;
54  sqlite3_prepare_v2
55  (sqliteDB, "SELECT ID, PSetBlob from ParameterSets;", -1, &stmt, nullptr);
56  throwOnSQLiteNotOK("[SELECT ID, PSetBlob from ParameterSets;]");
57 
58  std::map<fhicl::ParameterSetID, fhicl::ParameterSet> config;
59  while (sqlite3_step(stmt) == SQLITE_ROW) {
60 
61  // reinterpretation: `unsigned char*` -> `char*`
62  std::string const psetIDstr
63  = reinterpret_cast<const char*>(sqlite3_column_text(stmt, 0));
64  auto pset = fhicl::ParameterSet::make
65  (reinterpret_cast<const char*>(sqlite3_column_text(stmt, 1)));
66  config.emplace(fhicl::ParameterSetID{ psetIDstr }, std::move(pset));
67 
68  } // while
69  sqlite3_finalize(stmt);
70  throwOnSQLiteNotOK("[SELECT ID, PSetBlob from ParameterSets;]");
71 
72  return config;
73 } // util::readConfigurationFromArtFile()
* file
Definition: file_to_url.sh:69
height to which particles are projected pnfs larsoft persistent physics cosmics Fermilab CORSIKA standard He_showers_ * db
template<typename Principal >
std::map< std::string, fhicl::ParameterSet > util::readConfigurationFromArtPrincipal ( Principal const &  principal)

Reads and returns the complete art configuration in the principal.

Template Parameters
Principaltype of framework principal class (e.g. art::Event)
Parameters
principalthe "principal" art object to read the information from
Returns
the full configuration, as map: process name -> FHiCL parameter set
Exceptions
cet::exception(category: "readConfigurationFromArtPrincipal") on error
See Also
readConfigurationFromArtFile()

Compared to readConfigurationFromArtFile(), this function relays the same information after it has been conveniently extracted by the framework. A "principal" is framework jargon for art::Event, art::SubRun or art::Run (all derived from art::DataViewImpl). Therefore, this function can be called e.g. in beginRun() hook of a module using its art::Run argument, or in a analyze() hook using its art::Event argument.

This function is supposed to be more solid than readConfigurationFromArtFile() because it relies less on internals of how the framework works. , this function relays the same information after it has been conveniently extracted by the framework. Also, this function should also be compatible with gallery::Event too (which is the reason why it is implemented as template instead of taking a art::DataViewImpl, which is art-specific), making the name of this function a misnomer.

The configuration is returned as a map of process names to parameter sets (note that the key is different from the one returned by readConfigurationFromArtFile()).

Definition at line 97 of file ReadArtConfiguration.h.

97  {
98 
99  std::map<std::string, fhicl::ParameterSet> configMap;
100 
101  for (art::ProcessConfiguration const& procConfig: principal.processHistory())
102  {
103 
104  fhicl::ParameterSet config;
105  if (!fhicl::ParameterSetRegistry::get(procConfig.parameterSetID(), config))
106  {
107  // this would be, as far as I understand, a logic error
108  throw cet::exception("readConfigurationFromArtPrincipal")
109  << "Configuration of process '" << procConfig.processName()
110  << "' can't be found!\n";
111  }
112 
113  configMap[procConfig.processName()] = std::move(config);
114  } // for
115 
116  return configMap;
117 
118 } // util::readConfigurationFromArtPrincipal()
def util.resize_graph (   args,
  hist 
)

Definition at line 112 of file util.py.

113 def resize_graph(args, hist):
114  if args.range_lo is not None and args.range_hi is not None:
115  hist.GetXaxis().SetLimits(args.range_lo, args.range_hi)
116  if args.y_min is not None and args.y_max is not None:
117  hist.GetYaxis().SetRangeUser(args.y_min, args.y_max)
def resize_graph
Definition: util.py:112
def util.resize_histo (   args,
  hist,
  name_postfix = "" 
)

Definition at line 118 of file util.py.

119 def resize_histo(args, hist, name_postfix=""):
120  histdim = 0
121  if isinstance(hist, ROOT.TH1D): histdim = 1
122  elif isinstance(hist, ROOT.TH2D): histdim = 2
123  elif isinstance(hist, ROOT.TH3D): histdim = 3
124 
125  axes_ranges = [(args.x_min, args.x_max), (args.y_min, args.y_max), (args.z_min, args.z_max)]
126  for i_axis, (lo, hi) in enumerate(axes_ranges):
127  if lo is not None and hi is not None:
128  if i_axis >= histdim:
129  raise Exception("Error: setting axis (%i) for histogram of dimmension (%i)" % (i_axis, histdim))
130 
131  if i_axis == 0: axis = hist.GetXaxis()
132  elif i_axis == 1: axis = hist.GetYaxis()
133  elif i_axis == 2: axis = hist.GetZaxis()
134 
135  range_lo_ind = None
136  for i in range(1, axis.GetNbins()+1):
137  if range_lo_ind is None and axis.GetBinLowEdge(i) > lo:
138  range_lo_ind = max(0, i-2)
139  if axis.GetBinLowEdge(i) >= hi:
140  range_hi_ind = i
141  break
142  else:
143  range_hi_ind = axis.GetNbins()+1
144  assert(range_lo_ind < range_hi_ind)
145 
146  axis_range = [axis.GetBinLowEdge(i) for i in range(1,axis.GetNbins()+1)] + [axis.GetBinUpEdge(axis.GetNbins())]
147  #new_axis_range = array('d', [axis_range[i] for i in range(range_lo_ind, range_hi_ind)])
148 
149  new_axis_args = [range_hi_ind - range_lo_ind - 1, axis_range[range_lo_ind], axis_range[range_hi_ind-1]]
150  if histdim == 1:
151  new_hist = ROOT.TH1D(hist.GetName() + " resized " + name_postfix, hist.GetTitle() + name_postfix, *new_axis_args)
152  elif histdim == 2:
153  x_axis_args = [hist.GetXaxis().GetNbins(), hist.GetXaxis().GetBinLowEdge(1), hist.GetXaxis().GetBinUpEdge(hist.GetXaxis().GetNbins())]
154  y_axis_args = [hist.GetYaxis().GetNbins(), hist.GetYaxis().GetBinLowEdge(1), hist.GetYaxis().GetBinUpEdge(hist.GetYaxis().GetNbins())]
155  histo_args = new_axis_args + y_axis_args if i_axis == 0 else x_axis_args + new_axis_args
156  new_hist = ROOT.TH2D(hist.GetName() + " resized " + name_postfix, hist.GetTitle() + name_postfix, *histo_args)
157  elif histdim == 3:
158  x_axis_args = [hist.GetXaxis().GetNbins(), hist.GetXaxis().GetBinLowEdge(1), hist.GetXaxis().GetBinUpEdge(hist.GetXaxis().GetNbins())]
159  y_axis_args = [hist.GetYaxis().GetNbins(), hist.GetYaxis().GetBinLowEdge(1), hist.GetYaxis().GetBinUpEdge(hist.GetYaxis().GetNbins())]
160  z_axis_args = [hist.GetZaxis().GetNbins(), hist.GetZaxis().GetBinLowEdge(1), hist.GetZaxis().GetBinUpEdge(hist.GetZaxis().GetNbins())]
161  if i_axis == 0:
162  histo_args = new_axis_args + y_axis_args + z_axis_args
163  elif i_axis == 1:
164  histo_args = x_axis_args + new_axis_args + z_axis_args
165  elif i_axis == 2:
166  histo_args = x_axis_args + y_axis_args + new_axis_args
167  new_hist = ROOT.TH3D(hist.GetName() + " resized " + name_postfix, hist.GetTitle() + name_postfix, *histo_args)
168 
169  for i in range(range_lo_ind+1, range_hi_ind+1):
170  i_set = i - range_lo_ind
171  if histdim == 1:
172  new_hist.SetBinContent(i - range_lo_ind, hist.GetBinContent(i))
173  new_hist.SetBinError(i - range_lo_ind, hist.GetBinError(i))
174  elif histdim == 2:
175  other_axis = hist.GetYaxis() if i_axis == 0 else hist.GetXaxis()
176  for j in range(1, other_axis.GetNbins()+1):
177  i_bin_old = hist.GetBin(i, j) if i_axis == 0 else hist.GetBin(j, i)
178  i_bin_new = new_hist.GetBin(i_set, j) if i_axis == 0 else new_hist.GetBin(j, i_set)
179  new_hist.SetBinContent(i_bin_new, hist.GetBinContent(i_bin_old))
180  new_hist.SetBinError(i_bin_new, hist.GetBinError(i_bin_old))
181  elif histdim == 3:
182  other_axes = [hist.GetXaxis(), hist.GetYaxis(), hist.GetZaxis()]
183  other_axes.pop(i_axis)
184  for j in range(1,other_axes[0].GetNbins()+1):
185  for k in range(1, other_axes[1].GetNbins()+1):
186  old_axes_indices = [j,k]
187  old_axes_indices.insert(i_axis, i)
188 
189  new_axes_indices = [j,k]
190  new_axes_indices.insert(i_axis, i_set)
191 
192  i_bin_old = hist.GetBin(*old_axes_indices)
193  i_bin_new = new_hist.GetBin(*new_axes_indices)
194  new_hist.SetBinContent(i_bin_new, hist.GetBinContent(i_bin_old))
195  new_hist.SetBinError(i_bin_new, hist.GetBinError(i_bin_old))
196  hist = new_hist
197  if args.projectionX:
198  hist = hist.ProjectionX()
199  if args.projectionY:
200  hist = hist.ProjectionY()
201  if args.projectionZ:
202  hist = hist.ProjectionZ()
203  if args.projectionXY:
204  hist = hist.Project3D("yx")
205  if args.projectionYZ:
206  hist = hist.Project3D("zy")
207  if args.projectionXZ:
208  hist = hist.Project3D("zx")
209 
210  if args.rebinX is not None and args.rebinX != 1:
211  hist.RebinX(args.rebinX)
212  if args.rebinY is not None and args.rebinY != 1:
213  hist.RebinY(args.rebinY)
214  if args.rebinZ is not None and args.rebinZ != 1:
215  hist.RebinZ(args.rebinZ)
216  return hist
auto enumerate(Iterables &&...iterables)
Range-for loop helper tracking the number of iteration.
Definition: enumerate.h:69
def resize_histo
Definition: util.py:118
def util.root_env ( )

Definition at line 9 of file util.py.

9 
10 def root_env():
11  buildpath = os.environ["SBN_LIB_DIR"]
12  if not buildpath:
13  print "ERROR: SBNDDAQ_ANALYSIS_BUILD_PATH not set"
14  sys.exit()
15  ROOT.gROOT.ProcessLine(".L " + buildpath + "/libsbnanalysis_Event.so")
16  ROOT.gROOT.ProcessLine(".L " + buildpath + "/libsbnanalysis_PandoraTesting_classes.so")
17  ROOT.gROOT.ProcessLine(".L " + buildpath + "/libsbnanalysis_SBNOsc_classes.so")
18  ROOT.gROOT.ProcessLine(".L " + buildpath + "/libsbnanalysis_SBNOscReco_classes.so")
def root_env
Definition: util.py:9
template<typename BIter , typename EIter , typename Key , typename Sorter = std::less<void>>
auto util::sortBy ( BIter  begin,
EIter  end,
Key  key,
Sorter  sorter = {} 
)

Returns a vectors to pointers to coll elements, sorted by key.

Template Parameters
BItertype of begin iterator to objects to be sorted
EItertype of end iterator to objects to be sorted
Keytype of functor extracting the key from an element
Sorter(default: std::less) type of functor comparing two keys
Parameters
collcollection of objects to be sorted
keyfunctor extracting the key from an element
sorter(default: std::less{}) functor comparing two keys
Returns
a vector of pointers to coll elements, sorted by key
See Also
sortCollBy()

A vector of pointers to all elements of coll is returned. The pointers are constant only if Coll is a constant type. The order of the pointed elements is driven by sorter applied to the key of each element (key(item)).

Note
As an exception, if the elements of Coll are already C pointers, the returned collection is a copy of those pointers rather than pointers to them.

Definition at line 104 of file sortBy.h.

105 {
106 
107  /*
108  * 0. establish whether we are dealing with pointers or not
109  * 1. create a collection of pairs { key, pointer to element }
110  * 2. sort that collection on the first element (key)
111  * 3. create a collection of the pointer to element (second element of the
112  * pairs from the collection just sorted), and return it
113  */
114  using value_type = typename BIter::value_type;
115 
116  //
117  // 0. establish whether we are dealing with pointers or not
118  //
119  static constexpr bool isPointer = std::is_pointer_v<value_type>;
120 
121  using pointer_type = std::conditional_t
122  <isPointer, value_type, typename std::iterator_traits<BIter>::pointer>;
123 
124  using Key_t = std::decay_t<decltype(key(*begin))>;
125  using SortingPair_t = std::pair<Key_t, pointer_type>;
126 
127  //
128  // 1. create a collection of pairs { key, pointer to element }
129  //
130  auto getPointer = [](auto& elem)
131  { if constexpr(isPointer) return elem; else return &elem; };
132  auto makePair = [&key, getPointer](auto&& item)
133  { return SortingPair_t(key(item), getPointer(item)); };
134 
135  std::vector<SortingPair_t> sortingColl;
136 
137  // reserve size, but only if to discover the size is fast
138  if constexpr(details::is_random_access_iterator_v<BIter>)
139  sortingColl.reserve(std::distance(begin, end));
140  std::transform(begin, end, back_inserter(sortingColl), makePair);
141 
142  //
143  // 2. sort that collection on the first element (key)
144  //
145  auto pair_sorter
146  = [&sorter](SortingPair_t const& a, SortingPair_t const& b)
147  { return sorter(a.first, b.first); }
148  ;
149  std::sort(sortingColl.begin(), sortingColl.end(), pair_sorter);
150 
151  //
152  // 3. create a collection of the pointer to element (second element of the
153  // pairs from the collection just sorted), and return it
154  //
155  std::vector<pointer_type> sortedColl;
156  sortedColl.reserve(sortingColl.size());
158  sortingColl.begin(), sortingColl.end(), back_inserter(sortedColl),
159  [](SortingPair_t const& pair){ return pair.second; }
160  );
161 
162  return sortedColl;
163 
164 } // util::sortBy()
double std(const std::vector< short > &wf, const double ped_mean, size_t start, size_t nsample)
Definition: UtilFunc.cxx:42
static constexpr Sample_t transform(Sample_t sample)
process_name gaushit a
double distance(geo::Point_t const &point, CathodeDesc_t const &cathode)
Returns the distance of a point from the cathode.
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename Coll , typename Sorter >
void util::SortByPointers ( Coll &  coll,
Sorter  sorter 
)

Applies sorting indirectly, minimizing data copy.

Template Parameters
Colltype of collection to be sorted
Sortertype of sorter
Parameters
collcollection to be sorted
sorterfunctor sorting a vector of pointers (makePointerVector())

The sorter functor can receive a reference to a vector as the one produced by makePointerVector(coll) (that is, a C++ STL vector of pointers to the value type of Coll), and sort it "in place". The container Comp must implement push_back() call in a std::vector fashion.

The algorithm is equivalent to the following:

  1. create a parallel vector of pointers to the data
  2. sort the data pointers (delegating to sorter)
  3. move the data, sorted, from the original collection to a new one
  4. replace the content of cont with the one from the sorted collection

Single elements are moved from the original collection to a new one.

The data elements of Coll must be moveable, as Coll itself must be.

Note
Use this algorithm only as a last resort, as there are usually better ways to sort collections than this one, which is not even particularly optimized.

Definition at line 204 of file SortByPointers.h.

204  {
205 
206  using coll_t = Coll;
207 
208  //
209  // create the collection of pointers to data
210  //
211  auto ptrs = makePointerVector(coll);
212 
213  //
214  // delegate the sorting by pointers
215  //
216  sorter(ptrs);
217 
218  //
219  // create a sorted collection moving the content from the original one
220  //
221  coll_t sorted;
222  MoveFromPointers(sorted, ptrs);
223 
224  //
225  // replace the old container with the new one
226  //
227  coll = std::move(sorted);
228 
229 } // util::SortByPointers()
auto makePointerVector(Coll &coll)
Creates a STL vector with pointers to data from another collection.
void MoveFromPointers(Coll &dest, PtrColl &src)
Moves the content from a collection of pointers to one of data.
template<typename Coll , typename Key , typename Sorter = std::less<void>>
auto util::sortCollBy ( Coll &  coll,
Key  key,
Sorter  sorter = {} 
)

Returns a vectors to pointers to coll elements, sorted by key.

Template Parameters
Colltype of collection of objects to be sorted
Keytype of functor extracting the key from an element
Sorter(default: std::less) type of functor comparing two keys
Parameters
collcollection of objects to be sorted
keyfunctor extracting the key from an element
sorter(default: std::less{}) functor comparing two keys
Returns
a vector of pointers to coll elements, sorted by key
See Also
sortBy()

A vector of pointers to all elements of coll is returned. The pointers are constant only if Coll is a constant type. The order of the pointed elements is driven by sorter applied to the key of each element (key(item)).

Note
As an exception, if the elements of Coll are already C pointers, the returned collection is a copy of those pointers rather than pointers to them.

Definition at line 169 of file sortBy.h.

169  {
170  using std::begin, std::end;
171  return sortBy(begin(coll), end(coll), key, sorter);
172 } // util::sortCollBy()
auto sortBy(BIter begin, EIter end, Key key, Sorter sorter={})
Returns a vectors to pointers to coll elements, sorted by key.
Definition: sortBy.h:104
auto end(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:585
auto begin(FixedBins< T, C > const &) noexcept
Definition: FixedBins.h:573
template<typename Coll , typename Sorter >
void util::SortUniquePointers ( Coll &  coll,
Sorter &&  sorter 
)

Sorts a vector of unique pointers using a C pointer sorter.

Template Parameters
Colltype of collection to be sorted
Sortertype of sorter function
Parameters
collcollection to be sorted
sortersorting procedure

This adapter moves the unique pointers around to match a sorted version of source. This is an expensive procedure, implying the creation of a temporary vector and of additional supporting data: avoid it if at all possible.

Definition at line 234 of file SortByPointers.h.

234  {
235 
236  using Collection_t = Coll;
237  using UPtr_t = typename Collection_t::value_type;
238 
239  static_assert(util::is_unique_ptr_v<UPtr_t>);
240 
241  //
242  // create the collection of pointers to data
243  //
244  auto ptrs = makePointerVector(coll);
245 
246  // data pointer -> index
247  auto const ptrIndex = util::makeValueIndex(ptrs);
248 
249  //
250  // delegate the sorting by pointers
251  //
252  sorter(ptrs);
253 
254  //
255  // create a sorted collection moving the content from the original one
256  //
257  Collection_t sorted;
258  for (auto const& dataPtr: ptrs) {
259  std::size_t const originalIndex = ptrIndex.at(dataPtr);
260  sorted.emplace_back(std::move(coll[originalIndex]));
261  }
262 
263  //
264  // replace the old container with the new one
265  //
266  coll = std::move(sorted);
267 
268 } // util::SortUniquePointers()
auto makePointerVector(Coll &coll)
Creates a STL vector with pointers to data from another collection.
decltype(auto) makeValueIndex(Coll const &coll, Extractor getter)
Returns a map of value to index.
template<class T >
T util::sqr ( x)
inline

More efficient square function than pow(x,2)

Definition at line 23 of file MathUtil.h.

23 {return x*x;}
process_name opflash particleana ie x
def util.style (   args,
  canvas,
  hist 
)

Definition at line 237 of file util.py.

238 def style(args, canvas, hist):
239  hist.GetYaxis().SetTitleSize(20)
240  hist.GetYaxis().SetTitleFont(43)
241  hist.GetYaxis().SetLabelFont(43)
242  hist.GetYaxis().SetLabelSize(20)
243  hist.GetYaxis().CenterTitle()
244 
245  hist.GetXaxis().SetTitleSize(20)
246  hist.GetXaxis().SetTitleFont(43)
247  hist.GetXaxis().SetLabelFont(43)
248  hist.GetXaxis().SetLabelSize(20)
249  hist.GetXaxis().CenterTitle()
250 
251  if args.margin_left is not None:
252  canvas.SetLeftMargin(args.margin_left)
253  if args.margin_right is not None:
254  canvas.SetRightMargin(args.margin_right)
255  if args.margin_bottom is not None:
256  canvas.SetBottomMargin(args.margin_bottom)
257  if args.margin_top is not None:
258  canvas.SetTopMargin(args.margin_top)
259 
260  if args.xlabel is not None:
261  for i, xlabel in enumerate(args.xlabel):
262  hist.GetXaxis().SetBinLabel(i+1, xlabel)
263  if args.ylabel is not None:
264  for i, ylabel in enumerate(args.ylabel):
265  hist.GetYaxis().SetBinLabel(i+1, ylabel)
266  hist.GetYaxis().LabelsOption("v")
267 
268 
269  if args.xtitle: hist.GetXaxis().SetTitle(args.xtitle)
270  if args.ytitle: hist.GetYaxis().SetTitle(args.ytitle)
271  if args.yrange: hist.GetYaxis().SetRangeUser(*args.yrange)
def style
Definition: util.py:237
auto enumerate(Iterables &&...iterables)
Range-for loop helper tracking the number of iteration.
Definition: enumerate.h:69
template<typename _Key , typename _Tp , typename _Compare >
void util::swap ( VectorMap< _Key, _Tp, _Compare > &  __x,
VectorMap< _Key, _Tp, _Compare > &  __y 
)
inline

See VectorMap::swap().

Definition at line 545 of file VectorMap.h.

547  {
548  __x.swap(__y);
549  }
decltype(auto) util::takeAddress ( )

Returns a functor that returns the address of its argument.

See Also
util::AddressTaker

Example:

std::vector<int*> ptrs(data.size());
(data.begin(), data.end(), ptrs.begin(), util::takeAddress());

will fill the vector ptrs with pointers to the elements of data.

Why bother?

C++ already provides a tool to effectively take an address, std::addressof. The reason for takeAddress() is that std::addressof() is a function, with many overloads, and to use it in a STL algorithm the overload has to be resolved first. For example:

using addressof_t = int const*(*)(int const&);
std::transform(data.cbegin(), data.cend(), std::back_inserter(dataPtr),
((addressof_t) &std::addressof));

One important limit is that the type of the argument (in this case int const&) needs to be known or deduced in a quite precise way, in particular regarding constantness and referenceness. This is unconvenient and convoluted enough that one would rather create a new function, like:

auto takeAddress = [](auto&& ref){ return std::addressof(ref); };
std::vector<int const*> dataPtr;
std::transform(data.cbegin(), data.cend(), std::back_inserter(dataPtr),

This util::takeAddress() operates in a very similar way to the lambda in the last example.

Definition at line 86 of file operations.h.

86 { return AddressTaker(); }
def util.validate_hists (   names,
  hists 
)

Definition at line 352 of file util.py.

353 def validate_hists(names, hists):
354  for nn,hh in zip(names, hists):
355  if isinstance(hh, list):
356  for n,h in zip(nn,hh):
357  if not h:
358  raise Exception("Error: invalid histogram with name (%s)" % n)
359  # raise Exception("Error: invalid histogram (%s) with name (%s)" % (h, n))
360  else:
361  if not hh:
362  raise Exception("Error: invalid histogram with name (%s)" % (nn))
363  #raise Exception("Error: invalid histogram (%s) with name (%s)" % (hh, nn))
364 
365 
def validate_hists
Definition: util.py:352
auto zip(Iterables &&...iterables)
Range-for loop helper iterating across many collections at the same time.
Definition: zip.h:295
template<typename Coll >
decltype(auto) util::values ( Coll &&  coll)

Range-for loop helper iterating across the values of the specified collection.

Template Parameters
Colltype of the collection to iterate through
Parameters
collthe collection to iterate through
Returns
an object suitable for range-for loop
See Also
util::const_values()

This function is in most of cases a no-operation, returning the collection just as it was specified, to be iterated on directly. In case of mapping types, though, a different object is returned and the iteration will happen to the value type of the mapping instead than on the key-value pair.

std::map<int, float> data { { 1, 4.0F }, { 3, 12.0F }, { 2, 8.0F } };
std::vector<float> values;
for (float value: util::values(data))
values.push_back(value);

will result in values vector being of size 3 and with values { 4.0F, 8.0F, 12.0F } (the order is the one of iterating through a std::map).

def util.wait (   args)

Definition at line 19 of file util.py.

19 
20 def wait(args):
21  if args.wait:
22  raw_input("Press Enter to continue...")
def wait
Definition: util.py:19
def util.with_display_args (   parser)

Definition at line 79 of file util.py.

79 
80 def with_display_args(parser):
81  parser.add_argument("-w", "--wait", action="store_true")
82  parser.add_argument("-o", "--output", default=None)
83  return parser
def with_display_args
Definition: util.py:79
def util.with_graphsize_args (   parser)

Definition at line 89 of file util.py.

89 
90 def with_graphsize_args(parser):
91  parser.add_argument("-xm", "--x_min", type=float, default=None)
92  parser.add_argument("-xh", "--x_max", type=float, default=None)
93 
94  parser.add_argument("-ym", "--y_min", type=float, default=None)
95  parser.add_argument("-yh", "--y_max", type=float, default=None)
96 
97  parser.add_argument("-zm", "--z_min", type=float, default=None)
98  parser.add_argument("-zh", "--z_max", type=float, default=None)
99  return parser
def with_graphsize_args
Definition: util.py:89
def util.with_histosize_args (   parser)

Definition at line 100 of file util.py.

101 def with_histosize_args(parser):
102  parser.add_argument("-rX", "--rebinX", type=int, default=1)
103  parser.add_argument("-rY", "--rebinY", type=int, default=1)
104  parser.add_argument("-rZ", "--rebinZ", type=int, default=1)
105  parser.add_argument("-pX", "--projectionX", action="store_true")
106  parser.add_argument("-pY", "--projectionY", action="store_true")
107  parser.add_argument("-pZ", "--projectionZ", action="store_true")
108  parser.add_argument("-pXY", "--projectionXY", action="store_true")
109  parser.add_argument("-pYZ", "--projectionYZ", action="store_true")
110  parser.add_argument("-pXZ", "--projectionXZ", action="store_true")
111  return with_graphsize_args(parser)
def with_histosize_args
Definition: util.py:100
def with_graphsize_args
Definition: util.py:89
def util.with_histostyle_args (   parser)

Definition at line 220 of file util.py.

221 def with_histostyle_args(parser):
222  parser.add_argument("-yr", "--yrange", default=None, type=int_pair)
223  parser.add_argument("-xt", "--xtitle", default=None)
224  parser.add_argument("-yt", "--ytitle", default=None)
225  parser.add_argument("-yl", "--ylabel", nargs="+", default=None)
226  parser.add_argument("-xl", "--xlabel", nargs="+", default=None)
227  parser.add_argument("-os", "--optstat", default=None)
228  parser.add_argument("-ml", "--margin_left", default=None, type=float)
229  parser.add_argument("-mr", "--margin_right", default=None, type=float)
230  parser.add_argument("-mt", "--margin_top", default=None, type=float)
231  parser.add_argument("-mb", "--margin_bottom", default=None, type=float)
232  return parser
def with_histostyle_args
Definition: util.py:220
def util.with_input_args (   parser)

Definition at line 27 of file util.py.

27 
28 def with_input_args(parser):
29  if "INPUTFILE" in os.environ:
30  parser.add_argument("-i", "--input", default=("input", ROOT.TFile(os.environ["INPUTFILE"])), nargs="+", type=filespec, action=FileSpec)
31  else:
32  parser.add_argument("-i", "--input", required=True, nargs="+", type=filespec, action=FileSpec)
33  return parser
def with_input_args
Definition: util.py:27
def util.with_io_args (   parser)

Definition at line 84 of file util.py.

84 
85 def with_io_args(parser):
86  parser = with_input_args(parser)
87  parser = with_display_args(parser)
88  return parser
def with_input_args
Definition: util.py:27
def with_display_args
Definition: util.py:79
def with_io_args
Definition: util.py:84
def util.with_text_args (   parser)

Definition at line 54 of file util.py.

54 
55 def with_text_args(parser):
56  parser.add_argument("-txt", "--text", nargs="+", default=None)
57  parser.add_argument("-tp", "--text_position", default=[0.5,0.4, 0.75, 0.6], type=comma_separated)
58  parser.add_argument("-ts", "--text_size", default=30, type=int)
59  parser.add_argument("-tf", "--text_font", default=43, type=int)
60  parser.add_argument("-tc", "--text_color", default=ROOT.kBlack, type=int)
61  return parser
def with_text_args
Definition: util.py:54
template<typename Range >
auto util::wrapRangeFor ( Range &&  range) -> decltype(auto)

Wraps an object for use in a range-for loop.

Template Parameters
Rangetype of range object (anything with begin() and end())
Parameters
rangeinstance of the range object to be wrapped

This is necessary only when the argument provides different types for the begin-of-range and end-of-range iterators. This is also superfluous for compilers adhering to C++ 2017 standard, which accepts iterators of different types by requirement. Example of usage:

Range data; // initialization
for (auto&& value: util::wrapRangeFor(data)) // ...

where data is supposed to gave begin and end iterators of different types.

Definition at line 426 of file RangeForWrapper.h.

427  {
428  return details::WrapRangeForDispatcher<Range>::wrap
429  (std::forward<Range>(range));
430  }
def util.write (   args,
  canvas 
)

Definition at line 23 of file util.py.

23 
24 def write(args, canvas):
25  if args.output:
26  canvas.SaveAs(args.output)
def write
Definition: util.py:23
template<std::size_t Lead, typename... Iterables>
auto util::zip ( Iterables &&...  iterables)

Range-for loop helper iterating across many collections at the same time.

Template Parameters
Leadindex of the parameter driving the start and end of the loop
Iterablestype of objects to be iterated together
Parameters
iterablesall iterable objects to be iterated together
Returns
an object suitable for range-for loop
See Also
util::enumerate()

In the range-for loop, at each iteration this object yields a tuple of values, each of the type returned by dereferencing begin(iterable). For example:

constexpr std::size_t N = 4;
std::array<int, N> twice;
std::vector<double> thrice(N + 1);
unsigned int i = 0;
for (auto&& [ a, b]: util::zip(twice, thrice)) {
a = 2 * i;
b = 3.0 * i;
++i;
} // for

In this example, N iterations will be run because that is the size of the first iterable given to enumerate. If a different leading iterable is needed, that has to be specified as an argument. The following loop is completely equivalent to the former one:

unsigned int i = 0;
for (auto&& [ b, a]: util::zip<1U>(thrice, twice)) {
a = 2 * i;
b = 3.0 * i;
++i;
} // for

(the index is zero-based, so 1U refers to the second argument).

Range-for loop helper iterating across many collections at the same time.

Definition at line 295 of file zip.h.

295  {
296 
297  return util::span(
298  details::make_zip_begin_iterator<Lead>(iterables...),
299  details::make_zip_end_iterator<Lead>(iterables...)
300  );
301 
302 } // util::zip()
Simple class with a begin and an end.
Definition: span.h:125
template<typename... Iterables>
auto util::zip ( Iterables &&...  iterables)

Version of zip() with first iterator implicitly leading the iteration.

Range-for loop helper iterating across many collections at the same time.

Definition at line 80 of file zip.h.

81  { return zip<0U>(std::forward<Iterables>(iterables)...); }

Variable Documentation

constexpr double util::kBogusD = -999.

obviously bogus double value

Definition at line 71 of file PhysicalConstants.h.

constexpr float util::kBogusF = -999.

obviously bogus float value

Definition at line 73 of file PhysicalConstants.h.

constexpr int util::kBogusI = -999

obviously bogus integer value

Definition at line 72 of file PhysicalConstants.h.

constexpr double util::kc = 29.9792458

Speed of light in vacuum in LArSoft units [cm/ns].

Definition at line 59 of file PhysicalConstants.h.

constexpr double util::kCentimeterToMeter = 1./kMeterToCentimeter

Definition at line 64 of file PhysicalConstants.h.

constexpr double util::keVToMeV = 1.e-6

1e6 eV = 1 MeV

Definition at line 68 of file PhysicalConstants.h.

constexpr double util::kGeVToElectrons = 4.237e7

23.6eV per ion pair, 1e9 eV/GeV

Definition at line 55 of file PhysicalConstants.h.

constexpr double util::kINVALID_DOUBLE = std::numeric_limits<Double_t>::max()

Definition at line 33 of file GeometryUtilities.h.

constexpr double util::kKilometerToMeter = 1./kMeterToKilometer

Definition at line 66 of file PhysicalConstants.h.

constexpr double util::kMeterToCentimeter = 1.e2

1 m = 100 cm

Definition at line 63 of file PhysicalConstants.h.

constexpr double util::kMeterToKilometer = 1.e-3

1000 m = 1 km

Definition at line 65 of file PhysicalConstants.h.

constexpr double util::kMeVToeV = 1./keVToMeV

Definition at line 69 of file PhysicalConstants.h.

constexpr double util::kModBoxA = 0.930

Modified Box Alpha.

Definition at line 49 of file PhysicalConstants.h.

constexpr double util::kModBoxB = 0.212

Modified Box Beta in g/(MeV cm)*kV/cm.

Definition at line 50 of file PhysicalConstants.h.

constexpr double util::kRecombA = 0.800

A constant.

Definition at line 35 of file PhysicalConstants.h.

constexpr double util::kRecombk = 0.0486

k constant, in g/(MeV cm)*kV/cm.

Definition at line 36 of file PhysicalConstants.h.

constexpr double util::quietCompiler = kBogusD*kBogusI*kBogusF*kRecombA*kRecombk*kGeVToElectrons

Definition at line 75 of file PhysicalConstants.h.

constexpr RangeForWrapperTag util::range_for

Constant to be used with operator|(Range&&, details::RangeForWrapperTag).

Definition at line 438 of file RangeForWrapper.h.

template<typename XType , typename Func , typename UntilFunc >
util::SampledFunction< XType, XType >

Definition at line 362 of file SampledFunction.h.

const float util::SQRT_TWO_PI = 2.506628

Definition at line 18 of file GaussianEliminationAlg.h.