MRS  1.0
A C++ Class Library for Statistical Set Processing
subpavings Namespace Reference

An abstract class for target function objects. More...

Classes

class  MyCompare
class  AdaptiveHistogram
 A wrapper or manager for an SPSnode aka StatsSubPaving in conjunction with massive amounts of sample data. More...
class  ChangeOfStateInformationAutoMCMC
 Type for collecting change of state information for use with automated MCMC processes. More...
class  ChangeOfStateInformationBasic
 Type for collecting change of state information. More...
class  AdaptiveHistogramCollator
 A wrapper or manager for a CollatorSPSnode. More...
class  BooleanMappedValue
class  BooleanValueImageEstimator
class  BooleanValueImageExpanderEstimator
class  BooleanValueMappedSPnode
 A derived class based on MappedSPnode < bool >. More...
class  CarverSEB
 A static class for doing carving-SEB RPQ routines. More...
class  CollatorSPnode
 A derived class based on SPnode. More...
class  FEIEvalObj
 An interface for a type providing a way to stop estimator changes. More...
class  FEICritLeaves_GTE
 Class for testing the number of leaves in estimator. More...
class  FEICritLeaves_LTE
 Class for testing the number of leaves in estimator. More...
class  FEICritIntervalBand_LTE
 Class for testing the interval band on the estimator. More...
class  FEICritStopAll
 Class to bale out of priority queue splitting. More...
class  FunctionEstimatorInterval
 A wrapper or manager for an IntervalMappedSPnode tree to be used for function estimation using interval enclosures over subpaving boxes. More...
class  FunctionEstimatorKDE
 A wrapper or manager for an RealMappedSPnode tree to be used for function estimation based on a kernel density estimate (KDE) function available pointwise. More...
class  FunctionEstimatorReal
 A wrapper or manager for an RealMappedSPnode tree to be used for function estimation. More...
class  FunctionImageEstimatorBooleanValue
 A wrapper or manager for an BooleanValueMappedSPnode tree to be used for function image estimation using boolean-mapped subpaving boxes. More...
class  HistEvalObj
 A Virtual class providing a way to stop histogram changes. More...
class  CritLeaves_GTE
 Class for testing the number of bins of a histogram. More...
class  CritLeaves_LTE
 Class for testing the number of bins of a histogram. More...
class  CritSmallestCount_LTE
 Class for testing the count of the node with the smallest count in histogram's subpaving. More...
class  CritLargestCount_LTE
 Class for testing the count of the node with the largest count in histogram's subpaving. More...
class  CritLargestCount_LTE_CritLeaves_GTE
 Class for testing the count of the node with the largest count or the maximum number of leaves in histogram's subpaving. More...
class  CritSmallestVol_LTE
 Class for testing the volume of the box with the smallest volume in the histogram's subpaving. More...
class  CritLargestVol_LTE
 Class for testing the volume of the box with the largest volume in the histogram's subpaving. More...
class  CritLargestVol_LTE_CritLeaves_GTE
 Class for testing the count of the node with the largest count or the maximum number of leaves in histogram's subpaving. More...
class  CritCOPERRChange_GTE
 Class for testing the change in COPERR score from splitting. More...
class  CritAICChange_GTE
 Class for testing the change in AIC score from splitting. More...
class  CritCOPERRChangeOrLeaves_GTE
 Class for testing change in COPERR or number leaves from splitting. More...
class  CritAICChangeOrLeaves_GTE
 Class for testing change in AIC or number leaves from splitting. More...
class  CritCOPERRChangeOrLargestCount_LTE
 Class for testing change in COPERR or largest count from splitting. More...
class  CritAICChangeOrLargestCount_LTE
 Class for testing change in AIC or largest count from splitting. More...
class  CritCOPERRMergeChange_GTE
 Class for testing the change in COPERR score from merging. More...
class  CritAICMergeChange_GTE
 Class for testing the change in AIC score from merging. More...
class  CritCOPERRMergeChangeOrLeaves_LTE
 Class for testing change in COPERR or number leaves from merging. More...
class  CritAICMergeChangeOrLeaves_LTE
 Class for testing change in AIC or number leaves from merging. More...
class  CritStopAll
 Class to bale out of priority queue splitting. More...
class  LogMCMCPrior
 Abstract class for MCMC priors. More...
class  LogCatalanPrior
 A class for a log prior based on a Catalan number prior. More...
class  LogTemperaturePrior
class  LogMCMCIMHPrior
 Abstract class for IMH MCMC priors. More...
class  LogCatalanIMHPrior
 A class for a log prior for IMH MCMC based on a Catalan number prior. More...
class  MCMCProposal
 Abstract class for MCMC proposal distributions. More...
class  UniformProposal
class  UniformSSMProposal
 The 'stay-split-merge' base chain proposal class, where probability of staying in same state $ \sigma $ is fixed, the probability of a split is $ \frac{1-\sigma}{2} $, the probability of a merge is $ \frac{1-\sigma}{2} $ and, given a split, the probabilities of each leaf being chosen are equal, and given a merge, the probabilities of each cherry being chosen are equal. More...
class  EquiProbProposal
class  PenObj
 Abstract class for objects with penalty function for histogram fit. More...
class  PenLeaves
 Penalty function as number of leaves in histogram. More...
class  PenAIC1
 Class for penalty function 1 for AIC. More...
class  PenAIC2
 Class for penalty function 2 for AIC. More...
class  PenAIC3
 Class for penalty function 3 for AIC. More...
class  PenAIC4
 Class for penalty function 4 for AIC. More...
class  PenAIC5
 Class for penalty function 5 for AIC. More...
class  IMHProposal
 Abstract class for IMH MCMC proposal distributions. More...
class  IntervalEstimator
class  IntervalExpanderEstimator
class  IntervalMappedSPnode
 A derived class based on MappedSPnode < cxsc::interval >. More...
class  ReimannDiffMeasurer
 A type for measuring nodes that uses the total area of the interval band on a node, ie the volume of the box multiplied by the diameter of the interval. More...
class  IntervalToleranceMeasurer
 A type for measuring nodes that uses the maximum distance between the ends of the interval and real image of the midpoint of the box of the node under some function. More...
class  MappedFobj
class  MappedFobj1D
class  MappedFobj2D
class  MappedSPnode
 A templated derived class based on SPnode. More...
class  MCMCGRAuto
 Type for objects capable of doing MCMC with some automatic convergence/burn-in testing rule using Gelman-Rubin heuristics. More...
class  MCMCGRAutoNew
 This class is instantiated with one or more MCMCGRAuto::Diagnostic diagnostics objects. Each one calculates its own Gelman-Rubin values and determines whether its own tolerance criteria is met. The MCMCGRAutoNew object organises the MCMC process and determines whether some overall burn-in criteria across all the diagnostics it is using is satisfied (eg, whether some threshold number of diagnostic criteria rhatFlagCounterThreshold has been met). If this overall burn-in criteria is satisfied, this object samples from the chains. When sampling is completed this object returns the sample average. More...
class  MCMCGRDiagnostic
class  MCMCGRDiagnosticInterval
 Constructor. More...
class  MCMCGRDiagnosticIntervalAvDepth
class  MCMCGRDiagnosticIntervalCherries
class  MCMCGRDiagnosticIntervalLeaves
class  MCMCGRDiagnosticPSRF
 Constructor. More...
class  MCMCGRDiagnosticPSRFAvDepth
class  MCMCGRDiagnosticPSRFCherries
class  MCMCGRDiagnosticPSRFLeaves
class  MCMCGRDiagnosticPSRFLogpost
class  MCMCPartitionGenerator
 A class to be able to generate a random partition of a binary tree into a given number of leaves. More...
class  LexicoSorting
class  MultiTreeManager
 A class which can look into the state space of SPSnode trees. More...
class  NodeCompObj
 A Virtual class providing a way to compare spsnodes. More...
class  CompCount
 Class comparing on count of data points associated with a node. More...
class  CompVol
 Class comparing on volume of box of node. More...
class  CompHeight
 Class comparing on count/volume (ie histogram height) of box of node. More...
class  CompEMPSumChangeCOPERR
 Class comparing change in EMP under COPERR from splitting 2 nodes. More...
class  CompEMPSumChangeAIC
 Class comparing change in EMP under AIC from splitting 2 nodes. More...
class  CompEMPSumChangeMergeCOPERR
 Class comparing change in EMP under COPERR from merging 2 nodes. More...
class  CompEMPSumChangeMergeAIC
 Class comparing change in EMP under AIC from merging 2 nodes. More...
class  CompVolMassMinus
 Class comparing volume * (1- empirical mass). More...
class  CompVolMassMinusAdj
class  CompNothing
 Class comparing nodes to give no change in ordering. More...
class  PiecewiseConstantFunction
 A wrapper or manager for an RealMappedSPnode tree representing a piecewise constant function. More...
class  PolygonPiecewiseConstantFunction
 A wrapper or manager for a collection of RealMappedShapeNodes representing a polygon 'paving' with real values mapped to each polygon-shaped piece in the 'paving'. More...
class  RangeCollectionHist
class  RealEstimator
class  RealKDEMidEstimator
 An estimator for a Kernel Density Estimate that estimates the kde on a box as the kde evaluated at the mid-point of the box. More...
class  RealPointwiseFunctionEstimator
class  RealExpanderEstimator
class  RealMappedShapeNode
 RealMappedShapeNodes are nodes in the representation of a non-regular non-rectangular non-axis aligned polygon-paving ("shape") as a binary tree, with each node having a real value mapped to it. More...
class  RealMappedSPnode
 A derived class based on MappedSPnode < cxsc::real >. More...
class  SPCheckVisitor
class  SplittableCheck
 A type that visits SPnodes to check if they are splittable. More...
class  IntervalImageToleranceCheck
 A type that visits SPnodes to check if they meet an interval image tolerance requirement. More...
class  ReimannDiffToleranceCheck
 A type that visits SPnodes to check if they meet a 'Reimann Difference' tolerance requirement. More...
class  SPExpandVisitor
class  SPValueVisitor
class  SpatialObjectRepresentationBV
 A wrapper or manager for an BooleanValueMappedSPnode tree representing a spatial object. More...
class  SplitDecisionObj
 A Virtual class providing decisions on whether to split spsnodes. More...
class  SplitOnK
 Classes derived from SplitDecisionObj. More...
class  SplitOnVolDivK
 Class for splitting based on average volume per point of a node. More...
class  SplitNever
 Class for never splitting. More...
class  SPMinimalnode
 SPMinimalnodes are nodes in the representation of a subpaving as a minimal binary tree. More...
class  SPnode
 SPnodes are nodes in the representation of a subpaving as a binary tree. More...
class  SPnodeVisitor
class  SPSnode
 A derived class based on SPnode for processing sample data. More...
class  SPSNodeMeasure
 A virtual class providing a way to measure spsnodes. More...
class  SPSNodeMeasureCount
 Class measuring count of data points associated with a node. More...
class  SPSNodeMeasureVol
 Class comparing on volume of box of node. More...
class  SPSNodeMeasureHeight
 Class measuring count/volume (ie histogram height) of box of node. More...
class  SPSNodeMeasureEMPSumChangeCOPERR
 Class measuring change in EMP under COPERR from splitting 2 nodes. More...
class  SPSNodeMeasureEMPSumChangeAIC
 Class measuring change in EMP under AIC from splitting 2 nodes. More...
class  SPSNodeMeasureEMPSumChangeMergeCOPERR
 Class measuring change in EMP under COPERR from merging 2 nodes. More...
class  SPSNodeMeasureEMPSumChangeMergeAIC
 Class measuring change in EMP under AIC from merging 2 nodes. More...
class  SPSNodeMeasureVolMassMinus
 Class comparing volume * (1- empirical mass). More...
class  SPSNodeMeasureChildDifferential
 Class measuring biggest absolute difference in prospective child counts if split. More...
class  SPSNodeMeasureNothing
 Class measuring nodes to give no change in ordering. More...
struct  RvecComp
 A struct for comparing rvectors. More...
class  IO_Error
class  NullSubpavingPointer_Error
class  NoBox_Error
class  MalconstructedBox_Error
class  IncompatibleDimensions_Error
class  IncompatibleLabel_Error
class  NonRootNode_Error
class  UnfulfillableRequest_Error
class  GaussianFobj
class  UniformFobj

Typedefs

typedef std::map< IntVec, int,
LexicoSorting< IntVec > > 
OrdLeafDepthsMap
typedef SPnodeSubPaving
 SubPaving is an alias for a pointer to an SPnode.
typedef SPSnodeStatsSubPaving
 StatsSubPaving is an alias for a pointer to an SPSnode.
typedef SPMinimalnodeMinimalSubPaving
 MinimalSubPaving is an alias for a pointer to a SPMinimalnode.
Typedefs for function pointers.
typedef BOOL_INTERVAL(* PIBT )(const ivector &x, const SPMinimalnode *const spn)
 Define type "Pointer to an interval boolean test".
typedef ivector(* PIVF )(const ivector &x)
 Define type "Pointer to an interval vector function".
Typedefs for containers and iterators.
typedef std::vector< int > IntVec
 Define type IntVec as a container for ints.
typedef IntVec::iterator IntVecItr
 Define type IntVecItr as iterator over IntVec.
typedef std::vector< size_t > Size_tVec
 Define type Size_tVec as a container for size_t.
typedef Size_tVec::iterator Size_tVecItr
 Define type Size_tVecItr as iterator over Size_tVec.
typedef std::vector< real > RealVec
 Define type RealVec as a container for reals.
typedef RealVec::iterator RealVecItr
 Define type RealVecItr as iterator over RealVec.
typedef std::vector< double > VecDbl
 Define type VecDbl as a container of doubles.
typedef VecDbl::iterator VecDblIt
 Define type VecDblIt as an iterator over VecDbl.
