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

A wrapper or manager for an RealMappedSPnode tree representing a piecewise constant function. More...

List of all members.

Public Member Functions

 PiecewiseConstantFunction ()
 No argument constructor.
 PiecewiseConstantFunction (const ivector &v, int lab=0)
 Initialised constructor.
 PiecewiseConstantFunction (const RealMappedSPnode &rmspn, int lab=0)
 Initialised constructor.
 PiecewiseConstantFunction (const AdaptiveHistogram &adh)
 Initialised constructor.
 PiecewiseConstantFunction (unsigned long int numLeaves, const MCMCPartitionGenerator &partitioner, const ivector &v, int lab=0)
 Initialised constructor to make a random un-normalised function shape.
 PiecewiseConstantFunction (const PiecewiseConstantFunction &other)
 Copy constructor.
 ~PiecewiseConstantFunction ()
 Destructor.
PiecewiseConstantFunctionoperator= (PiecewiseConstantFunction rhs)
 Copy assignment operator.
int getLabel () const
 Get the label.
void setLabel (int lab)
 Set the label.
const RealMappedSPnode getCopySubPaving () const
 Get a copy of the subpaving managed by this.
bool hasSubPaving () const
 Get whether this has a subpaving to manage.
bool hasNegativePiecewiseConstantValues () const
 Get whether the subpaving managed by this has negative range values.
bool hasInfinitePiecewiseConstantValues () const
 Get whether the subpaving managed by this has infinite range values.
cxsc::ivector getRootBox () const
 Get the box of the subpaving managed by this.
int getDimensions () const
 get the dimensions of the subpaving this manages.
cxsc::real getDomainVolume () const
 get volume of the root box of the subpaving this manages.
size_t getRootLeaves () const
 Gets number of leaf nodes in the root paving.
IntVec getLeafLevels () const
std::string getLeafLevelsString () const
void smearZeroValues (cxsc::real totalSmear)
 Smear this out so that no piece has value 0.0 but the total integral is unchanged.
PiecewiseConstantFunction makeSmearZeroValues (cxsc::real totalSmear) const
 Make a PiecewiseConstantFunction by smearing this out so that no piece in the new function has value 0.0 but the total integral is the same as the total integral of this.
bool splitToShape (std::string instruction)
 Split this to a specified shape.
void allocateRanges (const std::vector< cxsc::real > &rangesToAllocate)
 Recursively allocate a collection of ranges to this and children.
void reshapeToUnion (const PiecewiseConstantFunction &other)
 Change this so that the subpaving it manages is the union of this's subpaving and the subpaving of another PiecewiseConstantFunction.
PiecewiseConstantFunction makeShapeToUnion (const PiecewiseConstantFunction &other) const
 Return a PiecewiseConstantFunction that has subpaving that is the union of this's subpaving and the subpaving of another PiecewiseConstantFunction.
cxsc::real getTotalIntegral () const
 Get the total integral of the piecewise constant function represented by this.
cxsc::real getLogLikelihood (const AdaptiveHistogram &adh) const
 Get a 'log likelihood' using function values from this and counts from spn.
cxsc::real getIAE (const PiecewiseConstantFunction &pcf) const
 Get the total integrated absolute error (IAE) between this and another PiecewiseConstantFunction.
cxsc::real getMaxPiecewiseConstant () const
 Get maximum value of the constant for any piece in this.
PiecewiseConstantFunctionoperator+= (const PiecewiseConstantFunction &rhs)
 Addition to self operator.
const PiecewiseConstantFunction operator+ (const PiecewiseConstantFunction &rhs) const
 Addition operator.
PiecewiseConstantFunctionoperator+= (const cxsc::real &add)
 Self-scalar addition operator.
const PiecewiseConstantFunction operator+ (const cxsc::real &add) const
 Scalar addition operator.
PiecewiseConstantFunctionoperator-= (const PiecewiseConstantFunction &rhs)
 Subtraction from self operator.
const PiecewiseConstantFunction operator- (const PiecewiseConstantFunction &rhs) const
 Subtraction operator.
PiecewiseConstantFunctionoperator-= (const cxsc::real &sub)
 Self-scalar subtraction operator.
const PiecewiseConstantFunction operator- (const cxsc::real &sub) const
 Scalar subtraction operator.
PiecewiseConstantFunctionoperator*= (const PiecewiseConstantFunction &rhs)
 Multiplication of self operator.
const PiecewiseConstantFunction operator* (const PiecewiseConstantFunction &rhs) const
 Multiplication operator.
PiecewiseConstantFunctionoperator*= (const cxsc::real &mult)
 Self-scalar multiplication operator.
const PiecewiseConstantFunction operator* (const cxsc::real &mult) const
 Scalar multiplication operator.
PiecewiseConstantFunctionoperator/= (const PiecewiseConstantFunction &rhs)
 Division of self operator.
const PiecewiseConstantFunction operator/ (const PiecewiseConstantFunction &rhs) const
 Division operator.
PiecewiseConstantFunctionoperator/= (const cxsc::real &div)
 Self-scalar division operator.
const PiecewiseConstantFunction operator/ (const cxsc::real &div) const
 Scalar division operator.
void normalise ()
const PiecewiseConstantFunction makeNormalised () const
void marginalise (const std::vector< int > &reqDims)
 Marginalised this.
const PiecewiseConstantFunction makeMarginal (const std::vector< int > &reqDims) const
 Make a marginalised version of this.
cxsc::real findCoverage (const rvector &pt) const
 Find the coverage value for a data point.
cxsc::real pointwiseExtension (const rvector &pt) const
 Find the pointwise extension of the piecewise constant function for a given data point.
cxsc::real getL1Distance (const PiecewiseConstantFunction &other) const
std::ostream & outputToStreamTabs (std::ostream &os, int prec=5) const
 Output the subpaving managed by this to a given stream.
void outputGraphDot () const
 Make a .dot graph file.
Get a slice of this.
Note:
The sliceDims are given as 1, 2, 3, etc, ie are numbered from 1 upwards not from 0 upwards<>.

Make a slice this on at the point jointly specified by sliceDims and slicePts. For example, if this has a 3-dimensional root box [-1,1]x[-1,1]x[-1,1], ie dimensions {1,2,3} and sliceDims = {2,3} and slicePts is (0.0,0.5) then we are slicing at point 0.0 on dimension 2, point 0.5 on dimension 3. The slice returned would then have only one-dimensional boxes on dimensions {1,2,3}2,3} = {1}, each box being one that did contain point 0.0 on dimension 2, point 0.5 on dimension 3. The range will be unchanged). Any boxes associated with this that do not contain the point 0.0 on dimension 2 and 0.5 on dimension 3 will not be represented in the returned object.

Parameters:
sliceDimsis a vector of dimensions to slice on, indexed from 1 onwards.
slicePtsis a vector of points to slice on, assumed to correspond to the dimensions in sliceDims, ie the ith value in sliceDims gives the dimension for the ith point in slicePts.
sliceFilenameis the name of file to use to capture the boxes of this that are used in the slice by outputting them to the file named sliceFilename. Defaults to the empty string "". If sliceFilename is the empty string "" no boxes will be captured to file.
Returns:
The slice of this on the specified dimensions and points.
Precondition:
This must have a subpaving to manage.
sliceDims must contain only valid dimensions, ie dimensions in this, with minimum dimension 1.

const PiecewiseConstantFunction makeSlice (const std::vector< int > &sliceDims, const std::vector< cxsc::real > &slicePts, const std::string sliceFilename="") const
const PiecewiseConstantFunction makeSlice (const std::vector< int > &sliceDims, const std::vector< double > &slicePts, const std::string sliceFilename="") const
Output the nodes constituting coverage region \a cov

to a file called covFileName.