typedef std::vector< rvector > RVecData
 Define type RVecData as a container for rvectors.
typedef RVecData::const_iterator RVecDataCItr
 Define type RVecDataCItr as const_iterator over RVecData.
typedef RVecData::iterator RVecDataItr
 Define type RVecDataItr as iterator over RVecData.
typedef std::vector< SPnode * > SPnodePtrs
 Define type SPnodePtrs as container of pointers to SPnodes.
typedef SPnodePtrs::iterator SPnodePtrsItr
 Define type SPnodePtrsItr as an iterator over SPnodePtrs.
typedef std::vector< const
SPnode * > 
SPnodeConstPtrs
 Define type SPnodeConstPtrs as container of pointers to const SPnodes.
typedef
SPnodeConstPtrs::const_iterator 
SPnodeConstPtrsItr
 Define type SPnodeConstPtrsItr as an iterator over SPnodeConstPtrs.
typedef std::vector
< SPMinimalnode * > 
SPMinimalnodePtrs
 Define type SPMinimalnodePtrs as container of pointers to SPMinimalnodes.
typedef SPMinimalnodePtrs::iterator SPMinimalnodePtrsItr
 Define type SPMinimalnodePtrsItr as an iterator over SPMinimalnodePtrs.
typedef std::vector< ivector > BoxVec
 Define type BoxVec as a container of boxes.
typedef BoxVec::iterator BoxVecItr
 Define type BoxVecItr as iterator over BoxVec.
typedef std::list< ivector > ImageList
 Define type ImageList as a container for images of boxes.
typedef ImageList::iterator ImageListItr
 Define type iterator over ImageList.
typedef std::vector< SPSnode * > SPSnodePtrs
 Define type SPSnodePtrs as container of pointers to SPSnodes.
typedef SPSnodePtrs::iterator SPSnodePtrsItr
 Define type SPSnodePtrsItr as an iterator over SPSnodePtrs.
typedef std::vector< const
SPSnode * > 
SPSnodeConstPtrs
 Define type SPSnodeConstPtrs as container of pointers to const SPSnodes.
typedef
SPSnodeConstPtrs::const_iterator 
SPSnodeConstPtrsItr
 Define type SPSnodeConstPtrsItr as an iterator over SPSnodeConstPtrs.
typedef std::list< SPSnode * > SPSnodeList
 Define type SPSnodeList as a list of pointers to SPSnodes.
typedef SPSnodeList::iterator SPSnodeListItr
 Define type SPSnodeListItr as an iterator over SPSnodeList.
typedef std::vector
< CollatorSPnode * > 
CollatorSPnodePtrs
 Define type CollatorSPnodePtrs as container of pointers. to CollatorSPnodes.
typedef
CollatorSPnodePtrs::iterator 
CollatorSPnodePtrsItr
 Define type CollatorSPnodePtrsItr as an iterator over CollatorSPnodePtrs.
typedef std::list< rvector > BigDataCollection
 Define type BigData Collection as a container for data.
typedef BigDataCollection::iterator BigDataItr
 Define type BigDataItr as an iterator BigData.
typedef
BigDataCollection::const_iterator 
BigDataConstItr
 Define type BigDataItr as a BigData const iterator.
typedef std::vector< BigDataItrNodeData
 Define type NodeData as a container for iterators a BigData.
typedef NodeData::iterator NodeDataItr
 Define type NodeDataItr as a NodeData iterator.
typedef NodeData::const_iterator NodeDataConstItr
 Define type NodeDataConstItr as a NodeData const iterator.
typedef std::vector< dotprecision > VecDotPrec
 Define type VecDotPrec as a container of cxsc dotprecision variables.
typedef VecDotPrec::iterator VecDotPrecIt
 Define type VecDotPrecIt as an iterator over VecDotPrec container.

Enumerations

enum  AUTO_TYPE { LEAVES_CRIT = 1, L1_CRIT = 2, DBL_CRIT = 3 }
Typedefs for enums.
enum  BOOL_INTERVAL { BI_TRUE, BI_FALSE, BI_INDET }
 Define type "Interval Booleans". More...
enum  OPERATIONS_ON { ON_LEFT = -1, ON_RIGHT = 1, ON_PARENT = 0 }
 Define a type OPERATION_ON. More...
enum  LOGGING_LEVEL {
  NOLOG = 0, TXT = 1, TXTANDGRAPH = 2, GRAPHSAMPLES = 3,
  LOGSAMPLES = 4, LOGANDGRAPHSAMPLES = 5, LOGSTATETRACE = 6, LOGMCMCTRACE = 7
}
 Define a type LOGGING_LEVEL. More...

Functions

std::ostream & operator<< (std::ostream &os, const subpavings::AdaptiveHistogram &adh)
 Output the contents of an AdaptiveHistogram object.
std::ostream & operator<< (std::ostream &os, const AdaptiveHistogramCollator &adhc)
 Output the contents of an AdaptiveHistogramCollator object.
std::ostream & operator<< (std::ostream &os, const BooleanMappedValue &bv)
 Output the contents of an BooleanValue object.
std::ostream & operator<< (std::ostream &os, const CollatorSPnode &spn)
 Output operator for CollatorSPnodes.
bool nodeCompTotalRangeCollection (const CollatorSPnode *const lhs, const CollatorSPnode *const rhs)
 Comparison of CollatorSPnodes using total of range collection.
std::ostream & operator<< (std::ostream &os, const subpavings::FunctionEstimatorInterval &fei)
 Output the contents of an FunctionEstimatorInterval object.
std::ostream & operator<< (std::ostream &os, const subpavings::FunctionEstimatorKDE &fek)
 Output the contents of an FunctionEstimatorKDE object.
std::ostream & operator<< (std::ostream &os, const subpavings::FunctionEstimatorReal &fei)
 Output the contents of an FunctionEstimatorReal object.
std::ostream & operator<< (std::ostream &os, const subpavings::FunctionImageEstimatorBooleanValue &fei)
 Output the contents of an FunctionImageEstimatorBooleanValue object.
std::ostream & operator<< (std::ostream &os, const subpavings::PiecewiseConstantFunction &pcf)
 Output the contents of an PiecewiseConstantFunction object.
std::ostream & operator<< (std::ostream &os, const subpavings::PolygonPiecewiseConstantFunction &ppcf)
 Output the contents of an PolygonPiecewiseConstantFunction object.
std::ostream & operator<< (std::ostream &os, const RealMappedShapeNode &spn)
 Output the contents of a SubPaving.
bool nodePtrCompare (const subpavings::RealMappedSPnode *lhs, const subpavings::RealMappedSPnode *rhs)
 Less-than operator using pointers.
void Mince (SPnode *const spn, double eps)
 Mince up a subpaving.
void Evaluate (PIVF f, const SPnode *const spn, ImageList &evalImages, ivector &hull)
 Evaluates images of subpaving.
void Expand (SPnode *const spn)
 Expand a leaf node to have two child nodes.
void Expand (SPnode *const spn, int comp)
 Expand a leaf node to have two child nodes.
std::ostream & operator<< (std::ostream &os, const subpavings::SpatialObjectRepresentationBV &pcf)
 Output the contents of an SpatialObjectRepresentationBV object.
BOOL_INTERVAL operator<= (const ivector &z, const SPMinimalnode *const spmn)
 Check for containment of interval vector in the SubPaving.
std::ostream & operator<< (std::ostream &os, const SPnode &spn)
 Output the contents of a SubPaving.
bool isEmpty (const SPnode *const spn)
 Check if a SubPaving is empty.
bool isLeaf (const SPnode *const spn)
 Check if a node is a leaf.
double spVolume (const SPnode *const spn)
 Get the volume of the subpaving represented by spn.
size_t spLeaves (const SPnode *const spn)
 Get the number of leaves of a tree (boxes in the subpaving).
template<typename T >
T * Reunite (T *lChild, T *rChild, ivector x)
 Tries to reunite two nodes to form a single leaf.
template<typename T >
T * Adopt (T *lChild, T *rChild, ivector x)
 Adopt nodes to build a non-minimal subpaving.
template<typename T >
T * Regularize (ivector &hull, ImageList &ivectorList, double eps)
 Forms a minimal image subpaving.
template<typename T >
T * RegularizeNonMinimal (ivector &hull, ImageList &ivectorList, double eps)
 Forms a non-minimal image subpaving.
std::string getUniqueFilename (const std::string &baseFileName, const std::string &suffix=".txt")
 Construct a unique filename from base and timestamp number.
std::string getPidFilename (const std::string &baseFileName, const std::string &suffix=".txt")
 Construct a filename from base and process ID (PID).
void outputFile (const std::string &s, const std::string &line, bool append=true)
 Append a line to a txt file.
void outputFileString (const std::string &s, const std::string &line, bool append=true)
 Append a string to a txt file.
void outputFileStart (const std::string &s)
 Opening line of a txt log file.
std::string stripPath (const std::string &filename)
 Strip the path from a filename.
void outputFile (const std::string &s, subpavings::RealVec &vals, int i)
 Append a tab delimited seq of values as a line in log file.
void outputFile (const std::string &s, RealVec &vals, int i, int nodeType, int accepted, size_t nCount)
 Append a tab delimited seq of values as a line in log file.
void outputFile (const std::string &s, int i, int val)
 Append a value to a log file.
void outputFile (const std::string &s, int i, size_t val)
 Append a value to a log file.
void outputFile (const std::string &s, const std::string &intro, subpavings::RealVec &vals)
 Append a tab delimited list seq of values as a line in log file.
void outputFile (const std::string &s, std::vector< std::string > &strings, int i)
 Append a tab delimited list seq of strings as a line in log file.
bool parseForGraphDot (const std::string &s, std::string toParse)
 Parse a string to make lines for a dot graph.
void makeDotImage (const std::string &s)
 make a Dot graph png image given a dot file.
int countLinesInTxt (const std::string &s, const size_t headerlines=0)
 Method to count lines of data in a txt file.
cxsc::ivector makeBox (const RVecData &theData, int dim, cxsc::real padding)
 Make a box to contain all the data in a collection.
bool checkBox (const cxsc::ivector &box)
bool volCompare (const ivector &a, const ivector &b)
 A function for comparing ivectors based on volume.
real tryExp (real r)
 Work arround for c-xsc math library for exponentiation of reals.
rvector makeDoubleIntoRvector (const double d)
 Make a double into an rvector.
std::string & reformatLine (std::string &line)
 Reformat a line to be suitable for reading into an rvector.
bool checkString (const std::string &s)
 A quick check on a data string: expecting only numbers white space or decimal points.
int countNumbers (const std::string &s)
 Find the number of 'blocks' of numbers in a string of numbers.
void lineErrorLogger (const std::string &line, int lineNumber)
 Log an error from reading in data.
cxsc::rvector & readRV (cxsc::rvector &r, const std::string &line)
 Read an rvector in from a string.
cxsc::rvector & readRV (cxsc::rvector &r, const std::string &line, const std::vector< int > &reqDims, int lineDim)
 Read specified elements from a string into an rvector.
bool _readRvectorsFromTxt (subpavings::RVecData &theData, const std::string &s, std::size_t headerlines, int checkLevel, const std::vector< int > &reqDims, int dim=-1)
 Get rvectors from text.
size_t getRvectorsFromRVec (subpavings::RVecData &theData, const subpavings::RVecData &inputData, bool checkDims=false)
 Get rvectors from a container of rvectors.
size_t getSampleRvectorsFromRVec (subpavings::RVecData &data, gsl_rng *rgsl, size_t samplesize, const subpavings::RVecData &rvec)
 Get a sample of rvectors from an a container.
size_t getSampleRvectorsFromRSSample (subpavings::RVecData &data, gsl_rng *rgsl, size_t samplesize, const RSSample &rss, int label)
 Get a sample of rvectors from an RSSample object.
size_t getRvectorsFromRSSample (subpavings::RVecData &data, const RSSample &rss, int label)
 Get all rvectors from an RSSample object.
size_t getRvectorsFromRSSampleForSampling (subpavings::RVecData &allData, subpavings::RVecData &sampleData, size_t samplesize, const RSSample &rss, int label)
 Get data from an RSSample object to take samples from.
void getSampleFromContainer (size_t samplesize, gsl_rng *rgsl, const subpavings::RVecData &allData, subpavings::RVecData &sampleData)
 Get a sample from data in a container.
bool readVecRealVecFromTxt (std::vector< subpavings::RealVec > &theData, const std::string &s, std::size_t headerlines, int dims=0)
 Read from a txt file into a container of containers of reals.
void outputToFileVertical (std::vector< const subpavings::RealVec * > &dataPtrs, const std::vector< std::string > &colNames, const std::string &filename, int prec=5)
 Output multiple containers of data in vertical format.
void outputToFileVertical (const std::vector< size_t > &lhsLines, std::vector< const subpavings::RealVec * > &dataPtrs, const std::vector< std::string > &colNames, const std::string &filename, int prec)
 Output multiple containers of data in vertical format.
void outputToFileVertical (std::vector< const subpavings::Size_tVec * > &dataPtrs, const std::vector< std::string > &colNames, const std::string &filename)
 Output multiple containers of data in vertical format.
void outputToFileVertical (std::vector< const subpavings::Size_tVec * > &sizePtrs, std::vector< const subpavings::RealVec * > &realPtrs, const std::vector< std::string > &colNamesSize, const std::vector< std::string > &colNamesReal, const std::string &filename, int prec=5)
 Output multiple containers of data in vertical format.
void outputToFileVertical (std::vector< const subpavings::Size_tVec * > &sizePtrs, std::vector< const subpavings::RealVec * > &realPtrs, const std::string &filename, size_t startPos, int prec)
 Add output multiple containers of data in vertical format to an existing file.
void outputToFileVertical (std::vector< const subpavings::RealVec * > &realPtrs, const std::string &filename, size_t startPos, int prec)
 Add output from multiple containers of data in vertical format to an existing file.
std::vector< const
subpavings::RealVec * > & 
addDataPtrs (std::vector< const subpavings::RealVec * > &container, const std::vector< subpavings::RealVec > &toAdd)
 Add a pointer to a container to a container of pointers.
std::map< rvector, size_t,
subpavings::RvecComp > & 
pointMassFilter (const subpavings::RVecData &theData, std::map< rvector, size_t, subpavings::RvecComp > &countsMap)
 Create a map of counts of points in an rvector.
RSSamplelabelDataFromFilter (RSSample &labData, const std::map< rvector, size_t, subpavings::RvecComp > &countsMap, int uniqueLabel, int ptMassLabel)
 Label data from a filter.
double makeEMFMap (std::map< rvector, double, subpavings::RvecComp > &EMFMap, const std::map< rvector, size_t, subpavings::RvecComp > &countsMap)
 Make an empirical mass filter map.
std::pair< cxsc::real, cxsc::real > calcMeanAndSD (const RealVec &vec)
 Calculate mean and sample standard deviation from vec.
IntVec parseSpacings (string line, IntVec &spacings)
 parse a .vtk header line for spacings data.
bool findBlack (string line, string seek)
 Look for a black marker in a line from a .vtk file.
IntVec getCoordinatesFromVtk (IntVec &Xs, IntVec &Ys, IntVec &Zs, const string &s)
 Get coordinates from a .vtk file.
cxsc::rvector & operator/= (cxsc::rvector &a, const cxsc::rvector &b)
cxsc::rvector operator/ (const cxsc::rvector &a, const cxsc::rvector &b)
cxsc::real getEstLogLikelihoodFromRSSample (const subpavings::AdaptiveHistogramCollator &adh, RSSample &labSampledData, double dx, double wt, double weightHist, const std::map< cxsc::rvector, double, subpavings::RvecComp > &emfMap, int ptMassLabel)
cxsc::real newGetEstLogLikelihoodFromSample (const subpavings::AdaptiveHistogramCollator &adh, const RVecData &sample, double dx, double wt, double weightHist, const std::map< cxsc::rvector, double, subpavings::RvecComp > &emfMap)
void outputCovNodes (const subpavings::AdaptiveHistogramCollator &coll, double covForHist, const std::string &covFileName)
void getHistsAndPtMassInfo (std::vector< subpavings::AdaptiveHistogramCollator > &vecMCMCHist, std::vector< std::map< cxsc::rvector, double, subpavings::RvecComp > > &emfMapVec, std::vector< double > &weightPM, const std::vector< RVecData > &unlabDataVec, int uniqueLabel, int ptMassLabel, const std::string &dirName, int dataDim, const cxsc::ivector &pavingBox, int maxLoops, int samplesNeeded, int thinout, int minPoints, long mcmcSeed, const subpavings::RealVec &tols, subpavings::AUTO_TYPE auto_type)
subpavings::RVecDatagetSampleWithoutReplacement (subpavings::RVecData &sample, const subpavings::RVecData &source, const gsl_rng *r, std::size_t samplingSize)
bool outputSample (const RVecData &sample, const std::string &fileName)
bool outputEMFMap (const std::map< cxsc::rvector, double, subpavings::RvecComp > &emfMap, const std::string &fileName)
bool outputLogLikelihoodMatrix (const std::vector< subpavings::RealVec > &mat, const std::string &fileName)
bool checkNodeCountForSplit (const subpavings::SPSnode *const spn, size_t minChildPoints)
 Method to do checking for whether a node is splittable.
bool histCollatorBoxContains (const subpavings::AdaptiveHistogramCollator &adh, const cxsc::rvector &pt)
std::vector< const
subpavings::CollatorSPnode * > & 
findDensityRegion (const subpavings::AdaptiveHistogramCollator &adh, std::vector< const subpavings::CollatorSPnode * > &covNodes, double cov)
subpavings::AdaptiveHistogramCollator doMCMCGRAutoLeaves (std::vector< subpavings::AdaptiveHistogram * > hists, const std::string &dirName, int maxLoops, int samplesNeeded, int thinout, int minPoints, long thisSeed, const subpavings::RealVec &tols)
subpavings::AdaptiveHistogramCollator doMCMCGRAutoL1 (std::vector< subpavings::AdaptiveHistogram * > hists, const std::string &dirName, int maxLoops, int samplesNeeded, int thinout, int minPoints, long thisSeed, const subpavings::RealVec &tols)
subpavings::AdaptiveHistogramCollator doMCMCGRAutoDblHurdle (std::vector< subpavings::AdaptiveHistogram * > hists, const std::string &dirName, int maxLoops, int samplesNeeded, int thinout, int minPoints, long thisSeed, const subpavings::RealVec &tols)
Make a box to contain all the data in a collection.

The box is made to fit all of the data in theData, with padding padding around the minimums and maximums of the data on each dimension.

Parameters:
theDataa reference to a container of rvector data.
paddingthe padding to put around the minimums and maximums of the data in theData.
Returns:
an ivector same dimensions as the data and to fit all the data including an allowance for padding.
Precondition:
theData is not empty.
cxsc::ivector makeBox (const RVecData &theData, cxsc::real padding)
cxsc::ivector makeBox (const std::vector< std::vector< double > > &theData, cxsc::real padding)
Routines to read in rvectors from a txt file and

store in a given data container theData.

Reads in lines of data representing rvectors from a txt file. The dimensions of the data may given or may be deduced from existing data in theData or from the data in the file.

Expects one line per rvector with the elements separated by white space (space or tabs), or by commas.

Input files can be checked to try to ensure data conforms with some given dimensions and/or has no illegal characters.

Illegal characters are any characters other than those in the string "eE+-.,0123456789 \\t".

Note that this allows numbers in scientific format, and with space, tab, or comma delimiters. However, allowing the characters 'e' and 'E' as part of scientific format, and the delimiters, also allows the possibility that these are erroneously present. The level of checking for illegal characters is not rigorous and will not pick up the inadvertent or erroneous presence of these non-numeric characters. This includes the presence of delimiters before the first numeric character, which may result in 0.0 being inserted into the first dimension(s) of the rvector read from the relevant data line.

Ordinary checking means that:

  • The first valid line is checked against the given data dimensions if any. Oherwise the first valid data line is used to find data dimensions.
  • If data dimensions are given and the dimensions found in the first valid data line are less than those given dimensions, an error message is given and reading of all data is aborted. Any data in excess of the given dimensions will however just be ignored.
  • The first valid data line, as described above, is the first line after the given headers not containing illegal characters. All lines after that are also checked to ensure that they do not contain illegal characters.

Note that under ordinary checking, data lines after the first valid line are not checked to ensure that they conform to expected dimensions: data in excess of the given dimensions will be ignored and 'missing' dimensions will be padded with 0.0's.

Paranoid checking means that expected data dimensions must be given and checking is carried out as for Ordinary checking plus further checking:

  • All lines after the first valid data line are also checked to to check that the number of blocks of numbers is equal to the expected dimensions.

Fast checking effectively means no checking (fast reading of data). Data is assumed to conform to the given dimensions: data in excess of the given dimensions will be ignored and all data lines which are less than the given dimensions will result in an rvector "padded" with 0.0 in the additional dimensions. Illegal characters in the input, including initial delimiters before the first numeric values, may be interpreted as part of a real vector, or as delimiters, or ignored. No guarantees are given about the resulting data read in if the data does not conform to the values given for the parameters for headerlines and data dimensions.

While reading of the file continues (has not been aborted, for example because the dimension of the data does not seem to be as expected) , input lines which do not pass checks are rejected and logged but the rest of the file will continue to be processed and valid lines converted to rvectors to be stored in theData.

Blank lines are ignored.

These routines will work if theData it is not empty, provided that if dim is given, this matches the dimensions of the existing data.

If no data dimension is specified by the user (dim = -1), then the routine will attempt to find it. If there is existing data in theData, the expected dimension dim will be taken as the dimension of the first element in theData. If theData is empty, the expected dimension dim will be taken as the dimension of the first valid data line read in from the file.

Throws an invalid_argument exception if dim is supplied by the user and dim < 1.

Throws an invalid_argument exception if there is existing data in theData and the dimensions of this data are < 1.

Parameters:
theDatais a reference to a container of data into which to place the data once read.
sis the name of the txt file from which to read the data.
headerlinesis number of headerlines to skip before reading data.
dimexpected data dimension.
Returns:
true if at least some data was read in, else false (if the file could not be opened, if the file contained no data, or if no valid data was found in the file).
Precondition:
A file with filename s (s can include path and name), if dim is supplied then dim >= 1, and if there is existing data in theData, the dimensions of that data are >= 1.
Postcondition:
The container theData contains all data that it contained before the operation and the valid rvectors read in.
Todo:
Even paranoid checking does not check that the text can be properly represented in floating point format. See "C++ Toolbox for Verified Computing" book pp. 46-50.
bool readRvectorsFromTxtOrd (subpavings::RVecData &theData, const std::string &s, std::size_t headerlines, int dim)
 Read in rvectors from a txt file with Ordinary level checking, with data dimensions given.
bool readRvectorsFromTxtOrd (subpavings::RVecData &theData, const std::string &s, std::size_t headerlines=0)
 Read in rvectors from a txt file with Ordinary level checking.
bool readRvectorsFromTxtOrd (subpavings::RVecData &theData, const std::string &s, const std::vector< int > &reqDims, std::size_t headerlines=0)
 Read in rvectors from a txt file with Ordinary level checking.
bool readRvectorsFromTxtParanoid (subpavings::RVecData &theData, const std::string &s, std::size_t headerlines, int dim)
 Read in rvectors from a txt file with Paranoid level checking.
bool readRvectorsFromTxtParanoid (subpavings::RVecData &theData, const std::string &s, const std::vector< int > &reqDims, std::size_t headerlines)
 Read in rvectors from a txt file with Paranoid level checking.
bool readRvectorsFromTxtFast (subpavings::RVecData &theData, const std::string &s, std::size_t headerlines, int dim)
 Read in rvectors from a txt file with Fast level checking.
Read in rvectors from a vector of vectors of doubles.

Reads in vectors of doubles, representing rvectors, from a std::vector. The dimensions of the rvector can be given or (if dim is not given) deduced from existing data in theData or from the first vector in the input vector inputData.

The rest of the data then is expected to have the same dimension as that given or found from the frst vector in the input vector. Any data with dimensions less than the expected dimensions will be rejected. If data has more than the expected dimensions, only the values on the first expected dimensions will be read in (the rest will be ignored).

Expects one inner vector per rvector.

If the container theData is not empty this will work provided that the expected data dimension is the same as the existing data has the same dimension as the existing data (if dim is not specified by the user and there is no existing data, then the expected data dimension will have been found from the first element in the input vector inputData)

Throws an invalid_argument exception if dim is supplied by the user and dim < 1.

Throws an invalid_argument exception if there is existing data in theData and the dimensions of this data are < 1.

Parameters:
theDatais a reference to a container of data into which to place the data once read.
inputDatais the vector of vectors of doubles to be input.
dimis the dimensions of the data to expect. If dim = -1 then the method will try to establish the dimensions from the first data point in the inputData.
Returns:
true if at least some data was put into theData, false otherwise.
Precondition:
If dim is supplied then dim >= 1, and if there is existing data in theData, the dimensions of that data are >= 1.
Postcondition:
The container theData contains all data that it contained before the operation and the valid rvectors read in.
bool getRvectorsFromVectorOfVecDbl (subpavings::RVecData &theData, const std::vector< subpavings::VecDbl > &inputData)
 Version with no expected dimensions specified.
bool getRvectorsFromVectorOfVecDbl (subpavings::RVecData &theData, const std::vector< subpavings::VecDbl > &inputData, int dim)
 Version with expected dimensions specified by user.
bool _getRvectorsFromVectorOfVecDbl (subpavings::RVecData &theData, const std::vector< subpavings::VecDbl > &inputData, int dim=-1)
 Internal version: use getRvectorsFromVectorOfVecDbl rather than this.
std::ostream & operator<< (std::ostream &os, const subpavings::IntVec &vec)
 Output the contents of a collection.
String representations of collections.

Formatted to have ", " or "," (compact = true) between the elements of the collection.

Parameters:
vecthe collection to describe in the output.
compactindicator for whether format should be compact.
Returns:
string representation of vecints.
std::string toString (const subpavings::IntVec vec, bool compact=false)
 String representation of an IntVec.

Detailed Description

An abstract class for target function objects.

The namespace subpavings.

A class for range collections for histograms.

An abstract class for target function objects on 2-dimensional real space.

An abstract class for target function objects on 1-dimensional real space.

The underlying container should be some kind of sequence container.

This implementation uses an stl::vector as the implementation container

The namespace is used for all classes and non-member methods related to subpavings.


Typedef Documentation

typedef std::list<rvector> subpavings::BigDataCollection

Define type BigData Collection as a container for data.

Used in HistogramWrappers and SPSnode as the container for sample data. This container must not be vulnerable to iterator, pointer and reference invalidation. std::list has been chosen because it is a node-based container. The disadvantages of std::list is that it is heavy on memory because of the need to maintain pointers to other members, and it does not offer a random access iterator.

typedef std::list<ivector> subpavings::ImageList

Define type ImageList as a container for images of boxes.

Used in Evaluate() for list of function images.

typedef std::vector<BigDataItr> subpavings::NodeData

Define type NodeData as a container for iterators a BigData.

Used by SPSnode to hold iterators to the data associated with node.

typedef BOOL_INTERVAL(* subpavings::PIBT)(const ivector &x, const SPMinimalnode *const spn)

Define type "Pointer to an interval boolean test".