The coverage region is the smallest subset of the boxes of the leaf nodes of the subpaving managed by this such that the sum of the "areas" of those leaf boxes is >= cov * total sum of the "areas" of the leaf nodes of the subpaving managed by this.

ie it is the elements of the partition whose integral is at least cov% of the integral of the whole when the elements are chosen in order from "tallest" first downwards.

Precondition:
This must have a subpaving to manage.
0.0 =< cov <= 1.0.
The subpaving managed by this must have no negative ranges, ie hasNegativePiecewiseConstantValues() = false.
The subpaving managed by this must have no infinite ranges, ie hasInfinitePiecewiseConstantValues() = false.
void outputCoverageRegion (std::ostream &os, cxsc::real cov, int prec) const
void outputCoverageRegion (std::ostream &os, cxsc::real cov) const
void outputCoverageRegion (const std::string &covFileName, cxsc::real cov, int prec, bool confirm=true) const
void outputCoverageRegion (const std::string &covFileName, cxsc::real cov, bool confirm=true) const
Simulate some data from this.

Data is simulated from this according to a uniform mixture distribution where each leaf box of the subpaving managed by this is a component in the mixture with weight equal to contribution to the total integral over this. The result should be equivalent to simulating by, for each data point, choosing a leaf box randomly with probability according to the relative "areas" (value x volume) of the leaves and then randomly selecting a data point within that box (ie uniform probability of selection over the entire box).

Parameters:
containeris a reference to a container for the data.
numberToSimulateis the number of data points to simulate.
Returns:
the reference to container.
Precondition:
This has a subpaving to manage.
Postcondition:
container contains any data it had before the operation and then numberToSimulate data points simulated from this.
RVecDatasimulateData (RVecData &container, size_t numberToSimulate, gsl_rng *r) const
 Simulator taking a random number generator argument.
RVecDatasimulateData (RVecData &container, size_t numberToSimulate, long unsigned int seed) const
 Simulator taking a random number generator seed argument.
RVecDatasimulateData (RVecData &container, size_t numberToSimulate) const
 Simulator using default random number generator.
Output the subpaving managed by this to a txt file.

Format is a tab-delimited file of numeric data starting with nodeName, then the node box volume, then the node value, then the description of the node box as a tab-delimited list of interval upper and lower bounds.

Parameters:
sthe name of the txt file to send output to.
precthe precision for output formatting. ie, number of decimal places.
confirmis a boolean controlling whether confirmation goes to console output.
void outputToTxtTabs (const std::string &s, int prec=5) const
void outputToTxtTabs (const std::string &s, int prec, bool confirm) const
Output details of full sample (from root) to txt file.

Format is a mixture of alpha and numeric data.

Parameters:
sthe name of the txt file to send output to.
precthe precision for output formatting. ie, number of decimal places.
confirmis a boolean controlling whether confirmation goes to console output.
void outputRootToTxt (const std::string &s, int prec=5) const
void outputRootToTxt (const std::string &s, int prec, bool confirm) const

Friends

class PolygonPiecewiseConstantFunction

Output all nodes of the subpaving managed by this to

a given stream.

Format is a tab-delimited data giving details of all nodes.

Parameters:
osis a reference to the stream to output to.
precthe precision for output formatting. ie, number of decimal places, defaulting to 5.
Returns:
a reference to the given stream.
std::ostream & outputRootToStreamTabs (std::ostream &os, int prec=5) const
void outputLog (const std::string &s, int i, int prec=5) const
 Append current state of estimator to a txt log file.
std::string stringSummary () const
 Get a string summary of this estimator's properties.
void swap (PiecewiseConstantFunction &pcf)

Detailed Description

A wrapper or manager for an RealMappedSPnode tree representing a piecewise constant function.


Constructor & Destructor Documentation

No argument constructor.

Postcondition:
This has no subpaving and label 0.
         : rootPaving(NULL), label(0)
{}
PiecewiseConstantFunction::PiecewiseConstantFunction ( const ivector &  v,
int  lab = 0 
) [explicit]

Initialised constructor.

Initialised with domain box and label.

Constructor to be used if piecewise constant function is to be subsequently formed by, for example, splitToShape and allocateRanges.

Throws a MalconstructedBox_Error if the box is not suitable as the basis of a subpaving (eg, box has no dimensions, or the box has a thin interval on at least one dimension).

Parameters:
vThe box to use for the subpaving to be managed.
labThe label for this (defaults to 0).
Postcondition:
This has subpaving that consists of single leaf node (the root) with a box like v) and the range on that single node is 0.0.
         : rootPaving(NULL), label(lab)
{
    try {
        // check the box here
        if (!checkBox(v)) {
      throw subpavings::MalconstructedBox_Error(
      "PiecewiseConstantFunction::PiecewiseConstantFunction(const ivector&, int lab)");
    }
        rootPaving = new RealMappedSPnode(v, real(0.0)); 
    
  }
    catch (exception const& e) {
    constructor_error_handler();
    }
}
PiecewiseConstantFunction::PiecewiseConstantFunction ( const RealMappedSPnode rmspn,
int  lab = 0 
) [explicit]

Initialised constructor.

Initialised with a subpaving.

Parameters:
spnA subpaving to copy as the subpaving to be managed.
labThe label for this (defaults to 0).
Precondition:
rmspn has a box.
Postcondition:
The piecewise constant function constructed has label lab, and a subpaving that is a copy of rmspn.
         : rootPaving(NULL), label(lab)
{
    try {
        // check spn has box
    if (rmspn.isEmpty()) {
      throw subpavings::NoBox_Error(
      "PiecewiseConstantFunction::PiecewiseConstantFunction(const RealMappedSPnode&, int lab)");
    }
        
    rootPaving = new RealMappedSPnode(rmspn);
  }
    catch (exception const& e) {
    constructor_error_handler();
    }
}

Initialised constructor.

Initialised with an AdaptiveHistogram.

Parameters:
adhA subpaving to copy as the subpaving to be managed.
Precondition:
adh has a subpaving.
Postcondition:
The piecewise constant function constructed has a subpaving that is a copy of the subpaving managed by adh and label the same as the label for adh. The value mapped onto each node of this is equal to the count/(volume) of the equivalent node of the subpaving managed by adh after normalising for the total count in the whole histogram, ie the getTotalIntegral() = 1.0.
                : rootPaving(NULL), label(0)
{
  try {
        // check adh has paving
    if (!adh.hasSubPaving()) {
      throw subpavings::NullSubpavingPointer_Error(
      "PiecewiseConstantFunction::PiecewiseConstantFunction(const AdaptiveHistogram&)");
    }
        rootPaving = new RealMappedSPnode(*adh.getSubPaving());
    label = adh.getLabel();
    
    _normalise();
  }
    catch (exception const& e) {
    constructor_error_handler();
    }
  
}
PiecewiseConstantFunction::PiecewiseConstantFunction ( unsigned long int  numLeaves,
const MCMCPartitionGenerator partitioner,
const ivector &  v,
int  lab = 0 
)

Initialised constructor to make a random un-normalised function shape.

Throws a MalconstructedBox_Error if the box is not suitable as the basis of a subpaving (eg, box has no dimensions, or the box has a thin interval on at least one dimension).

Tries to make a random partition for this with numLeaves pieces. Throws a UnfulfillableRequest_Error if a partition with required numLeaves pieces could not be generated within a fixed number of tries. The possible partiions that can be generated are limited by the splittability of the pieces of this; some numbers of pieces will simply be unachievable, others will be so unlikely that it takes too long to find them.

If a shape with numLeaves pieces can be found, the ranges on the pieces are set randomly. If numLeaves > 1, then these random ranges emulate a kind of random unnormalised piecewise constant density estimate.