The test is for containment of the inclusion function image of an ivector in a minimal subpaving. The inclusion function is specified in the body of the interval boolean test function. The test returns BI_INDET if the inclusion function image overlaps the subpaving border.

Parameters:
xthe interval vector whose image is found and compared to the subpaving.
spna pointer to the node representing a subpaving we want to test for containment in. This parameter is added to the AIASPnode::(*AIA_PIBT) to replace the use of globals there.
typedef ivector(* subpavings::PIVF)(const ivector &x)

Define type "Pointer to an interval vector function".

PIVF is an interval vector inclusion function, ie a function which returns the interval vector which encloses f(x) for f as specified in the function and x given in the function parameter.

typedef std::vector<dotprecision> subpavings::VecDotPrec

Define type VecDotPrec as a container of cxsc dotprecision variables.

Can be used to hold accumulators for rvector elements. Used to hold representations of the sum of data points on each of the relevant dimensions.

typedef VecDotPrec::iterator subpavings::VecDotPrecIt

Define type VecDotPrecIt as an iterator over VecDotPrec container.


Enumeration Type Documentation

Define type "Interval Booleans".

This is used to extend the usual booleans TRUE and FALSE for use with intervals. With intervals the result of a test may be indeterminate at a particular level of accuracy rather than clearly true or false.

{BI_TRUE,BI_FALSE,BI_INDET} BOOL_INTERVAL;

Define a type LOGGING_LEVEL.

This is used to determine the type of logging output.

  • NOLOG should be obvious.
  • TXT for logging quite extensive txt files (pq and mcmc).
  • GRAPHSAMPLES to graph mcmc samples.
  • LOGSAMPLES to send each mcmc sample to a log file.
  • LOGANDGRAPHSAMPLES for both of the above.
  • LOGSTATETRACE to log leaf trace and log posterior trace for mcmc states.
  • LOGMCMCTRACE to log leaf trace and log posterior trace for mcmc states and also the leaf trace and log posterior for the sample average.
                {NOLOG = 0, TXT = 1, TXTANDGRAPH = 2, GRAPHSAMPLES = 3,
                LOGSAMPLES = 4, LOGANDGRAPHSAMPLES = 5, 
        LOGSTATETRACE = 6, LOGMCMCTRACE = 7} LOGGING_LEVEL;

Define a type OPERATION_ON.

This is used in SPSnode to indicate whether an operation is on a parent node or on the left or right child of a parent.

{ON_LEFT = -1, ON_RIGHT = 1, ON_PARENT = 0} OPERATIONS_ON;

Function Documentation

bool subpavings::_readRvectorsFromTxt ( subpavings::RVecData theData,
const std::string &  s,
std::size_t  headerlines,
int  checkLevel,
const std::vector< int > &  reqDims,
int  dim = -1 
)

Get rvectors from text.

Note:
Use getRvectorsFromTxtOrd, or getRvectorsFromTxtParanoid, or getRvectorsFromTxtFast, rather than this.
Parameters:
theDatais a reference to a container of data into which to place the data once read.
sis the name of the txt file from which to read the data.
headerlinesis number of headerlines to skip before reading data.
checkLevelthe level of checking to be carried out.
reqDimsis a container specifying the positions of the required values in the line in the file. If reqDims is empty and dim is not supplied, it will be assumed that all values from a line are required to make one rvector. If reqDims is empty and dim is supplied, it will be assumed that the first dim values from a line of the file are required to make one rvector.
dimexpected data dimension.
Returns:
true if at least some data was read in.
{
  bool retValue = false;
  bool cancontinue = true;
  
  int maxDim = 0;
  
  if (!reqDims.empty()) {
    dim = reqDims.size();
    maxDim = *max_element(reqDims.begin(), reqDims.end());
  }

  if (!theData.empty()) { // data already in theData, 
    std::cout
    //print a warning
      << "Warning: adding to existing data "
      << "- mixing datasets"
      << std::endl;
    
    // and if dim is -1, set dim to be size of existing data
    if (dim < 0) dim =VecLen( (*theData.begin()) );
    if (dim < 1) throw std::invalid_argument(
    "_readRvectorsFromTxt(RVecData&, const std::string&, std::size_t, int, int) : VecLen(*theData.begin()) < 1"); 
  }

  // we can read rvectors as strings in c-xsc format
  // and then convert to rvectors with c-xsc::>>

  //set up the file and read input line by line
  // we need to convert the string argument to a c-string for ifstream
  ifstream dataFile(s.c_str());
  int howMany = 0; // how many datapoints, to be read from file

  // if dim = -1, file will attempt to find it

  string line;
  
  std::streampos filePos = 0; // record where we are in file
  int lineDim = 0;
    
  if (dataFile.is_open())
  {
    std::size_t headers = headerlines;
    // skip headerlines
    while ((headers > 0) && (dataFile.good()) )
    {
      getline (dataFile,line);
      headers--;
    }
    filePos = dataFile.tellg( );
    
    if ( (dim == -1) || checkLevel || !reqDims.empty()) { // try to find dim from file
      // get the first data line from the file
      if (dataFile.good()) {
        
        getline (dataFile,line); 

        // find the number of blocks of numbers in first 
        // line that does not have illegal characters in
        while ( ( line.empty() || !checkString(line) ) && dataFile.good()) { // problem try next line
          filePos = dataFile.tellg( );
          getline(dataFile, line);
        }
        if ( !line.empty() && checkString(line) ) {
          lineDim = countNumbers(line);
          howMany++; // just read a valid line
        }
      }
    }

    if ((dim == -1) && (lineDim == 0)) {     // failed to find a valid line
      std::cerr << "Error in "
        << "_readRvectorsFromTxt: "
        << "could not establish data dimension from file "
        << "- aborting read of file " << s << std::endl;
      dataFile.close();
      cancontinue = false;
    }
    else if ((checkLevel) && (lineDim < dim) ) { 
      // check first valid line matches given dimensions
      std::cerr << "Error in "
        << "_readRvectorsFromTxt: "
        << "data dimensions seems to be < given dimensions "
        << "- aborting read of file " << s << std::endl;
      dataFile.close();
      cancontinue = false;
    }
      
    if (dim == -1) dim = lineDim;
    if (!maxDim) maxDim = dim;
    
    // dim now becomes the number of dimensions we expect
    
    // filePos is at the start of the first valid data line
  }

  else { // dataFile not open
  // todo should have this as our own subpavings io exception 
    std::cerr << "Error in "
      << "_readRvectorsFromTxt."
      << "Unable to open file " << s << std::endl;
    cancontinue = false;
  }

  // need to check we have enough values in the data
  if (cancontinue && !reqDims.empty()) {
    if (lineDim < maxDim) {
      std::cerr << "Error in "
        << "_readRvectorsFromTxt: "
        << "data dimensions seem to be < largest required dimension "
        << "- aborting read of file " << s << std::endl;
      dataFile.close();
      cancontinue = false;
    }
  }

  // if there is already data, check dimensions match
  if (cancontinue && !theData.empty()) {

    //find the data dimensions from the first datapoint
    int dataDim = Ub(*theData.begin()) -
      Lb(*theData.begin()) + 1;
    if (dim != dataDim) {
      std::cerr << "Error in "
        << "_readRvectorsFromTxt: "
        << "Existing data different "
        << "dimension to data to be read in "
        << "- aborting read of file " << s << std::endl;
      dataFile.close();
      cancontinue = false;
    }
  }

  if (cancontinue) {
    // file is still open and we have just read the first valid line, for dims
    // or are positioned at the start, if dims are given
    
    // count remaining lines from here
    
    // count the lines still to go, without checking if they are good
    while (dataFile.good() )
    {
      getline (dataFile,line);
      howMany++;  // count number of lines in the file
    } 
      
    // reserve space in vector, assuming all remaining files will be good 
    theData.reserve(howMany + theData.size());

    dataFile.clear(); // reset the flags on the file
    dataFile.seekg(filePos); // and put file pointer to read first [valid] line

    int countIn = 0;
    int countLines = 0;

    while (dataFile.good() )
    {
      // get from the file line by line
      getline (dataFile, line);

      line = reformatLine(line); 

      countLines++;

      // validity checks only if checkLevel != 0
      if (!line.empty() && (!checkLevel || checkString(line)) ) { // quick validity check

        rvector r(dim); // empty rvector of correct dimension

        // the cxsc insertion operator >> is too forgiving
        // and idiosyncratic.  It will not just fail if the conversion
        // was not perfect, and it produces completely the wrong result if 
        // the final number is an integer not followed by anything
        
        bool proceed = (checkLevel < 2);
        int giveDim = lineDim;
        
        // only check dims using countNumbers if checkLevel >= 2
        if (!proceed) {
          
          giveDim = countNumbers(line);
          proceed = (reqDims.empty() ? (dim == giveDim) : maxDim <= (giveDim));
          
        }
        
        if ( proceed ) {
        
          // work around for the problem of no final decimal place
          // by just adding a space at the end - cxsc is okay with this
          line += " "; 

          if (reqDims.empty()) {
            r = readRV(r, line);
          }
          else {
            r = readRV(r, line, reqDims, giveDim);
          }
          theData.push_back(r);
          countIn++;
        }
        else {  // invalid line, spit out
          lineErrorLogger(line, countLines);
        }
      }
      else if (!line.empty() ) {  // invalid line, spit out
        lineErrorLogger(line, countLines);
      }
    }
    dataFile.close();

    // confirm the amount of data read in
    std::cout << "End of reading data input file: "
      << countIn << " valid data points read in"
      << std::endl;

    if (countIn > 0) retValue = true; // some data successfully read in
  }

  return retValue;
}
std::vector< const subpavings::Size_tVec * > & subpavings::addDataPtrs ( std::vector< const subpavings::RealVec * > &  container,
const std::vector< subpavings::RealVec > &  toAdd 
)

Add a pointer to a container to a container of pointers.

Parameters:
containera reference to a container to add the pointer to.
toAdda reference to the container for which the pointer is to be added to container.
Returns:
a reference to container.
template<typename T >
T* subpavings::Adopt ( T *  lChild,
T *  rChild,
ivector  x 
)

Adopt nodes to build a non-minimal subpaving.

Make a new node and graft the two proposed children on as children.

Parameters:
lChilda pointer to the leftChild node to be adopted
rChilda pointer to the rightChild node to be adopted
xis the box of the new subpaving to be returned
Returns:
a non-minimal subpaving from two sibling subpavings
  {
    T* newNode = NULL; // pointer to new node to be returned

    try {
      newNode = new T(x);


      // both proposed children are empty, return null
      if(isEmpty(lChild) && isEmpty(rChild)) {
        newNode = NULL;
      }

      // add the new right child if there is one
      if (!isEmpty(rChild)) {
        //graft right child on
        newNode->nodeAdoptRight(rChild);
      }

      // add the new left child if there is one
      if (!isEmpty(lChild)) {
        //graft left child on
        newNode->nodeAdoptLeft(lChild);
      }

      return newNode;
    }
    catch(std::exception const& e) {
      delete newNode;
      newNode = NULL;
      throw;
    }
  }
bool subpavings::checkNodeCountForSplit ( const subpavings::SPSnode *const  spn,
size_t  minChildPoints 
)

Method to do checking for whether a node is splittable.

Decides whether a node is splittable based on checking number of points that would result in child nodes on split.

If there is a minChildPoints>0 specified, then either the node must have at least minChildPoints and all the points go to one of the children (the other getting none) or the smallest number of points which would go to the either of the prospective new children must be >= minChildPoints

Thus in general the method will only return true if the given node satisfies test that if it were to be split, both children would have at least minChildPoints data points, but if all the data points would go to one child (none) to the other, this is considered to also satisfy the minChildPoints test.

If the node has already been split, the test will use the actual numbers of points in the children; if the node is a leaf (ie not split) then the test will consider the number of points that would go to the each child if it were to be split.

Parameters:
spnis a pointer to the target node.
minChildPointsis the minimum number of points that there would be in the children if the node were to be split.
Returns:
true if has been a test conditions satisfied, false otherwise.
{
    bool retValue = false;
  
  size_t minChildCount = 0;
  size_t counter = spn->getCounter();
  if (spn->isLeaf()) minChildCount = spn->getMinChildCountIfSplit();
  else {
    size_t lcCount = spn->getLeftChild()->getCounter();
    size_t rcCount = counter - lcCount;
    minChildCount = (lcCount < rcCount ? lcCount : rcCount);
  }
  
  if ((minChildPoints == 0)
            || (minChildPoints > 0
                &&
                ((counter >= minChildPoints) &&
                    ((minChildCount == 0)
                    ||
                    (minChildCount >= minChildPoints))
                ))
        ) { retValue = true; }

    return retValue;
}
bool subpavings::checkString ( const std::string &  s)

A quick check on a data string: expecting only numbers white space or decimal points.

Checks for illegal characters; Used for checking txt file input.

Legal characters are any characters in the string "eE+-.,0123456789 \\t\\r"

Note that legal characters includes dos carriage return '\r'.

For example, a string "12.04 1.00005e-10 -30.0006" contains no illegal characters.

For example, a string "12.04ab 1.00005e-10 -30" has illegal characters 'a' and 'b'.

Parameters:
sa reference to the string to check.
Returns:
true if the string passed the test, false otherwise.
{
  // check for illegals, as anything but numbers, ".", e, E, ",", space or tab or carriage return
  string legal("eE+-.,0123456789 \t\r");
  string numeric("0123456789");
  string carriageRet("\r"); // only at the end
  bool retValue = ( (s.find_first_not_of(legal) == string::npos)
    && (s.find_first_of(numeric) != string::npos));
  
  return retValue;
  // return true there are no illegal characters
}
int subpavings::countLinesInTxt ( const std::string &  s,
const size_t  headerlines = 0 
)

Method to count lines of data in a txt file.

Counts all lines with no data checking. Used for counting lines before setting up an adaptive histogram.

Parameters:
sis the name of the txt file in which to count the lines.
headerlinesis the number of lines to ignore.
Returns:
the number of lines of data, excluding headerlines, in the file.
{
  //set up the file and read input line by line
  // we need to convert the string argument to a c-string for ifstream
  ifstream dataFile(s.c_str());
  string line;    // a string object to use in counting lines
  int howMany = -headerlines; // how many lines in the file

  if (dataFile.is_open())
  {
    // count the lines in the file
    while (dataFile.good() )
    {
      getline (dataFile,line);
      howMany++;  // count the number of lines in file
    }
    dataFile.close();
  }

  else {
    std::cerr << "Error in countLinesInTxt. "
      << "Unable to open file" << std::endl;
    
  }

  return howMany;
}
int subpavings::countNumbers ( const std::string &  s)

Find the number of 'blocks' of numbers in a string of numbers.

A number is identified as a block of characters containing at least one of the characters 0123456789

Blocks of numbers delimited by space ' ', comma ',' or tab '\t'

This function does not check for non-numeric characters, for example, the string "a12.3 2E+03" will be assessed as containing 2 blocks of numbers, "e" will be assessed as containing zero blocks of numbers, "1e" will be assessed as containing one block of numbers, "." will be assessed as containing zero block of numbers, ".0" will be assessed as containing one block of numbers, "a.0" will be assessed as containing one block of numbers.

Parameters:
sa reference to the string to check.
Returns:
the number of 'blocks' of numbers found.
{
  
  int countFound = 0;     // to count the number of finds
  
  // specify what to look for as numbers or decimal point or + or -
  string toFind(".0123456789");
  // and delimiters
  string delimFind(" \t,");
  // and illegals, as anything but numbers, ".", e, =, - space or tab
  //string illegalFind("e+-.0123456789 \t");

  size_t numberFound = s.find_first_of(toFind);    // first toFind
  size_t delimFound = 0;      //  first delimiter after number
  //size_t illegalFound = s.find_first_not_of(illegalFind);// first illegal

  while (numberFound != string::npos && delimFound != string::npos) {
    
    countFound++;
    
    delimFound = s.find_first_of(delimFind, numberFound+1);
    numberFound = s.find_first_of(toFind, delimFound); 
    
  }

  return countFound;
}
void subpavings::Evaluate ( PIVF  f,
const SPnode *const  spn,
ImageList evalImages,
ivector &  hull 
)

Evaluates images of subpaving.

Fills in the list of images using f of the subpaving boxes and update the hull of all the images.

Evaluate is now a non-friend non-member function (compare to AIASPnode::Evaluate()) which now uses public member functions in the SPnode class.

Parameters:
fa pointer to an interval vector function which returns the image box under f of some an interval vector
spnthe node of the subpaving to be evaluated
evalImagesa container of image interval vectors
hullthe interval hull of the image interval vectors
{
  // later on if we want to generalise this,
  // we might have a base Box class and then
  // use list<Box>& evalImages and Box& hull

  if (spn!=NULL && isLeaf(spn)) {
    // get image using PIVF function f on box of this node
    ivector image = f(spn->getBox());

    // if no images in image set yet, make hull the image
    // if are images in image set, hull is convex hull of
    // the current hull and ivector image from f(Box(A))
    if (evalImages.size() == 0) hull = image;
    else hull = (hull | image);

    // add the image to the list of images
    evalImages.push_back(image);
  } // end of is a leaf

  // recurse on children
  if (spn!=NULL && !isLeaf(spn)) {

    Evaluate(f, spn->getLeftChild(), evalImages, hull);
    Evaluate(f, spn->getRightChild(), evalImages, hull);

  } // end of if is not a leaf

  // case where A == NULL does nothing, just returns

  return;

}
void subpavings::Expand ( SPnode *const  spn)

Expand a leaf node to have two child nodes.

Uses nodeExpand method for the type of spn (base/derived) at runtime.

Expand is now a non-friend non-member function (compare to AIASPnode::Expand()) which now uses public member functions in the SPMinimalnode class.

Parameters:
spna pointer to the node to be expanded.
{
  if (spn!=NULL) spn->nodeExpand();
  
}
void subpavings::Expand ( SPnode *const  spn,
int  comp 
)

Expand a leaf node to have two child nodes.

Uses nodeExpand() method for the type of spn (base/derived) at runtime and this nodeExpand() method will find the dimension to split on.

Parameters:
spna pointer to the node to be expanded.
compis the dimension to split on.
{
  if (spn!=NULL) spn->nodeExpand(comp);
  
}
bool subpavings::findBlack ( string  line,
string  seek 
)

Look for a black marker in a line from a .vtk file.

Parameters:
lineis the line to be searched.
seekis the string to look for.
Returns:
true if found.
IntVec subpavings::getCoordinatesFromVtk ( IntVec &  Xs,
IntVec &  Ys,
IntVec &  Zs,
const string &  s 
)

Get coordinates from a .vtk file.

Expects structured point format data.

Parameters:
Xsa container of integers to put x-coordinate data into.
Ysa container of integers to put y-coordinate data into.
Zsa container of integers to put z-coordinate data into.
sthe filename to get the data from.
Precondition:
empty containers for Xs, Ys, Zs and a properly formated file s.
Postcondition:
containers Xs, Ys, Zs filled with coordinate data.
Returns:
a vector of the coordinate spacing in the x, y, z direction.
string subpavings::getPidFilename ( const std::string &  baseFileName,
const std::string &  suffix = ".txt" 
)

Construct a filename from base and process ID (PID).

This does not necessarily give a unique filename, but may be more helpful than getUniqueFilename in matching output files to process provided that only one output file with base filename baseFileName will be generated in one process.

Parameters:
baseFileNamethe base to use as the filename
suffixto put on filename, defaults to ".txt"
Returns:
afilename constructed as baseFileName + PID + suffix.
{
  string s;
  
  ostringstream out;
  out << getpid();
  return (baseFileName + out.str() + suffix);
  
}
size_t subpavings::getRvectorsFromRSSample ( subpavings::RVecData data,
const RSSample rss,
int  label 
)

Get all rvectors from an RSSample object.

Takes the rvector part of labeled points in the Samples data member of an RSS object, where the label on the point matches the label supplied as a function argument.

RSSample objects can have Samples containing points with different labels and points with different labels can have different dimensions.

The container theData is assumed to be empty but this will work even if it is not empty provided that the data added has the same dimension as the existing data, since we are only pushing back: new data will just get put in after the stuff already there.

Parameters:
datais a reference to a container of data into which to place the data once read.
rssis the RSSample object with the data we want.
labelis the label for the points that we want from rss.
Precondition:
A container theData, assumed to be empty, in which to store data. theData should support push_back() method.
Postcondition:
The container theData contains the valid rvectors read in.
Returns:
the number of data points matching label, and matching dimensions data points already in data if any, found in rss.Samples. Returns 0 if no data points with the correct label found or if dimensions did not match existing data points in data.
{

  size_t retValue = 0;
  bool cancontinue = true;

  if (!data.empty()) { // data already in data, print a warning
    std::cout
      << "Warning: adding to existing data "
      << "- mixing datasets"
      << std::endl;

    // assume we will be adding all the data from rss.Samples
    data.reserve((rss.Samples).size() +
              data.size());
  }

  else {
    data.reserve((rss.Samples).size());
  }

  //get the data with the appropriate label out of rss

  // transform would be better but we would have to assume that
  // we wanted all the data in rss.Samples, but we know that
  // an RSSample object can contain samples with with different labels
  // and with different dimensions

  bool foundfirst = false;
  rvector first;

  if (cancontinue) {
    //find the first point with the right label and
    // check dimensions
    vector<LabPnt>::const_iterator cit = rss.Samples.begin();

    while (!foundfirst && (cit<(rss.Samples).end())) {
      if ((*cit).L == label) {
        foundfirst = true;
        first = cit->Pnt;
      }
      cit++;
    }// end while
  }

  if (!foundfirst) { // could not find points with the right label
    std::cout << "Could not find any points in RSSample object "
      << " with the right label - aborting "
      << std::endl;
    cancontinue = false;
  }

  if (cancontinue && !data.empty()) {
    //find the data dimensions from the first datapoint fount
    int dim = Ub(first) - Lb(first) + 1;
    //find the data dimensions from the existing data
    int dataDim = Ub(*data.begin()) - Lb(*data.begin()) + 1;
    if (dim != dataDim) {
      std::cout
        << "Existing data different dimension "
        << " to data in RSSample object - "
        << " aborting"
        << std::endl;
      cancontinue = false;
    }
  }

  // if cancontinue is still true we know there is data we can take

  if (cancontinue) {

    size_t countIn = 0; // track points inserted

    //iterate through the rss.Samples and take points
    //that match the supplied label
    vector<LabPnt>::const_iterator cit;

    for (cit=(rss.Samples).begin();cit<(rss.Samples).end();cit++){
      if (cit->L == label) {
        data.push_back(cit->Pnt);
        countIn++;
      }
    }

    retValue = countIn;    // some data successfully read in
  }

  return retValue;
}
size_t subpavings::getRvectorsFromRSSampleForSampling ( subpavings::RVecData allData,
subpavings::RVecData sampleData,
size_t  samplesize,
const RSSample rss,
int  label 
)

Get data from an RSSample object to take samples from.

Parameters:
allDatais the container to put the all the data found into.
sampleDatais the container which the sample wll eventually go into.
samplesizeis the size of the sampel to be drawn.
rssis the RSSample object to sample data from.
labelis the label for the labeled points we want to find in rss.
Returns:
the number of data points taken as a sample from rss.Samples. Returns 0 if no data points with the correct label found in rss.Samples or if dimensions did not match existing data points in data.
{

  size_t retValue = 0;

  //use getRvectorsFromRSSample to put rvectors from labeled points in
  // rss.Samples into allData where the labeled point label matches label
  size_t numberFound = getRvectorsFromRSSample(allData, rss, label);

  bool cancontinue = (numberFound > 0);
  // cancontinue will be false if there was a problem getting data points
  // if cancontinue is true data should contain at least some data points

  if (cancontinue && (allData.size() < samplesize)) {
    std::cout << "Warning: Sample size required is greater than "
      << allData.size() << " the number of available data points "
      << "matching label " << label << "in the RSSample object's Samples"
      << std::endl;
  }

  // data already in data, print a warning
  if (cancontinue && !sampleData.empty()) {
    std::cout
      << "Warning: adding to existing data "
      << "- mixing datasets"
      << std::endl;

     //find the data dimensions from the first datapoint in allData
    int dim = Ub(*allData.begin()) - Lb(*allData.begin()) + 1;
    //find the data dimensions from the existing data
    int dataDim = Ub(*sampleData.begin()) - Lb(*sampleData.begin()) + 1;
    if (dim != dataDim) {
      std::cout
        << "Existing data different dimension "
        << " to data in RSSample object - aborting" << std::endl;
      cancontinue = false;
    }
  }

  if (cancontinue) {

    retValue = numberFound;    // some data successfully read in
  }

  return retValue;
}
size_t subpavings::getRvectorsFromRVec ( subpavings::RVecData theData,
const subpavings::RVecData inputData,
bool  checkDims = false 
)

Get rvectors from a container of rvectors.

If checkDims == false, appends the entire contents of rvec to the end of data unless the first element in rvec is an empty (0-d) rvector.

If checkDims == true, checks the dimensions of each element in inputData and only add to theData those elements where with dimension equal to that of the first element in inputData .

Aborts with a message to standard error output if there is existing data in theData and the dimensions of the first element of theData do not match the dimensions of the first element of inputData.

Throws an illegal_argument exception if the first element in inputData is an empty rvector.

Parameters:
theDatais a reference to a container of data into which to place the data once read.
inputDatais the container of rvectors we want to transfer to theData.
checkDimsis an indicator for whether the dimensions each of the elements of inputData are compared to the dimensions of the first (true) or not (false).
Returns:
the number of data points read in from inputData. Returns 0 if no data points read in from inputData.
Precondition:
If there is existing data in theData, the dimensions of that data are >= 1.
{

  size_t retValue = 0;
  bool cancontinue = true;
  int dim = 0;
  size_t existingSize = 0;
  
  if (!theData.empty()) { // data already in theData, print a warning
    existingSize = theData.size();
    std::cout
      << "Warning: adding to existing data "
      << "- mixing datasets"
      << std::endl;

  }

  if (inputData.empty()) {
    cancontinue = false;
  }
  
  // check first point in file
  if (cancontinue) {
    dim = VecLen(*(inputData.begin())); // size of the first one
    if (dim < 1) throw std::invalid_argument(
    "_getRvectorsFromRVec(RVecData&, RVecData&, int) : dimensions of first input element < 1"); 
    
  }

  if (cancontinue && !theData.empty()) { // check dimensions with first existing data point
    int dataDim = VecLen(*theData.begin());
    if (dim != dataDim) {
      std::cerr
        << "Aborting:: Existing data dimensions !=  "
        << "dimensions of first data point data to be read in" << std::endl;
      cancontinue = false;
    }
  }

  // dim is now irrelevant if checkDims = false
  
  // if cancontinue is still true we know there is data we can take
  if (cancontinue) {
    
    theData.reserve(inputData.size() + theData.size());

    if (!checkDims) {
      
      // just transfer the whole lot
      theData.insert(theData.end(), inputData.begin(),inputData.end());
    }
    else {
      int countLines = 0;
      for (RVecDataCItr it = inputData.begin();
          it < inputData.end();
          ++it) {
        countLines++;
        if ( VecLen(*it) == dim ) theData.push_back(*it);
        else {
          std::string line = ::toString(*it);
          lineErrorLogger(line, countLines);
        }
      }
    }
    assert(theData.size() >= existingSize);
    
    retValue = theData.size() - existingSize;    // data read in
  }

  return retValue;
}
void subpavings::getSampleFromContainer ( size_t  samplesize,
gsl_rng *  rgsl,
const subpavings::RVecData allData,
subpavings::RVecData sampleData 
)