Note:
This will be unnormalised.
Parameters:
numLeavesThe number of pieces to aim for in this.
partitionerThe object responsible for generating the random partition of this.
vThe box to use for the subpaving to be managed.
labThe label for this (defaults to 0).
Postcondition:
This is unnormalised with a subpaving that consists of numLeaves pieces with a box like v) and the range on each piece has been randomly derived.
          : rootPaving(NULL), label(lab)
{
  gsl_rng* r = NULL;
  try {
    
    std::string errorMsg("PiecewiseConstantFunction::PiecewiseConstantFunction(");
    errorMsg += "unsigned long int, const MCMCPartitionGenerator& const ivector&, int)";
    
        // check the box here
        if (!checkBox(v)) {
      throw subpavings::MalconstructedBox_Error(errorMsg);
    }
    
    bool success = false;
    size_t maxTries = (numLeaves < 1000 ? numLeaves : numLeaves/100);
    size_t t = 0;
    
    while ( !success && (t < maxTries) ) {
      if (NULL != rootPaving) delete rootPaving;
      rootPaving = new RealMappedSPnode(v, real(0.0)); 
      
      #if(0) // the uniform split
      success = rootPaving->randomSplitRootAtLeast(
            numLeaves, partitioner);
      #endif
      #if(1) // the natural split
      success = rootPaving->randomNaturalSplitRootAtLeast(
            numLeaves, partitioner);
      #endif
      t++;
    }
    
    if (!success) {
      throw subpavings::UnfulfillableRequest_Error(
        errorMsg + ":\nCould not get a shape with required numLeaves");
    }
      
    r = gsl_rng_alloc (gsl_rng_mt19937);
    unsigned long int seed = 1234;
    gsl_rng_set(r, seed); 
    
    // use r to put random ranges on this
    rootPaving->setRandomRange(r);
    
    // note that this is not normalised
    
    try {
      gsl_rng_free(r);
      r = NULL;
    }
    catch  (...) {} // catch and swallow
  }
    catch (exception const& e) {
    try {
      if (NULL != r) {
        gsl_rng_free(r);
        r = NULL;
      }
    }
    catch  (...) {} // catch and swallow
    constructor_error_handler();
    }
  
}

Member Function Documentation

void PiecewiseConstantFunction::allocateRanges ( const std::vector< cxsc::real > &  rangesToAllocate)

Recursively allocate a collection of ranges to this and children.

Allocation order is this, left child with remainder of allocation, right child with remainder.

{
  // checks:  is there a root paving, is the string properly formed?
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::allocateRanges(...)");
  }
  RealMappedSPnode temp(*getSubPaving()); // copy to temp
  try {
    getSubPaving()->allocateRanges(rangesToAllocate);
     
  }
  catch (std::invalid_argument const& ia) {
    cerr << ia.what() << endl;
    handleSPError(temp);
  }
  
  // any other exceptions are unhandled
}
cxsc::real PiecewiseConstantFunction::findCoverage ( const rvector &  pt) const

Find the coverage value for a data point.

The coverage value refers to the subpaving managed by this and is 1 - (sum of "area" of all leaf nodes with value > the value of the leaf node whose box contains pt)/ (sum of "area" of all leaf nodes) .

If the point is not in the root box of the subpaving managed by this, coverage = 0.0; If the point is in the box of the node associated with the lowest value in this, coverage = area lowest node / total area; If the point is in the box of the node associated with the highest value in this, coverage = 1.0.

Note:
The coverage value returned will be in the interval [0,1] whether this is normalised or not (ie it is a adjusted if necessary to be a proportion of the total integral).
Warning:
Coverage only makes sense for piecewise constant functions with non-negative values associated with all boxes (eg density estimates).

Throws a IncompatibleDimensions_Error if the dimensions of this and pt are not equal.

Parameters:
ptthe point to find coverage for
Returns:
coverage for the point given.
Precondition:
This must have a subpaving to manage.
Dimensions of pt and this must match.
hasNegativePiecewiseConstantValues() = false.
hasInfinitePiecewiseConstantValues() = false.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
          "PiecewiseConstantFunction::findCoverage(const rvector&)");
  }
  if (getDimensions() != (Ub(pt) - Lb(pt) + 1)) {
    throw IncompatibleDimensions_Error("PiecewiseConstantFunction::findCoverage(const rvector&)");
  }
  if (hasNegativePiecewiseConstantValues()) {
    throw std::runtime_error(
      "PiecewiseConstantFunction::findCoverage(const rvector&) : subpaving has an negative range");
  }
  if (getSubPaving()->hasInfiniteRangeInTree()) {
    throw std::runtime_error(
      "PiecewiseConstantFunction::findCoverage(const rvector&) : subpaving has an infinite range");
  }
  
  return _coverage(pt);
}

Get a copy of the subpaving managed by this.

Returns:
a copy of the subpaving managed by this.
Precondition:
hasSubPaving() == true.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
          "PiecewiseConstantFunction::getCopySubpaving()");
  }
  return RealMappedSPnode(*getSubPaving());
}

get the dimensions of the subpaving this manages.

Returns:
0 if this does not have a subpaving, else returns the dimensions of the subpaving.
{
  int retValue = 0;
  if (hasSubPaving()) {
    retValue = getSubPaving()->getDimension();
  }
  return retValue;
}

get volume of the root box of the subpaving this manages.

Returns:
volume of the root box of the subpaving this manages, or 0.0 if this has no subpaving.
{
  real retValue(0.0);
  if (hasSubPaving()) {
    retValue = getSubPaving()->nodeRealVolume();
  }
  return retValue;
}

Get the total integrated absolute error (IAE) between this and another PiecewiseConstantFunction.

The IAE is the total of the absolute value of the differences in the integrals of this and the other PiecewiseConstantFunction pcf.

Note:
that this method does not check that either this or rmsp have the same total integrals nor does it check that either is normalised.

If any of the values on the leaf nodes of the subpaving managed by this or pcf is Infinity, the value returned will be Infinity.

This method is symmetric, ie getIAE(pcf) == pcf.getIAE(*this).

Parameters:
pcfthe PiecewiseConstantFunction against which to calculate the IAE.
Returns:
total absolute area of the difference between function represented by this and function represented by pcf.
Precondition:
this and pcf have the same domain box.
Both this and pcf must have a subpaving to manage.
{
  if (!hasSubPaving() || !pcf.hasSubPaving()) {
    throw NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::getIAE()");
  }
  return getSubPaving()->getTotalAbsDiffLeafAreaRangeWithBox(
                  *(pcf.getSubPaving()) );
}

Gets the L1 distance between this and another PiecewiseConstantFunction.

The L1 distance is defined as the sum of the absolute values of the differences in 'area' represented by this and other over the union of their partitions (leaf nodes in subpaving managed).

Throws the following exceptions:

  • Throws a NullSubpaving_Error if either this or by other have no subpaving.
  • Throws a IncompatibleDimensions_Error if the dimensions and sizes of the root boxes of this and other are not the same.
Note:
this will not attempt to adjust for any difference in total integral between this and other: the L1 distance is simply taken as the difference between the 'areas' of the leaf boxes.
If this or other manages a subpaving in which there are leaf nodes with infinite value then the L1 distance between them will be infinite (cxsc::Infinity).
Parameters:
otherthe PiecewiseConstantFunction to calculate the L1 distance against.
Precondition:
Both this and other must have subpavings to manage and the root boxes of those subpavings must be the same.
Postcondition:
this will be unchanged.
{
  
  if (!hasSubPaving() || !(other.hasSubPaving())) {
    throw NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::getL1Distance(const PiecewiseConstantFunction&)");
  }
      
  return getSubPaving()->getL1Distance( *(other.getSubPaving()) );
}