Get a sample from data in a container.

A function to get a random sample of of a specified size from a given container of data. Sampling is with replacement.

Parameters:
samplesizeis the size of the sample to get.
rgslis a pointer to a random number generator.
allDatais the container of data points from which to draw the sample.
sampleDatais a container into which to put the sample drawn
Postcondition:
sampleData has samplesize data points from allData, drawn with replacement.
{
  // make space to add the sample in addition to existing data
  if (sampleData.empty()) {
    sampleData.reserve(samplesize);
  }
  else {
    sampleData.reserve(sampleData.size() + samplesize);
  }

  //get a sample of the data out of allData
  for (size_t i = 0; i < samplesize; i++) {
    //draw a random number in [0,1)
    double rand = gsl_rng_uniform(rgsl);
    //turn this into an index in [0, samplesize-1]
    int index = static_cast<int>(ceil(rand*samplesize - 1));
    //put element in allData indexed into data
    sampleData.push_back(allData[index]);
  }
}
size_t subpavings::getSampleRvectorsFromRSSample ( subpavings::RVecData data,
gsl_rng *  rgsl,
size_t  samplesize,
const RSSample rss,
int  label 
)

Get a sample of rvectors from an RSSample object.

A function to get a sample of rvectors from the labeled point sample data held by an RSSample object

Uses getRvectorsFromSample to get something to sample from. Then samples with replacement to find required sample size

Parameters:
datais a reference to a container of data into which to place the data once read.
rgslis a pointer to a random number generator
samplesizeis the size of the required sample
rssis the RSSample object with the data we want.
labelis the label for the points that we want from rss.
Precondition:
A container theData, assumed to be empty, in which to store data sampled from rss. theData should support push_back() method.
Postcondition:
The container theData contains a sample of rvectors from rss.
Returns:
the number of data points taken as a sample from rss.Samples. Returns 0 if no data points with the correct label found in rss.Samples or if dimensions did not match existing data points in data.
{

  RVecData allData; // a container for all the rvectors from rss.Samples

  //use getRvectorsFromRSSampleForSampling to put rvectors from labeled
  //points in rss.Samples into allData where the labeled point label
  //matches label
  size_t numberAll = getRvectorsFromRSSampleForSampling(allData,
          data, samplesize, rss, label);

  // get the sample
  if (numberAll > 0) {
    getSampleFromContainer(samplesize, rgsl, allData, data);
  }

  return data.size();
}
size_t subpavings::getSampleRvectorsFromRVec ( subpavings::RVecData data,
gsl_rng *  rgsl,
size_t  samplesize,
const subpavings::RVecData rvec 
)

Get a sample of rvectors from an a container.

Samples with replacement to find required sample size.

Parameters:
datais a reference to a container of data into which to place the data once read.
rgslis a pointer to a random number generator
samplesizeis the size of the required sample
rvecis the container with the data we want to sample from.
Returns:
the number of data points taken as a sample from the container. Returns 0 if dimensions did not match existing data points in data.
{
  getSampleFromContainer(samplesize, rgsl, rvec, data);

  return data.size();
}
string subpavings::getUniqueFilename ( const std::string &  baseFileName,
const std::string &  suffix = ".txt" 
)

Construct a unique filename from base and timestamp number.

Waits until timestamp number combined with baseFileName gives a name for a file that is unique.

Parameters:
baseFileNamethe base to use as the filename
suffixto put on filename, defaults to ".txt"
Returns:
a unique filename constructed as baseFileName + timestamp number + suffix.
{
  string s;
  bool newfilename = false;

  while (!newfilename) {
    stringstream out;
    out << time(NULL);
    s = baseFileName + out.str() + suffix;
    //try opening a file with this name for input
    ifstream inp;
    inp.open(s.c_str(), ifstream::in);
    inp.close();
    if(inp.fail()) // not already a file of this name
    {
      inp.clear(ios::failbit);
      newfilename = true;
    }
  } // we should now have a unique filename
  return s;

}
bool subpavings::isEmpty ( const SPnode *const  spn)

Check if a SubPaving is empty.

Returns:
true if the given node is NULL or SPnode::isEmpty() is true
{
  // return true if spn is a null pointer or
  // node spn points to is empty
  return ((spn==NULL) || (spn->isEmpty()));
}
bool subpavings::isLeaf ( const SPnode *const  spn)

Check if a node is a leaf.

Returns:
true if the given node is not NULL and SPnode::isLeaf() is true.
{
  // FALSE if spn is a null pointer, true if spn is not NULL
  bool retVal = (spn!=NULL);


  if (retVal) { // if spn points to a non-empty node
    retVal = spn->isLeaf();
  }

  return retVal;
}
void subpavings::lineErrorLogger ( const std::string &  line,
int  lineNumber 
)

Log an error from reading in data.

At present this just spits the error message out to cerr.

Parameters:
lineis the line that caused the problem.
lineNumberis the number of the line in the input file.
{
  std::cerr << "Error in data input file, "
          << "ignored line " << lineNumber
          << ".  Data ignored is:  "
          << line << std::endl;

}
cxsc::ivector subpavings::makeBox ( const RVecData &  theData,
int  dim,
cxsc::real  padding 
)

Make a box to contain all the data in a collection.

The box is made to fit all of the data in theData, with padding padding around the minimums and maximums of the data on each dimension.

Parameters:
theDataa reference to a container of rvector data.
dimthe dimensions of the data.
paddingthe padding to put around the minimums and maximums of the data in theData.
Returns:
an ivector same dimensions as the data and to fit all the data including an allowance for padding.
Precondition:
theData is not empty.
dim is the dimension of all the data in theData.
void subpavings::makeDotImage ( const std::string &  s)

make a Dot graph png image given a dot file.

Prints out a line to console with name of image file

Parameters:
sthe name of the .dot file to make the graph out of.
{
  string baseFileName = "graph";
  string suffix = ".png";
  string graphName = getUniqueFilename(baseFileName, suffix);

  // make the graph
  string commandLine = "dot -Tpng " + s + " -o " + graphName;
  int rv = system(commandLine.c_str());
  std::cout << endl;
  std::cout << "Graph output to " << graphName << std::endl << std::endl;

}
rvector subpavings::makeDoubleIntoRvector ( const double  d)

Make a double into an rvector.

Used for processing input to an AdaptiveHistogram object.

{
  rvector newdata = _rvector(d);
  // 1-d rvector, only element is the implicit cast of d to real
  // note that cxsc allows an implicit cast from double to real
  return newdata;

}
void subpavings::Mince ( SPnode *const  spn,
double  eps 
)

Mince up a subpaving.

Mince minces recursively until each leaf has maximum diameter smaller than eps.

Mince is now a non-friend non-member function (compare to the AIASPnode::Mince()) which now uses public member functions in the SPnode class.

Parameters:
spna pointer to the node whose box is to be minced
epsthe maximum diameter any box in the subpaving should be
{
  
  // only try to expand if we have a non-empty leaf
  if (!isEmpty(spn) && isLeaf(spn)) {

    int maxdiamcomp; // valued with MaxDiam function below

    // if the leaf's box is >= to eps, keep expanding
    if(MaxDiam(spn->getBox(), maxdiamcomp) >= eps) {
      // comp is the dimension to split on

      // if leaf and box not < eps then expand
      Expand(spn, maxdiamcomp);
    }

  } // end !isEmpty() && isLeaf()

  // not a leaf, so Mince the children
  if (!isEmpty(spn) && !isLeaf(spn)) {
    Mince(spn->getRightChild(), eps);
    Mince(spn->getLeftChild(), eps);
  }

  // if spn points to an empty subpaving, nothing happens
  
}

Less-than operator using pointers.

Returns:
true iff *lhs < *rhs.
{
  return ((*lhs) < (*rhs));
} 
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::FunctionEstimatorReal fei 
)

Output the contents of an FunctionEstimatorReal object.

Verbose output for an FunctionEstimatorReal object, including all boxes (not just leaves), data, and summary statistics.

{
    fei.outputRootToStreamTabs(os);
    return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::PolygonPiecewiseConstantFunction ppcf 
)

Output the contents of an PolygonPiecewiseConstantFunction object.

Verbose output for an PolygonPiecewiseConstantFunction object, including all boxes (not just leaves), data, and summary statistics.

{
    ppcf.outputToStreamTabs(os);
    return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const RealMappedShapeNode spn 
)

Output the contents of a SubPaving.

Output for all nodes in the subPaving.

This is intended for console output or output to a mixed alpha and numeric file.

{
  rpn.leavesOutputTabs(os);
  
  return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::FunctionImageEstimatorBooleanValue fei 
)

Output the contents of an FunctionImageEstimatorBooleanValue object.

Verbose output for an FunctionImageEstimatorBooleanValue object, including all boxes (not just leaves), data, and summary statistics.

{
    fei.outputRootToStreamTabs(os);
    return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::FunctionEstimatorKDE fek 
)

Output the contents of an FunctionEstimatorKDE object.

Verbose output for an FunctionEstimatorKDE object, including all boxes (not just leaves), data, and summary statistics.

{
    fek.outputRootToStreamTabs(os);
    return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const AdaptiveHistogramCollator adhc 
)

Output the contents of an AdaptiveHistogramCollator object.

Verbose output for an AdaptiveHistogram object.

{
    if (NULL != adhc.getSubPaving()) {
        adhc.getSubPaving()->nodesAllOutput(os, 1);
    os << std::endl;
    }

    return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::SpatialObjectRepresentationBV pcf 
)

Output the contents of an SpatialObjectRepresentationBV object.

Verbose output for an SpatialObjectRepresentationBV object, including all boxes (not just leaves), data, and summary statistics.

{
    pcf.outputRootToStreamTabs(os);
    return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const SPnode spn 
)

Output the contents of a SubPaving.

Output for all nodes in the subPaving.

This is intended for console output or output to a mixed alpha and numeric file.

{
  // uses nodePrint to generate node output

  if (!(spn.isEmpty()) && spn.isLeaf()) { // spn is non-empty leaf
    spn.nodePrint(os);
  }

  //recurse on the children
  if (spn.hasLCwithBox()) {
    os << (*(spn.getLeftChild()));
  }
  if (spn.hasRCwithBox()) {
    os << (*(spn.getRightChild()));
  }

  //in the case where spn is empty we just return os

  return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::IntVec vec 
)

Output the contents of a collection.

Output the contents of a VecDbl.

Output the contents of a RealVec.

Outputs colections as values separated by tabs.

Parameters:
osthe stream to send the output to.
vecthe collection to output.
Returns:
the stream with the new output.

Output the contents of an IntVec.

{
  if (!vec.empty()) {
    std::ostream_iterator< int > out_it (os, "\t");
    copy ( vec.begin(), vec.end(), out_it );
  }
  return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::FunctionEstimatorInterval fei 
)

Output the contents of an FunctionEstimatorInterval object.

Verbose output for an FunctionEstimatorInterval object, including all boxes (not just leaves), data, and summary statistics.

{
    fei.outputRootToStreamTabs(os);
    return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::PiecewiseConstantFunction pcf 
)

Output the contents of an PiecewiseConstantFunction object.

Verbose output for an PiecewiseConstantFunction object, including all boxes (not just leaves), data, and summary statistics.

{
    pcf.outputRootToStreamTabs(os);
    return os;
}
std::ostream & subpavings::operator<< ( std::ostream &  os,
const subpavings::AdaptiveHistogram adh 
)

Output the contents of an AdaptiveHistogram object.

Verbose output for an AdaptiveHistogram object, including all boxes (not just leaves), data, and summary statistics.

{
    if (adh.hasSubPaving()) {
    adh.getSubPaving()->nodesAllOutput(os, 1);
    os << std::endl;
  }
    return os;
}
BOOL_INTERVAL subpavings::operator<= ( const ivector &  z,
const SPMinimalnode *const  spmn 
)

Check for containment of interval vector in the SubPaving.

Parameters:
zthe interval vector we are testing for containment in a subpaving
spmna pointer to the subpaving node we are testing to see if it contains z
Returns:
a BOOL_INTERVAL, ie BI_TRUE, or BI_FALSE, or BI_INDET if z overlaps the boundary of the subpaving spn.
{
  BOOL_INTERVAL retValue = BI_FALSE;

  if (spmn!=NULL)
  {
    if (VecLen(z) != spmn->getDimension()) {
      throw IncompatibleDimensions_Error(
        "subpavings::operator<=(const ivector& , const SPMinimalnode * const )");
    }

    retValue = (*spmn).spContains(z);
  }
  return retValue;
  
}
void subpavings::outputFile ( const std::string &  s,
const std::string &  line,
bool  append = true 
)

Append a line to a txt file.

Puts a new line before and after the line.

Parameters:
sthe name of the txt file to send output to.
linethe line to append to the file.
appendcontrols whether line is appended to file, defaults to true.
{
  ofstream os;
  if (append) os.open(s.c_str(), ios::app);         // append
  else os.open(s.c_str()); // don't append
  if (os.is_open()) {
    os << endl;
    os << line << std::endl;
    os.close();
  }
  else {
    std::cerr << "Error: could not open file named "
      << s << std::endl << std::endl;
  }
}
void subpavings::outputFile ( const std::string &  s,
subpavings::RealVec vals,
int  i 
)

Append a tab delimited seq of values as a line in log file.

This routine is intended to help with logging a process like MCMC.

Parameters:
sthe name of the txt file to send output to.
valsis a vector of values to add to the file.
ithe number of pass (ie, 0, 1, 2, 3 etc) in process.
void subpavings::outputFile ( const std::string &  s,
RealVec vals,
int  i,
int  nodeType,
int  accepted,
size_t  nCount 
)

Append a tab delimited seq of values as a line in log file.

This routine is intended to help with logging a process like MCMC.

Parameters:
sthe name of the txt file to send output to.
valsis a vector of values to add to the file.
ithe number of pass (ie, 0, 1, 2, 3 etc) in process.
nodeTypean indictator for the type of node (eg leaf, cherry).
acceptedan indicator for whether the move was accepted.
nCountnumber of points in the node concerned.
{
  ofstream os(s.c_str(), ios::app);         // append
  if (os.is_open()) {
    os << i << "\t" << nodeType << "\t" << accepted << "\t" << nCount << "\t" << std::flush;
    ostream_iterator<real> out_it (os,"\t");
    copy ( vals.begin(), vals.end(), out_it );
    os << endl;
    
    os.close();
  }
  else {
    std::cerr << "Error: could not open file named "
      << s << std::endl << std::endl;
  }
}
void subpavings::outputFile ( const std::string &  s,
int  i,
int  val 
)

Append a value to a log file.

Parameters:
sthe name of the txt file to send output to.
ithe number of pass (ie, 0, 1, 2, 3 etc) in process.
vala value to log.
{
  ofstream os(s.c_str(), ios::app);         // append
  if (os.is_open()) {
    os << i << "\t" << val << std::endl;
    
    os.close();
  }
  else {
    std::cerr << "Error: could not open file named "
      << s << std::endl << std::endl;
  }
}
void subpavings::outputFile ( const std::string &  s,
int  i,
size_t  val 
)

Append a value to a log file.

Parameters:
sthe name of the txt file to send output to.
ithe number of pass (ie, 0, 1, 2, 3 etc) in process.
vala value to log.
{
  ofstream os(s.c_str(), ios::app);         // append
  if (os.is_open()) {
    os << i << "\t" << val << std::endl;
    
    os.close();
  }
  else {
    std::cerr << "Error: could not open file named "
      << s << std::endl << std::endl;
  }
}
void subpavings::outputFile ( const std::string &  s,
const std::string &  intro,
subpavings::RealVec vals 
)

Append a tab delimited list seq of values as a line in log file.

Parameters:
sthe name of the txt file to send output to.
introis the introduction before the rest is put in, all on one line.
valsis a vector of values to add to the file
{
  ofstream os(s.c_str(), ios::app);         // append
  if (os.is_open()) {
    os << intro << "\t";
    ostream_iterator<rvector> out_it (os,"\t");
    copy ( vals.begin(), vals.end(), out_it );
    os << "\n";

    os.close();
  }
  else {
    std::cerr << "Error: could not open file named "
      << s << std::endl << std::endl;
  }
}
void subpavings::outputFile ( const std::string &  s,
std::vector< std::string > &  strings,
int  i 
)

Append a tab delimited list seq of strings as a line in log file.

Parameters:
sthe name of the txt file to send output to.
stringsis a vector of strings to add to the file
ithe number of pass (ie, 0, 1, 2, 3 etc) in process
{
  ofstream os(s.c_str(), ios::app);         // append
  if (os.is_open()) {
    os << "Pass " << i << "\t" << std::endl; // numbering
    ostream_iterator<string> out_it (os,"\t");
    copy ( strings.begin(), strings.end(), out_it );
    strings.clear();
    os << endl;

    os.close();
  }
  else {
    std::cerr << "Error: could not open file named "
      << s << std::endl << std::endl;
  }
}
void subpavings::outputFileStart ( const std::string &  s)

Opening line of a txt log file.

Starts the log file with file name and date and time.

Parameters:
sthe name of the txt file to send output to.
{
  // Make a string with filename and timestamp to start log file
  time_t rawtime;
  struct tm * timeinfo;
  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  ofstream os(s.c_str());         // replace data
  if (os.is_open()) {
    os << "File " << s << " created " <<  asctime (timeinfo) << std::endl;
    os.close();
  }
  else {
    std::cerr << "Error: could not open file named "
      << s << std::endl << std::endl;
  }
}
void subpavings::outputFileString ( const std::string &  s,
const std::string &  line,
bool  append = true 
)

Append a string to a txt file.

Does not put in any new line characters.

Parameters:
sthe name of the txt file to send output to.
linethe string to append to the file.
appendcontrols whether line is appended to file, defaults to true.
{
  ofstream os;
  if (append) os.open(s.c_str(), ios::app);         // append
  else os.open(s.c_str()); // don't append
  if (os.is_open()) {
    os << line << flush;
    os.close();
  }
  else {
    std::cerr << "Error: could not open file named "
      << s << std::endl << std::endl;
  }
}
void subpavings::outputToFileVertical ( std::vector< const subpavings::RealVec * > &  dataPtrs,
const std::vector< std::string > &  colNames,
const std::string &  filename,
int  prec = 5 
)

Output multiple containers of data in vertical format.

Opening line of file gives creation details.

Puts data from each container in adjacent columns, right to left.

Checks that size of colNames matches size of dataPtrs, but does not check that vectors within dataPtrs are all the same length - if this is so, the resulting columns will simply be of unequal lengths.

Parameters:
dataPtrsa container of pointers to containers for the data.
colNamesheaders for the columns.
filenamefilename to use for the output.
void subpavings::outputToFileVertical ( const std::vector< size_t > &  lhsLines,
std::vector< const subpavings::RealVec * > &  dataPtrs,
const std::vector< std::string > &  colNames,
const std::string &  filename,
int  prec 
)

Output multiple containers of data in vertical format.

Opening line of file gives creation details.

lhsLines gives line or state numbers for left hand side column.

Puts data from each container in adjacent columns, right to left.

must be at least as long as the longest element in dataPtrs. Checks that size of colNames matches size of dataPtrs, but does not check that vectors within dataPtrs are all the same length - if this is so, the resulting columns will simply be of unequal lengths.

Parameters:
lhsLInesa container of line or state numbers for left hand side column.
dataPtrsa container of pointers to containers for the data.
colNamesheaders for the columns.
filenamefilename to use for the output.
void subpavings::outputToFileVertical ( std::vector< const subpavings::Size_tVec * > &  dataPtrs,
const std::vector< std::string > &  colNames,
const std::string &  filename 
)

Output multiple containers of data in vertical format.

Opening line of file gives creation details.

Puts data from each container in adjacent columns, right to left.

Checks that size of colNames matches size of dataPtrs, but does not check that vectors within dataPtrs are all the same length - if this is so, the resulting columns will simply be of unequal lengths.

Parameters:
dataPtrsa container of pointers to containers for the data.
colNamesheaders for the columns.
filenamefilename to use for the output.
precprecision to use for outputting data (cxsc formatting, Variable type output).
void subpavings::outputToFileVertical ( std::vector< const subpavings::Size_tVec * > &  sizePtrs,
std::vector< const subpavings::RealVec * > &  realPtrs,
const std::vector< std::string > &  colNamesSize,
const std::vector< std::string > &  colNamesReal,
const std::string &  filename,
int  prec = 5 
)

Output multiple containers of data in vertical format.

Opening line of file gives creation details.

Puts data from each container in adjacent columns, alternating between successive columns from sizePts and dataPtrs, right to left.

Checks that size of colNames matches size of collection of ptrs for both size and real, and that size of size data is same as size of real data, but does not check that vectors within dataPtrs and sizePtrs are all the same length - if this is so, the resulting columns will simply be of unequal lengths.

Parameters:
sizePtrsa container of pointers to containers for the data as size_t types.
dataPtrsa container of pointers to containers for the data as reals.
colNamesSizeheaders for the size data columns.
colNamesDataheaders for the real data columns.
filenamefilename to use for the output.
precprecision to use for outputting data (cxsc formatting, Variable type output).
void subpavings::outputToFileVertical ( std::vector< const subpavings::Size_tVec * > &  sizePtrs,
std::vector< const subpavings::RealVec * > &  realPtrs,
const std::string &  filename,
size_t  startPos,
int  prec 
)

Add output multiple containers of data in vertical format to an existing file.

Puts last (see startPos) data from each container in adjacent columns, alternating between successive columns from sizePts and dataPtrs, right to left.

Does not check that vectors within realPtrs and sizePtrs are all the same length - if this is so, the resulting columns will simply be of unequal lengths.

Parameters:
sizePtrsa container of pointers to containers for the data as size_t types.
realPtrsa container of pointers to containers for the data as reals.
filenamefilename to use for the output.
startPosposition in collections inside sizePtrs, realPtrs, at which to start finding data to output.
precprecision to use for outputting data (cxsc formatting, Variable type output).
void subpavings::outputToFileVertical ( std::vector< const subpavings::RealVec * > &  realPtrs,
const std::string &  filename,
size_t  startPos,
int  prec 
)

Add output from multiple containers of data in vertical format to an existing file.

Puts last (see startPos) data from each container in adjacent columns, right to left.

Does not check that vectors within realPtrs are all the same length - if this is so, the resulting columns will simply be of unequal lengths.

Parameters:
realPtrsa container of pointers to containers for the data as reals.
filenamefilename to use for the output.
startPosposition in collections inside realPtrs, at which to start finding data to output.
precprecision to use for outputting data (cxsc formatting, Variable type output).
bool subpavings::parseForGraphDot ( const std::string &  s,
std::string  toParse 
)

Parse a string to make lines for a dot graph.

Parameters:
sthe name of the file to output to
toParsethe string to parse
Returns:
true if parsing worked, false if problems encountered
{
  bool success = false;
  if (toParse.length() > 1) { // min of "XL" or "XR"

    string sep = " \t,";
    size_t startpos = toParse.find_first_not_of(sep); // start of segment
    size_t endpos = string::npos;
    string segment = "";
    if (startpos != string::npos) { // find start next sep
      endpos = toParse.find_first_of(sep, startpos+1);
      if (endpos != string::npos) {  // get the segment
        segment = toParse.substr(startpos, endpos-startpos);
        toParse = toParse.substr(endpos); // what is left

      }
      else { // must be last segment
        segment = toParse.substr(startpos);
        toParse = "";
      }
    }
    if (segment.length() > 1) {
      string parent = segment.substr(0,segment.length()-1);
      string line = "\t " + parent + " -> " + segment + ";";
      outputFile(s, line);
      success = true;
    }
    if (success && toParse.length() > 0) {
      //recurse
      success = parseForGraphDot(s, toParse);
    }
  } // end if length at start > 1

  return success;
}
IntVec subpavings::parseSpacings ( string  line,
IntVec &  spacings 
)

parse a .vtk header line for spacings data.

Expects a line of the form "DIMENSIONS 32 32 32"

Parameters:
lineis the line to be parsed.
spacingsis an empty container for the spacings.
Returns:
the container of spacings filled up from the data in the line.
cxsc::rvector & subpavings::readRV ( cxsc::rvector &  r,
const std::string &  line 
)

Read an rvector in from a string.

Parameters:
ris a reference to the rvector to read into.
lineis the line to read into r.
Returns:
the reference to r, with line read in.
Precondition:
The length of r should be the same as the number of values in line.
{
  // convert line to an istream type
  istringstream sin(line);
  // c-xsc can convert this to an rvector
  sin >> r;
  // put r into the container
  return r;
}
cxsc::rvector & subpavings::readRV ( cxsc::rvector &  r,
const std::string &  line,
const std::vector< int > &  reqDims,
int  lineDim 
)

Read specified elements from a string into an rvector.

The elements are specified in reqDims.

Eg reqDims = 5, 3, 7 would create a 3-d rvector r where r[1] is the 5th value in the line, r[2] is the 3rd value in the line, r[3] is the 7th value in the line.

Parameters:
ris a reference to the rvector to read into.
lineis the line to read into r.
reqDimsis a container of dimensions to read from line.
lineDimis the number of values the line is meant to contain.
Returns:
the reference to r, with line read in.
Precondition:
line must have at least as many separate values in as the maximum value in reqDims. The length of r should be the same as the size of reqDims. line contains lineDim values.
{
  // c-xsc can convert this to an rvector
  int n = reqDims.size();
  
  cxsc::rvector tmp(lineDim);
  
  tmp = readRV(tmp, line);
  
  for (int i = 1; i <= n; ++i) {
    r[i] = tmp[reqDims[i-1]];
  }

  return r;
}
bool subpavings::readRvectorsFromTxtOrd ( subpavings::RVecData theData,
const std::string &  s,
std::size_t  headerlines = 0 
)

Read in rvectors from a txt file with Ordinary level checking.

Data dimensions are deduced from the first valid input line read after headerlines.

{
  int checkLevel = 1;
  int dataDim = -1;
  std::vector <int> reqDims;
  
  return _readRvectorsFromTxt(theData, 
              s,
              headerlines,
              checkLevel,
              reqDims,
              dataDim);
}
bool subpavings::readRvectorsFromTxtOrd ( subpavings::RVecData theData,
const std::string &  s,
const std::vector< int > &  reqDims,
std::size_t  headerlines = 0 
)

Read in rvectors from a txt file with Ordinary level checking.

Data dimensions are deduced from the first valid input line read after headerlines.

{
  if (reqDims.empty()) {
    throw std::invalid_argument(
    "readRvectorsFromTxtOrd(RVecData&, const string&, const std::vector < int >&, std::size_t) : reqDims.empty()");
  }
  if ( (*std::min_element(reqDims.begin(), reqDims.end())) < 1) {
    throw std::invalid_argument(
    "readRvectorsFromTxtParanoid(RVecData&, const string&, const std::vector < int >&, std::size_t) : min element < 1");
  }
  
  int checkLevel = 1;
  int dataDim = reqDims.size();
  
  return _readRvectorsFromTxt(theData, 
              s,
              headerlines,
              checkLevel,
              reqDims,
              dataDim);
}
bool subpavings::readVecRealVecFromTxt ( std::vector< subpavings::RealVec > &  theData,
const std::string &  s,
std::size_t  headerlines,
int  dims = 0 
)