Get the label.

Returns:
the label for this.
{return label;}

Get a vector of the leaf node levels.

Root is level 0, next level down is 1, etc.

Returns:
a vector of leaf levels, left to right order,
{
    IntVec levels; // empty container

    if (hasSubPaving()) {
        getSubPaving()->getLeafNodeLevels(levels, 0);
        //levels has now been filled in
    }
    return levels;
}

Get a string of the leaf node levels.

Root is level 0, next level down is 1, etc. Example return string "3,3,2,1"

Returns:
a comma separated string of leaf levels, left to right order
{
    string retValue = "";
    if (hasSubPaving())
        retValue = getSubPaving()->getLeafNodeLevelsString();

    return retValue;
}

Get a 'log likelihood' using function values from this and counts from spn.

If any of the pieces of this have negative values (including -ve infinity) then the value returned will be cxsc::SignalingNaN.

Otherwise, if any of the pieces of this where adh has points are have zero values then the value returned will be -cxsc::Infinity.

Otherwise, if any of the pieces of this where adh has points are infinite then the value returned will be cxsc::Infinity.

Note:
If testing the results, it seems to be more reliable to use gsl_isnan and gsl_isinf (both in gsl_math.h) than to use cxsc::IsSignalingNaN() and cxsc::IsInfinity(). Also note that both positive and negative cxsc::Infinity will give gsl_isinf true, but negative cxsc::Infinity will also give true for test < 0.0.
This is not normalised before the calculation: the user is responsible for normalising if that is required. Similarly, any pieces of this that have non-positive values will simply be ignored in the calculation: the user is responsible for ensuring that there are no non-positive values if this check is required.
Parameters:
adhis a histogram used to supply the information about counts to be associated with each piece of this in calculating the log-likelihood.
Returns:
the sum over the pieces of this with positive values in the intersection of the shape of the partition of this and the partion of adh of the product of the log of the value on the piece of this and the count on the corresponding bin of adh. Returns 0 if adh has no data in it. Return values can include cxsc::SignalingNaN, -cxsc::Infinity, and cxsc::Infinity.
Precondition:
this and adh have subpavings to manage and both supavings have the same box.
{
  if ( !hasSubPaving() || !adh.hasSubPaving() ) {
    throw NullSubpavingPointer_Error(
      "PiecewiseConstantFunction::getLogLikelihood(const AdaptiveHistogram&)");
  }
  return getSubPaving()->getLogLikelihood(*(adh.getSubPaving()));
}

Get maximum value of the constant for any piece in this.

Returns:
maximum value of the constant on any piece of this.
Precondition:
This has a subpaving to manage.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::getMaxPiecewiseConstant()");
  }
  return getSubPaving()->getMaxRangeForLeavesInTree();
}
cxsc::ivector PiecewiseConstantFunction::getRootBox ( ) const

Get the box of the subpaving managed by this.

Note:
with the present constructors, it is impossible for this to have a subpaving but for the subpaving to have no box.
Returns:
copy of the box of the subpaving managed by this.
Precondition:
hasSubPaving() == true.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
          "PiecewiseConstantFunction::getRootBox()");
  }
  return getSubPaving()->getBox();
}

Gets number of leaf nodes in the root paving.

Returns:
the total number of leaves in the subpaving managed by this. Returns 0 if this has no subpaving to manage.
{
  size_t result = 0;
  if (hasSubPaving()) {
    result = getSubPaving()->getNumberLeaves();
  }
  return result;
}

Get the total integral of the piecewise constant function represented by this.

The integral is calculated as the sum over all the leaves of the subpaving managed by this of the absolute value of the real range on the leaf multiplied by the volume of the box represented by the leaf.

If any of the values on the leaf nodes of the subpaving managed by this is Infinity, the value returned will be Infinity.

Returns:
total area between function and 0 for the function as represented by this.
Precondition:
This must have a subpaving to manage.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::getTotalIntegral()");
  }
  
  
  return getSubPaving()->getTotalAbsLeafAreaRangeWithBox();
}

Get whether the subpaving managed by this has infinite range values.

Returns:
true if the subpaving managed by this has infinite ranges, false otherwise. Returns false if this has no subpaving to manage.
{
  bool result = false;
  if (hasSubPaving()) result = getSubPaving()->hasInfiniteRangeInTree();
  return result;
}

Get whether the subpaving managed by this has negative range values.

Returns:
true if the subpaving managed by this has negative ranges, false otherwise. Returns false if this has no subpaving to manage.
{
  bool result = false;
  if (hasSubPaving()) result = getSubPaving()->hasNegativeRangeInTree();
  return result;
}

Get whether this has a subpaving to manage.

Note:
with the present constructors, it is impossible for this to have a subpaving but for the subpaving to have no box.
Returns:
true if this has a subpaving to manage. false otherwise.
{
    return ( getSubPaving() != NULL );
}
const PiecewiseConstantFunction PiecewiseConstantFunction::makeMarginal ( const std::vector< int > &  reqDims) const

Make a marginalised version of this.

Marginalises to take out the given dimensions and adjusts the constant values for each node of the subpaving managed by this so that the node vol x node value is the same as before marginalisation, and hence that the overall sum of (node vol x valu3) over all leaf nodes (getTotalIntegral()) is the same as before marginalisation.

Note:
allowed dimensions start at 1, ie dimensions to marginalise on can include 1, 2, ... dimensions of this.

Throws a NullSubpavings_Error if the subpaving that this manages is a NULL pointer.

Throws a NoBox_Error if the subpaving box is empty.

Throws an std::invalid_argument if the required dimensions reqDim is empty or contains dimensions outside the range of the dimensions of this.

Parameters:
reqDimsis a vector of the dimensions to include in marginal.
Returns:
A PiecewiseConstantFunction managing a subpaving which is the marginalised version of the subpaving managed by this.
Precondition:
This has a subpaving to manage and reqDims must be compatible with current dimensions.
Postcondition:
returned estimator will have sum over leaf nodes of (node vol x value) equal to that for this.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::makeMarginal(const std::vector<int>&)");
  }
  PiecewiseConstantFunction temp(*this);
  
  temp._marginalise(reqDims);
  return temp;
}

Make a normalised version of this.

Normalises this so that the sum over all the leaf nodes of the subpaving managed by this of the product of the volume of the box represented by the leaf node and the constant function value on that box is 1.0.

Throws a NullSubpavings_Error if the subpaving that this manages is a NULL pointer.

Throws an std::runtime_error if the subpaving managed by this has no 'area', ie getTotalIntegral() <= 0.

Returns:
The normalised version of this.
Precondition:
This has a subpaving to manage and getTotalIntegral() > 0.0.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::makeNormalised()");
  }
  if (getTotalIntegral() <= 0.0) {
    throw runtime_error(
      "PiecewiseConstantFunction::makeNormalised() : integral <= 0.0");
  }
  
  PiecewiseConstantFunction temp(*this);
  
  temp._normalise();
  return temp;
}

Return a PiecewiseConstantFunction that has subpaving that is the union of this's subpaving and the subpaving of another PiecewiseConstantFunction.

Throws a NullSubpavings_Error if the subpaving that this manages is a NULL pointer or if the subpaving managed by other is a NULL pointer.

Throws a NoBox_Error if the subpaving of this has no box or if the the subpaving of other has no box.

Throws an IncompatibleDimensions_Error if the subpaving boxes of this and other are not identical.

Parameters:
otheris the PiecewiseConstantFunction to make the union against.
Returns:
A PiecewiseConstantFunction that has a subpaving that is the union of the shape of the subpaving managed by this and the shape of the subpaving managed by other. this and other are unchanged.
Precondition:
Both this and other have subpavings with boxes to manage.
The boxes of the subpavings of this and other are the same.
{
  if ( !hasSubPaving() || !other.hasSubPaving() ) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::reshapeToUnion(const PiecewiseConstantFunction&)");
  }
  
  PiecewiseConstantFunction tmp(*this);
  tmp.reshapeToUnion(other);
  return tmp;
}