Read from a txt file into a container of containers of reals.

Will print error messages to standard error output if the file cannot be opened or if no numeric data was found after the headerlines.

If dims is not given, the expected dimensions will be taken as the number of separate numeric values on the first non-blank line that passes the check checkString() read after the headerlines.

Numeric data is expected to be presented as one line per RealVec to be read in, with (at least) as many values as the expected dimensions (the excess will be silently ignored).

No checks for illegal characters or bad formatting are carried out: the results of this are unpredictable but will almost certainly result in the data read in being incorrect.

Throws an invalid_argument exception if dims < 0.

Parameters:
theDataa reference to a container to put the data in.
sthe name of the file to extract from.
headerlineshow many lines to skip at the start of the file.
dimsthe dimensions of the data to expect (defaults to 0).
Returns:
true if at least one RealVec was added to theData, false otherwise.
std::string & subpavings::reformatLine ( std::string &  line)

Reformat a line to be suitable for reading into an rvector.

Strips out dos carriage returns.

Parameters:
linea reference to a string to reformat.
Returns:
the same line reformatted.
{
  string carriageRet("\r"); 
  
  size_t cr_pos = line.find_first_of(carriageRet);
  while (cr_pos != std::string::npos) {
    size_t next = line.find_first_not_of(carriageRet, cr_pos);
    line.erase(cr_pos, 1);
    if (next != std::string::npos) {
      cr_pos = line.find_first_of(carriageRet, next-1);
    }
    else cr_pos = next;
  }
  return line;
}
template<typename T >
T* subpavings::Regularize ( ivector &  hull,
ImageList &  ivectorList,
double  eps 
)

Forms a minimal image subpaving.

Make a minimal subpaving from a list of interval vector images. The root of the subpaving will have Box = hull, where hull has already been formed from the union of all the ivectors in the ivectorList. Regularize is applied recursively on bisected half of hull and new lists until either there are no images in the list or the diameter of the hull is below eps.

Uses Reunite() and recursive calls to Regularize() to work upwards to form a minimal subpaving

Regularize is now a templatised non-friend non-member function (compare to AIASPnode::Regularize()) which now uses public member functions in the SPnode class.

Parameters:
hullthe interval hull of all the interval vectors in the image list
ivectorLista collection of possibly overlapping interval vectors to be made into a regular subpaving
epsthe precision with which the returned subpaving should be formed
Returns:
a regular minimal subpaving with root box hull
  {
    T* newNode = NULL;  // for return value
    
    try {

      /*sort the list: volCompare makes the sort largest to smallest
      Jaulin et al do not have this step because they have their own
      IMAGELIST class which acts like a set and keeps contents in order
      But we are using the stl std::list and so it is unsorted when
      it is passed to Regularize.  It is more effient to sort it once
      per call to Regularise than to keep it sorted as it is
      being built because the sorted order is only needed when
      the entire list has been built.
      */
      
      //sort using the volCompare function
      ivectorList.sort(volCompare);   // sorts smallest to largest

      // test if hull is contained in the first (largest) box in list

      int maxdiamcomp = 0;  // to take value calculated from MaxDiam

      // find the maximum diameter and
      double maxDiamHull = MaxDiam(hull, maxdiamcomp);

      // test if hull is equal to the largest image element, ie the last one
      bool isHullEqual = (hull == (*ivectorList.rbegin()));

      // test if hull is smaller than eps
      bool isHullSmall = (maxDiamHull < eps);

      // if the list has some images in it
      // and either if the hull is equal to the largest box in the list
      // or if the hull max diameter is < eps
      // return a new node based on hull
      if (!(ivectorList.empty()) && (isHullEqual || isHullSmall)) {
          newNode = new T(hull);
      }

      // if the list has some images in it
      // and the hull is not equal to the largest box in the list
      // and the hull max diameter is not < eps
      // return look at the left and right boxes
      if (!(ivectorList.empty()) && !isHullEqual && !isHullSmall) {

        // new ivectors from splitting hull along its biggest dimension
        ivector lefthull = Lower(hull, maxdiamcomp);
        ivector righthull = Upper(hull, maxdiamcomp);

        // create two empty lists for the left and right side
        ImageList leftlist, rightlist;

        ImageListItr it; // iterator to for the list

        // iterate through the current list and put the intersection of any
        // element with the lefthull into new left list, and the intersection
        // of any element with the new right hull into the new right list
        for (it=ivectorList.begin(); it!=ivectorList.end(); it++) {
          ivector interLeft;  // intersection with left hull
          ivector interRight;  // intersection with right hull

          if (Intersection(interLeft, *it, lefthull)) {
            leftlist.push_back(interLeft);
          }

          if (Intersection(interRight, *it, righthull)) {
            rightlist.push_back(interRight);
          }

        } // end of iteration through list elements

        // recursively call Regularize with lefthull, leftlist
        // and righthull, rightlist
        // reunite the results using hull as the box for parent node
        // Regularize creates a minimal subpaving
        // (no sibling child nodes) on the hull

        newNode = Reunite<T>(Regularize<T>(lefthull, leftlist, eps),
                  Regularize<T>(righthull,
                        rightlist, eps), hull);

      } // end of is list has elements and first box does not contain hull
        // and hull is large enough to warrent further splitting

      // if there is nothing in the list we return the default
        // initialisation value of NULL

       return newNode;
     }
    catch(std::exception const& e) {
      delete newNode;
      newNode = NULL;
      throw;
    }
  }
template<typename T >
T* subpavings::RegularizeNonMinimal ( ivector &  hull,
ImageList &  ivectorList,
double  eps 
)

Forms a non-minimal image subpaving.

Make a non-minimal subpaving from a list of interval vector images The root of the subpaving will have Box = hull, where hull has already been formed from the union of all the ivectors in the ivectorList. RegularizeNonMinimal is applied recursively on bisected half of hull and new lists until either there are no images in the list or the diameter of the hull is below eps.

Uses Reunite() and recursive calls to RegularizeNonMinimal() to work upwards to form a non-minimal subpaving.

Parameters:
hullthe interval hull of all the interval vectors in the image list
ivectorLista collection of possibly overlapping interval vectors to be made into a regular subpaving
epsthe precision with which the returned subpaving should be formed
Returns:
a regular non-minimal subpaving with root box hull
  {
    T* newNode = NULL;  // for return value

    try {
      // sort the list: volCompare makes the sort largest to smallest
      // Jaulin et al do not have this step because they have their own
      // IMAGELIST class which acts like a set and keeps contents in order
      // But we are using the stl std::list and so it is unsorted when
      // it is passed to Regularize.  It is more efficient to sort it once
      // per call to Regularise than to keep it sorted as it is
      // being built because the sorted order is only needed when
      // the entire list has been built.

      // sort using the volCompare function
      ivectorList.sort(volCompare);   // sorts smallest to largest

      // test if hull is contained in the first (largest) box in the list

      int maxdiamcomp = 0;  // to take value from MaxDiam

      // find the maximum diameter
      double maxDiamHull = MaxDiam(hull, maxdiamcomp);

      // test if hull is equal to the
        // largest image element, ie the last one
      bool isHullEqual = (hull==(*ivectorList.rbegin()));
      bool isHullSmall = (maxDiamHull < eps);

      // if the list has some images in it
      // and either if the hull is equal to the largest box in the list
      // or if the hull max diameter is < eps
      // return a new node based on hull
      if (!(ivectorList.empty()) && (isHullEqual || isHullSmall)) {
        newNode = new T(hull);
      }

      // if the list has some images in it
      // and the hull is not contained in the first box in the list
      // and the hull max diameter is not < eps
      // return look at the left and right boxes
      if (!(ivectorList.empty()) && !isHullEqual && !isHullSmall) {

        // new ivectors from splitting hull along its biggest dimension
        ivector lefthull = Lower(hull, maxdiamcomp);
        ivector righthull = Upper(hull, maxdiamcomp);

        // create two empty lists for the left and right side
        ImageList leftlist, rightlist;

        ImageListItr it; // iterator to for the list

        // iterate through the current list and put the intersection of any
        // element with the lefthull into new left list, and the intersection
        // of any element with the new right hull into the new right list
        for (it=ivectorList.begin(); it!=ivectorList.end(); it++) {
          ivector interLeft;  // intersection with left hull
          ivector interRight;  // intersection with right hull

          if (Intersection(interLeft, *it, lefthull)) {
            leftlist.push_back(interLeft);
          }

          if (Intersection(interRight, *it, righthull)) {
            rightlist.push_back(interRight);
          }

        } // end of iteration through list elements

        // recursively call RegularizeNonMinimal with lefthull,
        // leftlist and righthull, rightlist
        // adopt the results using hull as the box for parent node
        // RegularizeNonMinimal creates a non-minimal subpaving
        // (ie has sibling child nodes) on the hull

        newNode = Adopt<T>(RegularizeNonMinimal<T>(lefthull, leftlist,
                            eps),
                RegularizeNonMinimal<T>(righthull,
                            rightlist,
                            eps),
                        hull);

      } // end of is list has elements and first box does not contain hull
      // and hull is large enough to warrent further splitting

      // if there is nothing in the list we return the default
        // initialisation value of NULL

      return newNode;
    }
    catch(std::exception const& e) {
      delete newNode;
      newNode = NULL;
      throw;
    }

  }
template<typename T >
T* subpavings::Reunite ( T *  lChild,
T *  rChild,
ivector  x 
)

Tries to reunite two nodes to form a single leaf.

Note:
Node types used with these templates should implement default constructor and constructor taking ivector argument and also implement nodeExpand(), nodeReunite(), nodeAdoptLeft() and nodeAdoptRight() functions.

Note that the nodes provided, lChild and rChild, are potential children for the node to be created and returned in this function. nodeReunite is used in building a tree upwards (rather than in pruning leaves of formed tree from the bottom up).

If two potential children are provided and they are both leaves, combines the two leaf siblings into the returned node. If the potential children are not leaves or if only one potential child is provided, graft the potential child/children onto the node to be created and returned as its child/children.

Calls nodeReunite method for the type of spn (base or derived) at runtime.

Reunite is now a templatised non-friend non-member function (compare to AIASPnode::Reunite()) which now uses public member functions in the SPnode class.

Parameters:
lChilda pointer to the leftChild node to be reunited
rChilda pointer to the rightChild node to be reunited
xis the box of the new subpaving to be returned
Returns:
a minimal subpaving from two sibling subpavings
  {
    T* newNode = NULL; // pointer to new node to be returned

    try {
      
      newNode = new T(x);

      // both proposed children are empty, return null
      if(isEmpty(lChild) && isEmpty(rChild)) {
        newNode = NULL;
      }

      // only given a right child, left child is NULL
      if (isEmpty(lChild) && !isEmpty(rChild)) {
        //graft right child on
        newNode->nodeAdoptRight(rChild);
      }

      // only given a left child, right child is NULL
      if (!isEmpty(lChild) && isEmpty(rChild)) {
        //graft left child on
        newNode->nodeAdoptLeft(lChild);
      }

      // both children exist
      if (!isEmpty(lChild) && !isEmpty(rChild)) {

        // otherwise reunite the proposed children on this node
        newNode->nodeReunite(lChild, rChild);
      }

      return newNode;
    }
    catch(std::exception const& e) {
      delete newNode;
      newNode = NULL;
      throw;
    }
  }
std::string subpavings::stripPath ( const std::string &  filename)

Strip the path from a filename.

If the filename is in the form "path/file" then just the string file is returned. If the filename is in the form file (ie there is no path) then the string returned is file.

Note:
The path and file are assumed to be delimited by "/".
Parameters:
filenamethe name of the file to strip path from.
Returns:
a string comprising filename without path.
{
  /* Search for the last '/' in the filename, break
   * it there*/

  std::string file = filename;

  size_t found;
  found=filename.find_last_of("/");
  if (found!=string::npos) {
    file = filename.substr(found+1);
  }
  return file;
}
std::string subpavings::toString ( const subpavings::IntVec  vec,
bool  compact = false 
)

String representation of an IntVec.

String representation of a VecDbl.

String representation of a RealVec.

{
  std::ostringstream oss;
  
  std::string delim(", ");
  if (compact) delim = ",";
  
  std::ostream_iterator<int> out_it (oss, delim.c_str());
  copy ( vec.begin(), vec.end(), out_it );
  
  std::string result = oss.str();

  result = result.substr(0, result.size()-delim.size());
  
  return result;
}
real subpavings::tryExp ( real  r)

Work arround for c-xsc math library for exponentiation of reals.

The library handling exponentiation of reals cannot deal with large reals. This function tries the exponentiation after conversion to a double and converting the results back to a real if success.

{
  real result = 0.0;
  try
  {
    result = _real(exp(_double(r)));

  }
  catch (...)
  {
    // exponentiation error

  }
  return result;

}
bool subpavings::volCompare ( const ivector &  a,
const ivector &  b 
) [related]

A function for comparing ivectors based on volume.

Used in sorting a list of ivectors ordered by volume.

Uses Volume() as defined in toolz.

Returns:
TRUE if the Volume of a is strictly less than Volume of b.
{
  bool returnValue = 0;

  // Make sure vectors have same number of elements
  // and at least one element each
  if( (Ub(a)-Lb(a)) == (Ub(b)-Lb(b)) && (Ub(a)-Lb(a))>=0 ) {
    // compare the two volumes
    returnValue = ((Volume(a)<Volume(b)));

  }
  else {
    std::cerr << "Error in volCompare : comparing "
      << "ivectors of different dimensions"
      << std::endl;
  }

  return returnValue;
}
 All Classes Namespaces Functions Variables Typedefs Enumerations Friends