Make a PiecewiseConstantFunction by smearing this out so that no piece in the new function has value 0.0 but the total integral is the same as the total integral of this.

Pieces of this with value == 0.0 will get a small positive range in the returned PiecewiseConstantFunction such that the total integral on such pieces is totalSmear. Pieces of this with value <> 0.0 will get their ranges reduced in the returned PiecewiseConstantFunction so that the total integral over the whole of the returned PiecewiseConstantFunction is the same of the total integral of this.

Parameters:
totalSmearis the total integrated density to allocate over the pieces that have value 0.0.
Returns:
a PiecewiseConstantFunction that has the same integral as this where any piece of this that has zero value the returned function has a positive value such that the total value of the integral over these pieces is totalSmear.
Precondition:
this has a subpaving to manage.
totalSmearDensity > 0.0.
{
  PiecewiseConstantFunction temp(*this);
  temp.smearZeroValues(totalSmear);
  return temp;
}
void PiecewiseConstantFunction::marginalise ( const std::vector< int > &  reqDims)

Marginalised this.

Marginalises to take out the given dimensions and adjusts the constant values for each node of the subpaving managed by this so that the node vol x node value is the same as before marginalisation, and hence that the overall sum of (node vol x valu3) over all leaf nodes (getTotalIntegral()) is the same as before marginalisation.

Note:
allowed dimensions start at 1, ie dimensions to marginalise on can include 1, 2, ... dimensions of this.

Throws a NullSubpavings_Error if the subpaving that this manages is a NULL pointer.

Throws a NoBox_Error if the subpaving box is empty.

Throws an std::invalid_argument if the required dimensions reqDim is empty or contains dimensions outside the range of the dimensions of this.

Parameters:
reqDimsis a vector of the dimensions to include in marginal.
Postcondition:
This manages a subpaving which is the marginalised version of the subpaving managed by this before the operation and will have sum over leaf nodes of (node vol x value) (ie total integral) equal to that before the operation.
Precondition:
This has a subpaving to manage and reqDims must be compatible with current dimensions.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::marginalise(const std::vector<int>&)");
  }
  
  _marginalise(reqDims);

}

Normalise this.

Normalises this so that the sum over all the leaf nodes of the subpaving managed by this of the product of the volume of the box represented by the leaf node and the constant function value on that box is 1.0.

Throws a NullSubpavings_Error if the subpaving that this manages is a NULL pointer.

Throws an std::runtime_error if the subpaving managed by this has no 'area', ie getTotalIntegral() <= 0.

Precondition:
This has a subpaving to manage and getTotalIntegral() > 0.0.
Postcondition:
This has the same subpaving as before the operation and getTotalIntegral() == 1.0
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::normalise()");
  }
  if (getTotalIntegral() <= 0.0) {
    throw runtime_error(
      "PiecewiseConstantFunction::normalise() : integral <= 0.0");
  }
  
  
  
  _normalise();
  
}
const PiecewiseConstantFunction PiecewiseConstantFunction::operator* ( const PiecewiseConstantFunction rhs) const

Multiplication operator.

Throws a NullSubpavingPointer_Error if either this or rhs do not have a subpaving to manage.

Throws an IncompatibleDimensions_Error if the root boxes of this and rhs are not identical.

Note:
Note that if this and rhs have the same label the result of the operation will have that label, but if this and rhs do not have the same label, the result will get the default label (0).
Parameters:
rhsthe object to multiply this by.
Returns:
A PiecewiseConstantFunction that manages a subpaving that is the non-minimal union of the subpavings managed by this and rhs and the value on each node of that subpaving is the result of multiplying the values on the equivalent nodes of this by the values on the equivalent nodes of rhs. If the labels of this and rhs are the same, the returned object will have the same label as this; otherwise the returned object's label will be the default label (0).
Precondition:
Both this and rhs have subpavings to manage.
This and rhs have identical root boxes.
{
  PiecewiseConstantFunction result =(*this);

  result*= rhs;
  
  if ( label != rhs.getLabel() ) result.setLabel(0);
  
  return result;
}
const PiecewiseConstantFunction PiecewiseConstantFunction::operator* ( const cxsc::real &  mult) const

Scalar multiplication operator.

Throws a NullSubpavingPointer_Error if this does not have a subpaving to manage.

Parameters:
multthe value to multiply this by.
Returns:
A PiecewiseConstantFunction that manages a subpaving that the same as the subpaving managed by this and the value on each node of that subpaving is the result of multiplying the values on the equivalent nodes of this by mult. The label of this is unchanged.
Precondition:
This has a subpaving to manage.
{
  PiecewiseConstantFunction result =(*this);

  result*= mult;
  
  return result;
}
PiecewiseConstantFunction & PiecewiseConstantFunction::operator*= ( const PiecewiseConstantFunction rhs)

Multiplication of self operator.

Throws a NullSubpavingPointer_Error if either this or rhs do not have a subpaving to manage.

Throws an IncompatibleDimensions_Error if the root boxes of this and rhs are not identical.

Parameters:
rhsthe object to multiply this by.
Precondition:
Both this and rhs have subpavings to manage.
This and rhs have identical root boxes.
Postcondition:
this manages a subpaving that is the non-minimal union of the subpavings managed by this and rhs and the value on each node of the subpaving is the result of multiplying the values on the equivalent nodes of this by the values on the equivalent nodes of rhs before the operation. The label of this is unchanged.
{
  
  if( !hasSubPaving() || !(rhs.hasSubPaving()) ) {
    throw subpavings::NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::operator*= (const PiecewiseConstantFunction&)");
  }
  
  getSubPaving()->operator*=( *(rhs.getSubPaving()) );
  return *this;
}
PiecewiseConstantFunction & PiecewiseConstantFunction::operator*= ( const cxsc::real &  mult)

Self-scalar multiplication operator.

Throws a NullSubpavingPointer_Error if this does not have a subpaving to manage.

Parameters:
multthe value to multiply this by.
Precondition:
This has a subpaving to manage.
Postcondition:
this manages a subpaving that is the same as the subpaving managed by this before the operation and the value on each node of the subpaving is the result of multiplying the values on the equivalent nodes of this by mult. The label of this is unchanged.
{
  if( !hasSubPaving() ) {
    throw subpavings::NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::operator*= (const cxsc::real&)");
  }
  
  getSubPaving()->operator*=( mult );
  return *this;
}
const PiecewiseConstantFunction PiecewiseConstantFunction::operator+ ( const PiecewiseConstantFunction rhs) const

Addition operator.

Throws a NullSubpavingPointer_Error if either this or rhs do not have a subpaving to manage.

Throws an IncompatibleDimensions_Error if the root boxes of this and rhs are not identical.

Note:
Note that if this and rhs have the same label the result of the operation will have that label, but if this and rhs do not have the same label, the result will get the default label (0).
Parameters:
rhsthe object to add to this.
Returns:
A PiecewiseConstantFunction that manages a subpaving that is the non-minimal union of the subpavings managed by this and rhs and the value on each node of that subpaving is the result of adding the values on the equivalent nodes of this and rhs. If the labels of this and rhs are the same, the returned object will have the same label as this; otherwise the returned object's label will be the default label (0).
Precondition:
Both this and rhs have subpavings to manage.
This and rhs have identical root boxes.
{
  PiecewiseConstantFunction result =(*this);

  result+= rhs;
  
  if ( label != rhs.getLabel() ) result.setLabel(0);
  
  return result;
}
const PiecewiseConstantFunction PiecewiseConstantFunction::operator+ ( const cxsc::real &  add) const

Scalar addition operator.

Throws a NullSubpavingPointer_Error if this does not have a subpaving to manage.

Parameters:
addthe value to add to this.
Returns:
A PiecewiseConstantFunction that manages a subpaving that the same as the subpaving managed by this and the value on each node of that subpaving is the result of adding add to the values on the equivalent nodes of this. The label of this is unchanged.
Precondition:
This has a subpaving to manage.
{
  PiecewiseConstantFunction result =(*this);

  result+= add;
  
  return result;
}
PiecewiseConstantFunction & PiecewiseConstantFunction::operator+= ( const PiecewiseConstantFunction rhs)

Addition to self operator.

Throws a NullSubpavingPointer_Error if either this or rhs do not have a subpaving to manage.

Throws an IncompatibleDimensions_Error if the root boxes of this and rhs are not identical.

Parameters:
rhsthe object to add to this.
Precondition:
Both this and rhs have subpavings to manage.
This and rhs have identical root boxes.
Postcondition:
this manages a subpaving that is the non-minimal union of the subpavings managed by this and rhs and the value on each node of the subpaving is the result of adding the values on the equivalent nodes of this before the operation and rhs. The label of this is unchanged.
{
  if( !hasSubPaving() || !(rhs.hasSubPaving()) ) {
    throw subpavings::NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::operator+= (const PiecewiseConstantFunction&)");
  }
  
  getSubPaving()->operator+=( *(rhs.getSubPaving()) );
  return *this;
}
PiecewiseConstantFunction & PiecewiseConstantFunction::operator+= ( const cxsc::real &  add)

Self-scalar addition operator.

Throws a NullSubpavingPointer_Error if this does not have a subpaving to manage.

Parameters:
addthe value to add to this.
Precondition:
This has a subpaving to manage.
Postcondition:
this manages a subpaving that is the same as the subpaving managed by this before the operation and the value on each node of the subpaving is the result of adding add to the values on the equivalent nodes of this. The label of this is unchanged.
{
  if( !hasSubPaving() ) {
    throw subpavings::NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::operator+= (const cxsc::real&)");
  }
  
  getSubPaving()->operator+=( add );
  return *this;
}
const PiecewiseConstantFunction PiecewiseConstantFunction::operator- ( const PiecewiseConstantFunction rhs) const

Subtraction operator.

Throws a NullSubpavingPointer_Error if either this or rhs do not have a subpaving to manage.

Throws an IncompatibleDimensions_Error if the root boxes of this and rhs are not identical.

Note:
Note that if this and rhs have the same label the result of the operation will have that label, but if this and rhs do not have the same label, the result will get the default label (0).
Parameters:
rhsthe object to subtract from this.
Returns:
A PiecewiseConstantFunction that manages a subpaving that is the non-minimal union of the subpavings managed by this and rhs and the value on each node of that subpaving is the result of subtracting the values on the equivalent nodes of rhs from the values on the equivalent nodes of this. If the labels of this and rhs are the same, the returned object will have the same label as this; otherwise the returned object's label will be the default label (0).
Precondition:
Both this and rhs have subpavings to manage.
This and rhs have identical root boxes.
{
  PiecewiseConstantFunction result =(*this);

  result-= rhs;

  if ( label != rhs.getLabel() ) result.setLabel(0);
  
  return result;
}
const PiecewiseConstantFunction PiecewiseConstantFunction::operator- ( const cxsc::real &  sub) const

Scalar subtraction operator.

Throws a NullSubpavingPointer_Error if this does not have a subpaving to manage.

Parameters:
subthe value to subtract from this.
Returns:
A PiecewiseConstantFunction that manages a subpaving that is the same as the subpaving managed by this and the value on each node of that subpaving is the result of subtracting sub from the values on the equivalent nodes of this. The label of this is unchanged.
Precondition:
This has a subpaving to manage.
{
  PiecewiseConstantFunction result =(*this);

  result-= sub;
  
  return result;
}
PiecewiseConstantFunction & PiecewiseConstantFunction::operator-= ( const PiecewiseConstantFunction rhs)

Subtraction from self operator.

Throws a NullSubpavingPointer_Error if either this or rhs do not have a subpaving to manage.

Throws an IncompatibleDimensions_Error if the root boxes of this and rhs are not identical.

Parameters:
rhsthe object to subtract from this.
Precondition:
Both this and rhs have subpavings to manage.
This and rhs have identical root boxes.
Postcondition:
this manages a subpaving that is the non-minimal union of the subpavings managed by this and rhs and the value on each node of the subpaving is the result of subtracting the values on the equivalent nodes of rhs from the values on the equivalent nodes of this before the operation. The label of this is unchanged.
{
  
  if( !hasSubPaving() || !(rhs.hasSubPaving()) ) {
    throw subpavings::NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::operator-= (const PiecewiseConstantFunction&)");
  }
  
  getSubPaving()->operator-=( *(rhs.getSubPaving()) );
  return *this;
}
PiecewiseConstantFunction & PiecewiseConstantFunction::operator-= ( const cxsc::real &  sub)

Self-scalar subtraction operator.

Throws a NullSubpavingPointer_Error if this does not have a subpaving to manage.

Parameters:
subthe value to subtract from this.
Precondition:
This has a subpaving to manage.
Postcondition:
this manages a subpaving that is the same as the subpaving managed by this before the operation and the value on each node of the subpaving is the result of subtracting sub from the values on the equivalent nodes of this. The label of this is unchanged.
{
  if( !hasSubPaving() ) {
    throw subpavings::NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::operator-= (const cxsc::real&)");
  }
  
  getSubPaving()->operator-=( sub );
  return *this;
}
const PiecewiseConstantFunction PiecewiseConstantFunction::operator/ ( const PiecewiseConstantFunction rhs) const

Division operator.

Throws a NullSubpavingPointer_Error if either this or rhs do not have a subpaving to manage.

Throws an IncompatibleDimensions_Error if the root boxes of this and rhs are not identical.

Note:
Note that if this and rhs have the same label the result of the operation will have that label, but if this and rhs do not have the same label, the result will get the default label (0).
If any of the nodes of the subpaving managed by rhs have a value of 0.0 on them, then the PiecewiseConstantFunction returned will manage a subpaving that has nodes with infinite values on them (the result of dividing by 0.0).
Parameters:
rhsthe object to divide this by.
Returns:
A PiecewiseConstantFunction that manages a subpaving that is the non-minimal union of the subpavings managed by this and rhs and the value on each node of that subpaving is the result of dividing the values on the equivalent nodes of this by the values on the equivalent nodes of rhs. If the labels of this and rhs are the same, the returned object will have the same label as this; otherwise the returned object's label will be the default label (0).
Precondition:
Both this and rhs have subpavings to manage.
This and rhs have identical root boxes.
{
  PiecewiseConstantFunction result =(*this);

  result/= rhs;

  if ( label != rhs.getLabel() ) result.setLabel(0);
  
  return result;
}
const PiecewiseConstantFunction PiecewiseConstantFunction::operator/ ( const cxsc::real &  div) const

Scalar division operator.

Throws a NullSubpavingPointer_Error if this does not have a subpaving to manage.

Parameters:
divthe value to multiply this by.
Returns:
A PiecewiseConstantFunction that manages a subpaving that the same as the subpaving managed by this and the value on each node of that subpaving is the result of dividing the values on the equivalent nodes of this by div. The label of this is unchanged.
Precondition:
This has a subpaving to manage.
div != 0.0.
{
  PiecewiseConstantFunction result =(*this);

  result/= div;

  return result;
}
PiecewiseConstantFunction & PiecewiseConstantFunction::operator/= ( const PiecewiseConstantFunction rhs)

Division of self operator.

Throws a NullSubpavingPointer_Error if either this or rhs do not have a subpaving to manage.

Throws an IncompatibleDimensions_Error if the root boxes of this and rhs are not identical.

Note:
If any of the nodes of the subpaving managed by rhs have a value of 0.0 on them, then after the division this will have nodes with infinite values on them (the result of dividing by 0.0).
Parameters:
rhsthe object to divide this by.
Precondition:
Both this and rhs have subpavings to manage.
This and rhs have identical root boxes.
Postcondition:
this manages a subpaving that is the non-minimal union of the subpavings managed by this and rhs and the value on each node of the subpaving is the result of dividing the values on the equivalent nodes of this by the values on the equivalent nodes of rhs before the operation. The label of this is unchanged.
{
  if( !hasSubPaving() || !(rhs.hasSubPaving()) ) {
    throw subpavings::NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::operator/= (const PiecewiseConstantFunction&)");
  }
  
  getSubPaving()->operator/=( *(rhs.getSubPaving()) );
  return *this;
}
PiecewiseConstantFunction & PiecewiseConstantFunction::operator/= ( const cxsc::real &  div)

Self-scalar division operator.

Throws a NullSubpavingPointer_Error if this does not have a subpaving to manage.

Parameters:
divthe value to divide this by.
Precondition:
This has a subpaving to manage.
div != 0.0.
Postcondition:
this manages a subpaving that is the same as the subpaving managed by this before the operation and the value on each node of the subpaving is the result of dividing the values on the equivalent nodes of this by div. The label of this is unchanged.
{
  if( !hasSubPaving() ) {
    throw subpavings::NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::operator/= (const cxsc::real&)");
  }
  if( div == cxsc::real(0.0) ) {
    throw std::invalid_argument(
    "PiecewiseConstantFunction::operator/= (const cxsc::real&)");
  }
  
  getSubPaving()->operator/=( div );
  return *this;
}

Make a .dot graph file.

Makes a simple .dot graph from the piecewise constant function using node names and also makes the .png image for this graph.

Postcondition:
a .dot file and a .png in the same directory as the program creating it was run in.
{
    bool success = false;
  if (hasSubPaving()) {
        success = getSubPaving()->outputGraphDot();

    }
    else {
        std::cerr << "Sorry, you can't make a graph without a root paving"
                << std::endl;
    }
  if (!success) {
    std::cerr << "Failed to make dot graph" << std::endl;
  }
}
void PiecewiseConstantFunction::outputLog ( const std::string &  s,
int  i,
int  prec = 5 
) const

Append current state of estimator to a txt log file.

Format is a tab-delimited file of numeric data. Output includes node contributions to unscaled EMP under COPERR and AIC and the changes in EMP that would result from splitting the node.

Parameters:
sthe name of the txt file to send output to.
ithe number of pass (ie, 0, 1, 2, 3 etc) in process.
precthe precision for output formatting. ie, number of decimal places.
{
    // To add output of the PiecewiseConstantFunction object to file
    ofstream os(s.c_str(), ios::app);         // append
    if (os.is_open()) {
    
    os << std::endl;
        os << "Pass " << i << std::endl; // numbering
        getSubPaving()->leavesOutputTabs(os, prec); // the output
    
    os.close();
    }
    else {
        std::cerr << "Error: could not open file named "
            << s << std::endl << std::endl;
    }
}
std::ostream & PiecewiseConstantFunction::outputToStreamTabs ( std::ostream &  os,
int  prec = 5 
) const

Output the subpaving managed by this to a given stream.

Format is a tab-delimited data giving details of leaf nodes.

Parameters:
osis a reference to the stream to output the histogramm to.
precthe precision for output formatting. ie, number of decimal places.
Returns:
a reference to the given stream.
{
  if (hasSubPaving()) {
    
    // have to use cxsc io manipulators
    os << cxsc::SaveOpt;
    os << cxsc::Variable << cxsc::SetPrecision(prec+2,prec);

    getSubPaving()->leavesOutputTabs(os); // the output
    
    os << cxsc::RestoreOpt;
  }
  
    return os;
}
cxsc::real PiecewiseConstantFunction::pointwiseExtension ( const rvector &  pt) const

Find the pointwise extension of the piecewise constant function for a given data point.

The pointwise extension is the value associated with the leaf node of the subpaving managed by this that has the box containing pt.

Note:
the pointwise extension is not adjusted if this is not normalised (getTotalIntegral() != 1.0): it is just the value associated with the leaf node containing pt no matter what the total integral of the function over the domain is.

If the point is not in the rootbox of the subpaving managed by this at all, the pointwise extension is 0; Throws a IncompatibleDimensions_Error if the dimensions of this and pt are not equal.

Parameters:
ptthe point to find pointwise extension for.
Returns:
the function value at the point.
Precondition:
This must have a subpaving to manage.
Dimensions of pt and this must match.
{
  
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
          "PiecewiseConstantFunction::pointwiseExtension(const rvector&)");
  }
  if (getDimensions() != (Ub(pt) - Lb(pt) + 1)) {
    throw IncompatibleDimensions_Error(
      "PiecewiseConstantFunction::pointwiseExtension(const rvector&)");
  }
  cxsc::real result(0.0);
  
  const RealMappedSPnode * container = 
        getSubPaving()->findContainingNode(pt);
        
  if (container != NULL) {
    result = container->getRange();
    
  }
    
  return result;
}

Change this so that the subpaving it manages is the union of this's subpaving and the subpaving of another PiecewiseConstantFunction.

Throws a NullSubpavings_Error if the subpaving that this manages is a NULL pointer or if the subpaving managed by other is a NULL pointer.

Throws a NoBox_Error if the subpaving of this has no box or if the subpaving of other has no box.

Throws an IncompatibleDimensions_Error if the subpaving boxes of this and other are not identical.

There will be no change in this if the subpaving of is everywhere less split than the subpaving of this.

Parameters:
otheris the PiecewiseConstantFunction to make the union against.
Precondition:
Both this and other have subpavings with boxes to manage.
The boxes of the subpavings of this and other are the same.
Postcondition:
the subpaving managed by this has the shape that is the union of its shape before the operation and the shape of the subpaving managed by other. other is unchanged.
{
  if ( !hasSubPaving() || !other.hasSubPaving() ) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::reshapeToUnion(const PiecewiseConstantFunction&)");
  }
  
  getSubPaving()->reshapeToUnion(*other.getSubPaving());
}
RVecData & PiecewiseConstantFunction::simulateData ( RVecData container,
size_t  numberToSimulate,
gsl_rng *  r 
) const

Simulator taking a random number generator argument.

Parameters:
ris a random number generator to use for the simulation.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
    "PiecewiseConstantFunction::simulateData(RVecData&, size_t, gsl_rng*)");
  }
  
  gsl_ran_discrete_t* gslpdfstruct = NULL;
  RealMappedSPnode::ConstPtrs* leavesPtr = NULL;
  std::vector< cxsc::ivector >* boxesPtr = NULL;
  double* weightsArrayPtr = NULL;
  
  try {/* the weights are the "areas" of the boxes of the 
     * leaves of the subpaving managed by this, area = range * volume */
    
    //copy container to tmp temporarily
    RVecData tmp(container.begin(), container.end());
    tmp.reserve(container.size() + numberToSimulate);
     
    leavesPtr = new RealMappedSPnode::ConstPtrs();
    getSubPaving()->getConstLeaves(*leavesPtr);

    size_t sizeWeights = leavesPtr->size();
    
    boxesPtr = new std::vector< cxsc::ivector >();
    boxesPtr->reserve(sizeWeights);
    weightsArrayPtr = new double [sizeWeights];
    
    size_t index = 0;
    for (RealMappedSPnode::ConstPtrsItr it = leavesPtr->begin();
          it < leavesPtr->end();
          ++it, ++index) {
      // put box into boxes and weight into weightsArray
      boxesPtr->push_back( (*it)->getBox() );
      weightsArrayPtr[index] = _double((*it)->getRealAreaRangeWithBox());
    }
    
    try {
      delete leavesPtr;
      leavesPtr = NULL;
    }
    catch(...) {}// catch and swallow
    
    gslpdfstruct = gsl_ran_discrete_preproc(sizeWeights, weightsArrayPtr);
    
    int d = getDimensions(); 
    for (size_t i = 0; i < numberToSimulate; ++i) {
      
      rvector thisrv(d);
      size_t proposedIndex = gsl_ran_discrete(r, gslpdfstruct);
      //thisrv = DrawUnifBox(r, boxes[proposedIndex]);
      tmp.push_back( DrawUnifBox(r, boxesPtr->at(proposedIndex)) );
    }  // data  should be in tmp
    
    assert(tmp.size() == container.size() + numberToSimulate);
    
    tmp.swap(container);
  
    try {
      delete boxesPtr;
      boxesPtr = NULL;
    }
    catch(...) {}// catch and swallow
    try {
      delete [] weightsArrayPtr;
      weightsArrayPtr = NULL;
    }
    catch(...) {}// catch and swallow
    
    try {
      gsl_ran_discrete_free (gslpdfstruct);
      gslpdfstruct = NULL;
    }
    catch(...) {}// catch and swallow
    
    return container;
    
  }
  catch(...) {
    try {
      if (gslpdfstruct != NULL) gsl_ran_discrete_free (gslpdfstruct);
      if (leavesPtr !=NULL) delete leavesPtr;
      if (boxesPtr !=NULL) delete boxesPtr;
      if (weightsArrayPtr !=NULL) delete [] weightsArrayPtr;
    }
    catch(...) {}// catch and swallow
    throw; // rethrow original exception
  }
}
RVecData & PiecewiseConstantFunction::simulateData ( RVecData container,
size_t  numberToSimulate,
long unsigned int  seed 
) const

Simulator taking a random number generator seed argument.

Simulation uses the gsl_rng_mt19937 generator and seed seed.

Parameters:
seedis a random number generator seed to use for the simulation.
{
  gsl_rng * r = NULL;
  
  try {
    /* make a generator for this mcmc run */
    r = gsl_rng_alloc (gsl_rng_mt19937);
    
    gsl_rng_set(r, seed);

    return simulateData(container, numberToSimulate, r);
    
    try {
      gsl_rng_free(r);
      r = NULL;
    } 
    catch(...) {}// catch and swallow
  }
  catch(...) {
    try {
      if (r != NULL) gsl_rng_free (r);
    }
    catch(...) {}// catch and swallow
    throw; // rethrow original exception
  }
}
RVecData & PiecewiseConstantFunction::simulateData ( RVecData container,
size_t  numberToSimulate 
) const

Simulator using default random number generator.

Simulation uses the gsl_rng_mt19937 generator and seed = 1234.

{
  long unsigned int seed = 1234;
  return simulateData(container, numberToSimulate, seed);
}
void PiecewiseConstantFunction::smearZeroValues ( cxsc::real  totalSmear)

Smear this out so that no piece has value 0.0 but the total integral is unchanged.

Pieces with value == 0.0 will get a small positive range such that the total integral on such pieces is totalSmear. Pieces with value <> 0.0 will get their values reduced by a proportion calculated so that the total integral over the whole of this is unchanged.

Parameters:
totalSmearis the total integrated density to allocate over the pieces that have value 0.0.
Precondition:
this has a subpaving to manage.
totalSmearDensity > 0.0.
Postcondition:
This has the same total integral as before the operation but any piece of this that had zero value before the operation now has a positive value such that the total value of the integral over the pieces which orignally had zero value is totalSmear.
{
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::smearZeroValues(cxsc::real)");
  }
  if (!(totalSmear > 0.0)) {
    throw std::invalid_argument(
        "PiecewiseConstantFunction::smearZeroValues(cxsc::real)");
  }
  
  std::pair<size_t, cxsc::real> emptyVolInfo 
        = getSubPaving()->getNonZeroBoxSummary();
  
  if(emptyVolInfo.first > 0) {
    cxsc::real nonZeroVolPropn = emptyVolInfo.second;
    if (nonZeroVolPropn < 1.0) {
      
      /* range for zeros is totalSmear/total empty volume*/
      real zeroRange = totalSmear/
        ((1.0 - nonZeroVolPropn)*getDomainVolume());
      
      real totalIntBefore = getTotalIntegral();
      if (!(totalSmear < totalIntBefore)) {
        throw std::invalid_argument(
          "PiecewiseConstantFunction::smearZeroValues(cxsc::real)");
      }
      real ratioRange = totalSmear/ totalIntBefore;
      
      getSubPaving()->smearRanges(zeroRange, ratioRange);
      
      real totalIntAfter = getTotalIntegral();
      
      this->operator*=(totalIntBefore/totalIntAfter);
      
    }
  }
  else throw std::runtime_error(
    "PiecewiseConstantFunction::smearZeroValues(cxsc::real): no non-zero pieces");
}
bool PiecewiseConstantFunction::splitToShape ( std::string  instruction)

Split this to a specified shape.

Note:
that ranges for each node in the revised shape will have to be set explicitly, using allocateRanges().

Throws a NullSubpavings_Error if the subpaving that this manages is a NULL pointer.

Throws a NoBox_Error if the subpaving box is empty.

Prints a message to the standard error output if the instruction could not be carried out.

Parameters:
instructionspecifies the required shape, eg "3, 3, 2, 1"
Returns:
true if the split was successful, false otherwise
Precondition:
hasSubPaving() == true.
Postcondition:
this has subpaving with shape specified by instruction and the function value mapped to each node in the subpaving is the same as the value mapped to the root box before the operation.
{
  
  // checks:  is there a root paving, is the string properly formed?
  if (!hasSubPaving()) {
    throw NullSubpavingPointer_Error(
        "PiecewiseConstantFunction::splitToShape()");
  }
  bool success = false;
  RealMappedSPnode temp(*getSubPaving()); // copy to temp
  try {
    if (instruction.length() == 0) {
      throw std::invalid_argument(
        "PiecewiseConstantFunction::splitToShape() : No instruction");
    }

    std::string legal(", 0123456789");
    if (instruction.find_first_not_of(legal) != std::string::npos) {
      throw std::invalid_argument(
        "PiecewiseConstantFunction::splitToShape() : Illegal character");
    }

    // all seems to be okay, we can start splitting the root paving
    
    success = getSubPaving()->splitRootToShape(instruction);
    
    if (!success) {
      
      handleSPError(temp);
     }
     
  }
  catch (std::invalid_argument const& ia) {
    cerr << ia.what() << endl;
    handleSPError(temp);
    success = false;
  }
  catch (std::logic_error const& le) {
    cerr << le.what() << endl;
    handleSPError(temp);
    success = false;
  }
  return success;
  // any other exceptions are unhandled
}

Get a string summary of this estimator's properties.

A string description of this. Includes the address of the subpaving managed but not details of that subpaving.

Returns:
the string summary.
{
  std::ostringstream oss;
  
  oss << "This address = " << (this) << endl;
  oss << "This label = " << label << endl;
  if (hasSubPaving()) oss << "Address of subpaving is " << getSubPaving() << endl;
  else oss << "Subpaving is NULL" << endl;
  
  return oss.str();
}

The documentation for this class was generated from the following files:
 All Classes Namespaces Functions Variables Typedefs Enumerations Friends