| Version: | 0.8.2 |
| Date: | 2026-06-15 |
| Title: | Ray-Based Mapping and Visualization of Level Sets (Excursion Sets) |
| Author: | Richard Raubertas [aut, cre] |
| Maintainer: | Richard Raubertas <rrprf@emvt.net> |
| License: | GPL (≥ 3) |
| Depends: | R (≥ 3.5.0) |
| Imports: | graphics, stats, tools, utils, proxy, withr |
| Suggests: | ggplot2, randomForest, palmerpenguins, knitr, rmarkdown |
| Description: | An (upper) level set of a function is the set of inputs for which the function value is at or above a specified threshold. (Also called an excursion set). Applications of level sets include confidence or credible regions for parameters of statistical models, where the function is the likelihood or posterior density; regions where classification rules assign high probability to a given class; and scientific or engineering models where one is interested in input regions for which model output is above a threshold. This package maps out the boundary of a level set by finding its intersections with collections of 1-dimensional rays, generalizing a proposal by Kim and Lindsay (Statistica Sinica 21:923-948, 2011). Tools are provided to generate rays, find intersections, and visualize results. The package makes few assumptions about the studied function: it may be discontinuous, it may have a complicated feasible region, and the target level set may be non-convex or have multiple, disconnected parts. Vignettes describe package usage and show examples with two to five input space dimensions. |
| LazyData: | yes |
| VignetteBuilder: | knitr, rmarkdown |
| NeedsCompilation: | no |
| Packaged: | 2026-06-16 03:31:07 UTC; rfr |
| Repository: | CRAN |
| Date/Publication: | 2026-06-22 14:30:02 UTC |
Initialization of Package Objects
Description
Initialization of package objects. The function is designed to work whether or not it is actually called within a package environment. This is an internal utility function, not intended to be called by package users.
Usage
.onLoad(libname=NULL, pkgname=NULL)
Arguments
libname, pkgname |
Optional character scalars. See |
Value
NULL, invisibly.
See Also
Extract Lines/Point Pairs from an Object
Description
Extract lines/point pairs from an object inheriting from class
inpPairs, returning an object of the same class. This is an
internal utility method, not intended to be used by package users.
Usage
## S3 method for class 'inpPairs'
x[i, j, ..., drop=TRUE]
Arguments
x |
An object inheriting from class |
i |
Index vector specifying which _pairs/lines_ in |
j |
Unused, only present for compatibility with the generic. An error will be raised if provided. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
drop |
Logical scalar. If TRUE (the default), points that are not part of any
pair will be dropped. If FALSE, all points in |
Details
Note that indexing refers to the point _pairs_ in x, not to the
individual points.
If drop is TRUE the internal order of points in the returned object
may be different than in x.
Value
An object with the same class as x, containing the extracted
pairs/lines.
See Also
Extract Points from a '*Pts' Object
Description
Extract points from a *Pts object (which all inherit from
inpPts), returning an object of the same class. This is an
internal utility method, not intended to be used by package users.
Usage
## S3 method for class 'inpPts'
x[i, j, ..., drop=FALSE]
Arguments
x |
An object of one of the |
i |
Index vector specifying which points in |
j |
Unused, only present for compatibility with the generic. An error will be raised if provided. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
drop |
Ignored, only present for compatibility with the generic. |
Value
An object with the same class as x, containing the extracted
points.
See Also
Extract Response Profiles from a 'respProfiles' Object
Description
Extract response function profiles from a respProfiles object.
This is an internal method, package users should call the generic
function.
Usage
## S3 method for class 'respProfiles'
x[i, j, ..., drop=FALSE]
Arguments
x |
An object inheriting from class |
i |
Index vector specifying which lines/rays are to have their profiles extracted. |
j |
Unused, only present for compatibility with the generic. An error will be raised if provided. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
drop |
Ignored, only present for compatibility with the generic. |
Details
Any lines/rays in x that are not selected by i are dropped
from the result. (This is required since all lines in a
respProfiles object must have profiles in the object.) Therefore
the line column in respInfo() applied to the result will
refer to the reduced set of lines, not the original.
Value
An object with the same class as x, containing the profiles for the
specified lines/rays.
See Also
Absolute (Difference Scale) Tolerance Values
Description
Calculate absolute (difference scale) tolerance values to associate with a
set of numeric values. The idea is that differences from x of that
magnitude or less should be treated as effectively 0.
Usage
absTol(x, tol)
Arguments
x |
Numeric vector. |
tol |
Vector with two non-negative scalars. The first value will be multiplied
with |
Value
Numeric vector like x, containing the associated tolerance values.
Note
If x contains infinite values and tol[1] is not 0, the
result will be set to the maximum finite value,
.Machine$double.xmax.
See Also
inpTol, respTol extract tol values from
fnSpec and related objects. lsetPkgOpt
describes how tolerances are used in this package.
base::all.equal.numeric uses a different, non-continuous function
of x to decide equality.
Examples
# The absolute tolerance is the larger of the minimum absolute tolerance
# and the relative tolerance:
x <- c(10000, 1000, 1, 0.001, 0.00001, 0)
absTol(x, tol=c(1e-3, 1e-4))
# When 'tol[1]' is 0, only absolute tolerance, 'tol[2]', is used,
# regardless of 'x' values:
absTol(c(-Inf, -10, -1, 0, 1, 10, Inf, NA), tol=c(0, 1e-6))
# Comparison to 'base::all.equal'.
x0 <- 1e-2
x <- x0 + 1e-3*c(-1, 0, 1)
atol <- absTol(x, tol=c(x0, 1e-8)) # ~1e-4
(abs(x - x0) <= atol) # FALSE, TRUE, FALSE
# 'base::all.equal' uses a discontinuous criterion that makes it less
# sensitive to differences on the down side than the up side, when 'x'
# is close in magnitude to 'tolerance'.
all.equal(x0-1e-3, x0, tolerance=x0) # TRUE
all.equal(x0, x0, tolerance=x0) # TRUE
all.equal(x0+1e-3, x0, tolerance=x0) # "Mean relative difference: 0.09090909"
# Effectively TRUE, TRUE, FALSE
Absolute Tolerances for Input Space Coordinates
Description
Derive absolute tolerances for coordinates in each input space dimension, based on the magnitudes of coordinates for a set of points. This is an internal utility function, not intended to be called by package users.
Usage
absTolCoord(x, inptol, byPt=FALSE)
Arguments
x |
A matrix of coordinates for a set of points in input space. |
inptol |
|
byPt |
Logical scalar. If TRUE absolute tolerances are calculated separately for each point for each dimension. If FALSE, a single tolerance is calculated for each dimension using the maximum magnitude of its coordinates across points. |
Value
If byPt is FALSE, a 1-row matrix with an abolute tolerance value
for each dimension of the input space.
If byPt is TRUE, a matrix with the same shape as x, with an
absolute tolerance for each coordinate of each point.
See Also
Tolerances for Positions along Rays
Description
Absolute numerical tolerances for position along a single ray or line segment. They are based on tolerances for the underlying coordinates in each dimension, and the weight of each dimension in a ray's direction. This is an internal utility function, not intended to be called by package users.
Usage
absTolPosn_1line(posn, x0, x1, xvec=x1-x0, inptol)
Arguments
posn |
Vector of position values. |
x0, x1 |
1-row matrices with the coordinates of the points representing positions 0 and 1 along the ray or line segment. |
xvec |
1-row matrix that when added to |
inptol |
Two-row matrix. The first row specifies a relative tolerance for each input space dimension and the second row the minimum absolute tolerance. |
Value
Vector with the same length as posn, containing the absolute
tolerance for each position value.
See Also
absTol, absTolCoord, inpTol.
absTol_posn handles multiple lines.
Tolerances for Positions along Lines or Rays
Description
Absolute numerical tolerances for positions along lines or rays. They are based on tolerances for the underlying coordinates in each dimension, and the weight of each dimension in a line's direction. This is an internal utility function, not intended to be called by package users.
Usage
absTol_posn(posn, lineidx=NULL, x0, x1, inptol)
Arguments
posn |
Vector of position values. |
lineidx |
Optional vector of line or ray numbers (indices into rows of |
x0, x1 |
Matrices with the coordinates of the position 0 ( |
inptol |
2-row matrix with tolerance specifications for input space coordinates. |
Details
The arguments and code structure are similar to proj_pt_to_line.
Value
If lineidx is NULL: Numeric matrix with one row per position and
one column per line/ray. Element [i,j] contains the absolute
tolerance for position i on line j.
If lineidx is specified: Vector with one absolute tolerance for
each position in posn, along the line specified by the
corresponding element of lineidx.
See Also
absTol, absTolCoord, inpTol.
absTolPosn_1line is specialized for boundary search helper
functions.
Rays Based on the Coordinate Axes of Input Space
Description
Create rays based on the unit vectors for the coordinate axes, and sums and differences of those vectors.
Usage
axisRays(spec=NULL, degree=1, scale=NULL, origin=NULL, rect=NULL,
slice=NULL, named=(degree <= 3), warnDegenerate=TRUE)
Arguments
spec |
An |
degree |
Non-negative integer less than or equal to the dimension of the input
space (or of |
scale |
Optional |
origin |
Vector or 1-row matrix with the coordinates of a single point in input
space. All rays start from this point (i.e., it is position 0 for each
ray). |
rect |
Optional |
slice |
Optional vector or 1-row matrix specifying one slice of input space. (See
|
named |
Logical scalar. If TRUE the rays will be named; see DETAILS. |
warnDegenerate |
Integer or logical scalar. When |
Details
Let d denote the number of input space dimensions. If slice
is specified, rays are initially generated in the lower
d_s-dimensional hyperplane defined by slice, where
d_s is the number of NA coordinates in slice. At the end
the rays are brought back to the original d-dimensional input space
by including the d - d_s fixed coordinates from slice. (If
slice is not specified, set d_s = d in what follows.)
Rays are generated by the following steps.
Axis ray vectors of degree 1 are the unit vectors along the d_s
coordinate axes. Specifying degree=2 adds unit vectors pointing
along both diagonals for each pair of coordinate axes; degree=3
also adds unit vectors pointing along the four 3-way diagonals for each
set of three coordinate axes, and so on. The total number of vectors
depends on d_s and degree: sum((2^(1:degree)) *
choose(d_s, 1:degree)) / 2. It increases rapidly with degree.
If scale is specified, these unit vectors are then scaled and/or
rotated to reflect the relative scales and correlations among the input
space dimensions: They are multiplied by the inverse of matrix W
from scale. (This "unstandardizes" generic unit vectors to the
natural scale of the input space.)
Vectors are then translated by adding origin to their coordinates.
Finally, if rect is specified, vector lengths are adjusted so that
position 1 for each ray is its intersection with the boundary of
rect. Note that when origin itself is on the boundary of
rect, vectors pointing away from rect will lead to
degenerate rays (positions 0 and 1 being the same point). In that case a
vector pointing in the opposite direction will be tried. If that also
leads to a degenerate ray, the vector will be dropped.
The created rays are unique with respect to a sign change in their
directions; if ray r is included then the ray pointing in the
opposite direction is not.
If named is TRUE, rays will be named based on the names of the
input space dimensions in spec. However if scale includes
correlations between dimensions, the degree 1 rays are rotated relative to
the coordinate axes, so they will be renamed as rot1, rot2,
etc. Names for higher degree directions will be based on these.
Value
An inpRays object. The origin will be the point specified by
origin. The position 1.0 point for each ray will by default be
distance 1 from the origin, but distances may differ if scale or
rect is specified. Ray vectors of degree 1 will always be
orthogonal to each other.
See Also
Examples
oldopt <- lsetPkgOpt(reset=TRUE) # default options
spec <- fnSpec(inpnames=c("X1", "X2"))
layout(matrix(1:4, nrow=2, byrow=TRUE))
rays <- axisRays(spec, degree=2)
plot(rays, eqAxes=TRUE, main="Standard axis rays of degrees 1 & 2")
abline(h=0, v=0, lty=3)
# Effect of 'scale' (rescaling only).
scl <- inpScale(c(1, sqrt(5)), spec=spec)
# (Rays will be stretched in the X2 direction)
rays <- axisRays(spec, degree=2, scale=scl)
plot(rays, eqAxes=TRUE, main="Scaled axis rays")
abline(h=0, v=0, lty=3)
# Effect of 'scale' (rescaling and rotation).
scl <- inpScale(rbind(c(1, 2), c(2, 5)), spec=spec)
# (Rays will be rotated counterclockwise and stretched in the X2 direction.)
rays <- axisRays(spec, degree=2, scale=scl)
plot(rays, eqAxes=TRUE, main="Scaled & rotated axis rays")
abline(h=0, v=0, lty=3)
# 'scale' is applied before ray vectors are extended to the boundary of
# 'rect'.
rect <- inpRect(rbind(c(-1, 0), c(1, 2)), refpt=c(0.5, 0.5), spec=spec)
rays <- axisRays(spec, degree=2, scale=scl, rect=rect)
# Default ray origin is taken as reference point of 'rect'.
plot(rays, eqAxes=TRUE, main="Scaled & rotated axis rays, with 'rect'")
abline(h=0, v=0, lty=3)
layout(matrix(1))
#----- 3D example to illustrate 'slice'ing.
spec <- fnSpec(inpnames=c("X1", "X2", "X3"))
slice <- c(NA, NA, -2)
rays <- axisRays(spec, degree=2, slice=slice, origin=c(0, 0, -2)) # 4 rays
print(rays, vecForm=FALSE) # all rays lie in the slice with X3 = -2
# Specifying 'rect' and putting the ray origin on its boundary can lead
# to ray reversal or dropping rays:
rect <- inpRect(rbind(c(-1, 0, -2), c(1, 2, 3)),
refpt=c(1, 0, -2), # upper bdry of X1, lower of X2, X3
spec=spec)
rays <- axisRays(spec, degree=2, slice=slice, rect=rect,
warnDegenerate=FALSE)
print(rays, vecForm=FALSE) # 'X1', 'X1(-)X2' rays have been reversed
# and 'X1(+)X2' ray has been dropped
plot(rays, eqAxes=TRUE,
main="Axis rays (degrees 1 & 2), origin on bdry of 'rect'")
lsetPkgOpt(oldopt) # restore starting options
Negative of Rosenbrock's Banana Function in Two Dimensions
Description
List with components that set up a level set problem for the negative of Rosenbrock's banana function. The response function has a maximum value of 0 at the input point (x1, x2) = (1, 1). For illustration the level set of interest is defined by the -50 contour, which is non-convex and highly curved. Also for illustration, the feasible region is set to be the half-plane x1 >= -2.
Usage
banana_2dEx
Format
The list has components:
fobjfnObjobject with the response function and its gradient, input space specifications, and feasible region function.threshValue of the response function that defines the level set of interest (-50).
rect0inpRectobject with an initial hyper-rectangle in input space, to guide the search for the level set boundary.
Source
The code that creates the above list is included in the package, in the
location returned by system.file("data_create/banana_2dEx.create.r",
package="levelSets").
Intersections of Rays with the Boundary of a Level Set
Description
Identify the boundary of a level set by finding points where a set of rays intersect it. Use these to identify segments along each ray that appear to lie entirely in the level set (i.e., chords of the level set).
Usage
bdryFromRays(x, lsetthresh=NULL, rays, control=list())
Arguments
x |
|
lsetthresh |
Response value that defines the level set of interest. If |
rays |
An |
control |
Optional list with parameters to control the search process. See
|
Details
The level set of interest is defined as the set of input points at which
the response function has values greater than or equal to
lsetthresh. Along a given ray a boundary of the level set is
either (a) a point where the response function transitions from greater
than or equal to lsetthresh to less than lsetthresh, or vice
versa; or (b) a point where the ray crosses the boundary of the feasible
region of the response function, with a response value still at or above
lsetthresh. Both the level set and the feasible region are assumed
to be closed (although possibly unbounded) sets, so boundary points are
always feasible and have response values greater than or equal to
lsetthresh.
Points along rays are specified by their position. For a given
ray, position along it is measured in units of the length of the line
segment from the ray origin (defining position 0) to the ray's second
defining point, given by rayPosn1(rays) (position=1). See
inpRays.
For a given ray the response function is evaluated at positions specified
in control$initPosns. If any of those positions belongs to the
level set (and assuming the level set has non-negligible volume in the
input space), we know there is a segment of the ray, containing that
position, that lies in the level set. This function searches for the
limits of that segment in both directions. If none of the initial
positions belongs to the level set, or if a segment appears to extend
beyond the range of initPosns, positions in
control$initPosns2 are added. If the segment still appears to
extend further, the segment is marked as censored in that
direction. Otherwise the segment endpoint in that direction is a boundary
point of the level set.
Thus searching for level set boundary points using rays naturally leads to
obtaining line segments that belong to the level set, and that is the form
in which this function returns the result. Each segment is defined by its
two endpoints. An endpoint is either an actual boundary point of the
level set, or a censored boundary point if the level set appears to extend
beyond it in the direction of the segment. Censoring status for a pair of
endpoints is reported in the lsetcens1 and lsetcens2 columns
of the data frame returned by segInfo().
A given ray may have 0, 1, or >1 level set segments. The ability to find
segments, and to distinguish multiple short segments from a single long
one, depends on the range and spacing of the starting positions in
initPosns and initPosns2. In particular, if responses at a
consecutive pair of initPosns are on the same side of
lsetthresh, it is assumed that all of the points between them also
lie on that side. This may miss boundary crossings if the response
profile along the ray is not unimodal and the peaks or troughs are smaller
than the spacing between test positions. Adding additional values to
initPosns may allow multiple crossings to be found.
Although not required, it is highly recommended that the ray origin be a point in the level set. This will improve the chance that useful level set segments and boundary points will be found.
If control$bothDirections is TRUE and the rays have an associated
hyper-rectangle (rayRect(rays)), it is recommended that the ray
origin not be on the rectangle's boundary. Otherwise reversed rays are
likely to be degenerate and dropped, so the search for level set boundary
intersections in the reverse direction will be ineffective. Also in this
case, note that when a ray is reversed, position 1 on the reversed ray is
its intersection with the boundary of the rectangle. That position may
not have the same Euclidean distance from the ray origin as the original
ray (e.g. if the ray origin is not at the center of the rectangle).
Information about level set segments can be extracted from the return
value with segInfo(). Information about individual segment
endpoints can be extracted with respInfo() and ptCoord().
The lsetSegs class has summary, plot and pairs
methods to display the results. See ?lsetSegs for more
information.
Value
An object with S3 class lsetSegs. It contains pairs of points
where (a) each point in a pair lies along one of the rays in rays
(possibly with negative position if bothDirections is TRUE); (b)
each point in a pair belongs to the level set; and (c) all the points on
the line segment connecting them also appear to belong to the level set.
The goal is that the segment endpoints should lie on the boundary
of the level set. However this may not be possible if the boundary in the
direction of the line containing the segment lies outside the search
region determined by control components initPosns,
initPosns2, and bothDirections.
See Also
lsetSegs, respProfiles, fnObj,
inpRays, segInfo, respInfo,
srchControl. Functions axisRays and
randomRays generate useful sets of rays to explore the
boundary of the level set. lsetSegsCheck checks that points
within claimed level set segments actually do belong to the level set.
bdrySearch extends this function by adaptively selecting
multiple ray origins to better explore the full boundary of a level set.
slicedBdryFromRays extends this function by using search
rays restricted to one or more slices of the input space.
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
#----- 2D multimodal example (level set has two separate elliptical parts).
Ex <- dbl_ellipse_2dEx # see '?dbl_ellipse_2dEx'
fobj <- Ex$fobj
thresh <- Ex$thresh
# Specify the search region and generate some rays scaled to it.
rect1 <- inpRect(rbind(c(-5, -10), c(15, 12)), spec=fobj)
set.seed(1)
rays1 <- randomRays(50, origin=c(2, 1), rect=rect1)
segs1 <- bdryFromRays(fobj, rays=rays1, lsetthresh=thresh) # 'lsetSegs' object
summary(segs1)
plot(segs1, rect=rect1, main="Segments found along 50 random rays")
# Some segments cross the gap between level set parts. Check for and fix
# invalid segments.
chk <- lsetSegsCheck(segs1, fnobj=fobj, posns=(1:9)/10)
table(chk$validIn) # 6 invalid segments
table(chk$validOut) # all fixed, so ...
segs1 <- lsetSegs(chk)
summary(segs1)
plot(segs1, rect=rect1,
main="Segments along 50 random rays, invalid segs fixed")
# Generate a second set of rays with an origin in the 2nd ellipse, and
# find segments along them. Make use of what we've learned from 'segs1':
# - Scale the rays to a rectangle that bounds all the level set
# boundary points found so far.
rect2 <- segBoundingRect(segs1, expand=1.1)
rays2 <- randomRays(50, origin=c(5, 10), rect=rect2)
# - Since 'segs1' showed that the level set has multiple parts, it is a
# good idea to set control parameter 'initPosns' to a finer set of ray
# positions: the spacing between positions should be smaller than the
# distance between separate level set parts.
segs2 <- bdryFromRays(fobj, rays=rays2, lsetthresh=thresh,
control=list(initPosns=(0:10)/10))
chk <- lsetSegsCheck(segs2, fnobj=fobj, posns=(1:9)/10)
table(chk$validIn) # all valid
summary(segs2)
plot(segs2, rect=rect2, main="Segments found along 50 random rays, origin 2")
# Segments can be combined into a single 'lsetSegs' object.
segs12 <- c(segs1, segs2)
plot(segs12, rect=rect2,
main="Segments found along 100 random rays, 2 origins")
lsetPkgOpt(oldopt)
Ray-Based Exploration of the Boundary of a Level Set
Description
Identify the boundary of a level set by finding pairs of boundary points,
such that the line segment connecting each pair appears to lie entirely in
the level set. An adaptive, ray-based search is carried out. At each
step a new ray origin is chosen, rays from that origin are generated, and
their boundary intersection pairs are found. The choice of origins
attempts to explore as much of the boundary as possible. Results are
accumulated over all steps into an lsetSegs object, which is
returned along with the sequence of ray origins that were used.
Usage
bdrySearch(x, lsetthresh, rect, scale=NULL, initOrigin=NULL,
currentBdry=NULL, control=list())
Arguments
x |
|
lsetthresh |
Response function value that defines the level set of interest. |
rect |
|
scale |
Optional |
initOrigin |
Optional vector or 1-row matrix specifying the initial ray origin to use
in the search. It must belong to |
currentBdry |
Optional object containing existing information about the level set
boundary: either an |
control |
Optional list with parameters to control the search process. See
|
Details
See ?bdryFromRays for details about the search for level set
boundary intersections along individual rays.
For each new search origin, rays are generated based on
control$rayType and the associated parameters in control,
and modified according to scale. The search for level set boundary
intersections along each ray is in both directions from position 0, with
control$initPosns and control$initPosns2 applied separately
for each half-line. When the ray origin is in the level set, typically
this results in one or more segments along each line, whose endpoints are
boundary points of the level set.
The adaptive selection of new origins relies on success at finding level
set segments in previous steps (or in currentBdry): new candidate
origins are generated from the accumulated set of level set line segments
using control$originBias. From among the candidates one is
selected according to the method control$originCrit (described
below). The search stops when control$maxSteps is reached, or
earlier if the set of candidate origins is empty (e.g., if the search is
not finding level set boundary segments).
The maxproj criterion focuses the search for the level set boundary
in a particular direction in input space: the candidate origin that has
maximum position when projected onto the control$srchDirection
vector is selected. (Position is equal to the inner product of the
candidate vector with the search direction vector, divided by the square
of the length of the latter.) Note that the projection does not use the
scale argument to transform input space coordinates.
The other two criteria attempt to encourage wide exploration of the level
set. The maximindist criterion selects the candidate origin that
maximizes the minimum distance to any existing origin. Distance is
computed as Euclidean distance after transforming point coordinates
according to scale.
The minimaxdist criterion selects the candidate origin that
minimizes the maximum distance from any current boundary point to the
nearest (existing + new) origin. Distance is computed as Euclidean
distance after transforming point coordinates according to scale.
If requested by control$updateRect1 and control$updateScale,
at each step the search region rect and input scaling scale
will be updated. The updates are based on previously found level set
segments. The updates will be done only if at least d segments are
available, to avoid basing rect or scale on skimpy
information about the level set.
Value
List with components:
segs |
|
srchOrigins |
Matrix containing the coordinates of any search origins in
|
rect |
|
scale |
|
If argument currentBdry was provided, the return value will combine
the information in it with the new level set segments and origins.
See Also
bdryFromRays, lsetSegs,
srchControl. lsetSegsCheck checks the
assumption that points along each level set segment actually do belong to
the level set. slicedBdrySearch extends this function to do
a separate boundary search for each of a set of slices of the input space.
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
#----- 2D multimodal example (level set has two separate elliptical parts),
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
fobj <- Ex$fobj
thresh <- Ex$thresh
rect1 <- Ex$rect0
desc <- "Two-ellipse level set, with feasible region X1 \u2265 0"
# Boundary search with defaults:
srch1 <- bdrySearch(fobj, lsetthresh=-40, rect=rect1)
segs1 <- srch1$segs
srch1$srchOrigins # d^2 = 4 origins used, 2 rays per origin
summary(segs1) # 10 segments on 8 lines
plot(segs1, rect=srch1$rect, main=desc, sub=paste0("\nbdrySearch(): ",
"defaults"))
# Clear evidence that the level set has disconnected parts. Need to
# increase the density of initial positions along each ray to have a
# good chance of detecting that for individual rays.
srch1a <- bdrySearch(fobj, lsetthresh=-40, rect=rect1,
control=list(initPosns=(0:4)/4))
segs1a <- srch1a$segs
summary(segs1a) # 12 segments on 8 lines
plot(segs1a, rect=srch1a$rect, main=desc, sub=paste0("\nbdrySearch(): ",
"initPosns=(0:4)/4"))
# Use the 'control' argument to increase the number of search steps and rays.
srch2 <- bdrySearch(fobj, lsetthresh=-40, rect=rect1,
control=list(initPosns=(0:4)/4,
maxSteps=8, # increases number of origins
axisDegree=2)) # increases rays per origin
segs2 <- srch2$segs
srch2$srchOrigins # 8 origins used, 4 rays per origin
summary(segs2) # 46 segments on 32 lines
plot(segs2, rect=srch2$rect, main=desc, sub=paste0("\nbdrySearch(): ",
"initPosns=(0:4)/4, axisDegree=2, maxSteps=8"))
# Clear picture of boundaries of both parts of the level set.
# Check segment validity.
chk <- lsetSegsCheck(segs2, fnobj=fobj, posns=(1:4)/5)
table(chk$validIn) # All appear valid
lsetPkgOpt(oldopt) # restore previous settings
Ray Intersections with the Boundary of a Level Set
Description
For a given set of rays (fixed origin and ray directions), find the ray
intersections with a level set. This is a wrapper for
bdrySearch_fixed_rays that optionally expands the hyper-rectangle
associated with rays to attempt to resolve any censored level set
segments found along the rays. This is an internal utility function, not
intended to be called by package users.
Usage
bdrySearch_1origin(rays, fnobj, lsetthresh, control=list())
Arguments
rays |
|
fnobj |
|
lsetthresh |
Response function value that defines the level set of interest. |
control |
List with options to control the search process. The only component used
directly by this function is |
Details
The starting hyper-rectangle is rayRect(rays).
bdrySearch_fixed_rays() is called to find level set segments along
the rays in rays. If any of those segments is marked as censored
(i.e., the level set appears to extend beyond the segment endpoint(s)),
segBoundingRect() will be applied to the existing segments with
argument expand set to c(1.0, 2.0). A new inpRect
object will be defined as the enclosing hyper-rectangle for the union of
the previous one and the new one. (Thus, the search rectangle might
expand, but can never shrink.) rays will be rescaled so that
position 1.0 for each ray is on the boundary of the expanded rectangle,
and the level set segment search will be done again. This cycle will be
repeated up to control$updateRect2 times, or until there are no
censored segments.
Value
lsetSegs object containing level set segments found along the rays.
The inpRays() component of the object will have an associated
inpRect that may be expanded from the one for argument rays.
See Also
bdrySearch, slicedBdrySearch.
bdrySearch_1slice calls this function.
Ray-Based Exploration of the Boundary of One Slice of a Level Set
Description
Identify the boundary of a single slice of a level set, by finding pairs
of boundary points in the slice such that the line segment connecting each
pair appears to lie entirely in the level set. An adaptive, ray-based
search is carried out. At each step a new ray origin within the slice is
chosen, in-slice rays from that origin are generated, and their boundary
intersection pairs are found. The choice of origins attempts to explore
as much of the boundary as possible. Results are accumulated over all
steps into an lsetSegs object, which is returned along with the
sequence of ray origins that were used. This is an internal utility
function, not intended to be called by package users.
Usage
bdrySearch_1slice(x, lsetthresh, rect, scale, slice, initOrigin,
currentBdry=NULL, control)
Arguments
x |
|
lsetthresh |
Response function value that defines the level set of interest. |
rect |
|
scale |
|
slice |
1-row matrix specifying a single slice of input space. It may be the identity slice (no fixed-value dimensions). |
initOrigin |
1-row matrix specifying the initial ray origin to use in the search. It
must belong to |
currentBdry |
List containing existing information about the level set boundary. |
control |
List with parameters to control the search process *specifically for this
slice*. See |
All arguments are assumed to have been preprocessed by
srchsetup_args to put them in standard form and ensure that they
are mutually consistent. (So scale preserves point membership in
slice, slice intersects rect, and initOrigin
belongs to slice.)
Details
See ?bdrySearch for details.
All new search origins, rays, and boundary points will lie in
slice.
Value
List with components:
segs |
|
srchOrigins |
Matrix containing the coordinates of any origins in |
rect |
|
scale |
|
slice |
Same as the argument. |
If argument currentBdry was not empty, the return value will
combine the information in it with the new level set segments and origins.
However only currentBdry search origins and segments that also
belong to the slice will be included.
Note: There is no necessary connection between rows of srchOrigins
and position 0 points in inpLines(lsetSegs) or line/ray numbers in
respInfo(lsetSegs)$line. srchOrigins just lists the ray
origins used during the search. Segments found during the search may be
expressed in terms of reparameterized lines/rays, which are what will be
contained in inpLines(lsetSegs). (In particular for the 1D case;
see bdrySearch_1slice_1d.)
See Also
bdrySearch, slicedBdrySearch,
srchsetup_args, srchsetup_control,
srchControl, srchControl_1slice
Post-Process Boundary Search Results for 1d Input Spaces
Description
Post-process the result of bdrySearch_1slice in the case of a
1-dimensional input space (or a 1D slice of input space). This function
addresses the issue that all lines in 1D are equivalent, but
bdrySearch() with multiple steps treats the line for each step as
distinct. So merge overlapping/ contiguous segments if they are
consistent. This is an internal utility function, not intended to be
called by package users.
Usage
bdrySearch_1slice_1d(x)
Arguments
x |
List like the one created by |
Details
When x contains segments using multiple parameterizations of the 1D
slice, all segments are reexpressed in terms of their position using the
parameterization associated with the segment with smallest lower endpoint
coordinate.
This function then calls merge_segs() to do the actual consistency
check and merging. See the documentation for that function.
Value
List with components:
xmrg |
Object like |
mrgidx |
Vector parallel to |
incon_x |
Two-column matrix. Each row contains the indices of a pair of segments in
|
incon_xmrg |
Two-column matrix. Each row contains the indices of a pair of segments in
|
See Also
merge_segs, slicedBdrySearch,
bdrySearch_1slice, interval_merge
Helper Function for 'bdrySearch'
Description
Helper function for bdrySearch. Generate candidate ray origins
from one or more of: an inpRect object; an lsetSegs object;
or set of points in input space. Optionally restrict the candidates to a
specified slice of input space. This is an internal utility function, not
intended to be called by package users.
Usage
bdrySearch_cand_origins(fnobj, rect, pts=rectRefPt(rect),
lsetsegs=NULL, slice=NULL, lsetthresh, originBias, inclGrad=FALSE,
maxCand)
Arguments
fnobj |
|
rect |
|
pts |
Optional |
lsetsegs |
Optional |
slice |
Optional one-row matrix specifying a single slice of input space, to which
candidate origins will be restricted. It must intersect |
lsetthresh |
Response value that defines the level set of interest. It overrides any
threshold values specified in |
originBias |
Scalar in [0, 1], used only if |
inclGrad |
Logical scalar. If TRUE and |
maxCand |
The maximum number of candidate origins to return. If |
Details
Candidate ray origins are generated from pts and lsetsegs
separately, and then combined. If necessary the number of candidates is
reduced to maxCand by taking a systematic sample, starting with the
first.
If pts is specified, any that are not in rect are discarded
and the remaining points are treated as candidate origins. If
slice is specified, the points are projected onto the slice to
generate the candidates.
Generation of candidates from lsetsegs depends on whether
slice is specified. If not, two candidate origins are generated
from each level set segment: the points originBias of the way from
the segment's midpoint toward either endpoint. If slice is
specified, each segment is checked for whether it intersects the slice.
If it does, the intersection point is included as a candidate. If it does
not, then two candidate origins are generated using originBias as
previously described, and then projected onto the slice. Finally, any
candidates not in rect are discarded.
The requirement that all candidates belong to rect is because the
selected origin will define rays whose position 1.0 points will be their
intersection with the boundary of rect (see bdrySearch).
Value
A respPts object containing candidate origins, all belonging to
rect. If slice is specified all candidates will also lie in
that slice. The returned object may be empty if no valid candidates are
found.
See Also
bdrySearch, respPts,
bdrySearch_cand_select
Helper Function for 'bdrySearch'
Description
Given the existing origins, existing candidate origins, and new candidate
origins, select the next origin from among the (existing + new)
candidates. Return an updated set of origins (with the selected one
added) and remaining candidates (with the new candidates added and the
selected one removed). Selection is based on which candidate has the
highest value of the criterion specified by criterion. This is an
internal utility function, not intended to be called by package users.
Usage
bdrySearch_cand_select(curr_state, new_cand=NULL, new_bpts=NULL,
criterion=c("maximindist", "minimaxdist", "maxproj"), W,
lsetFirst=TRUE, maxCand, maxDist)
Arguments
curr_state |
List with components:
srchDirection : If |
new_cand |
|
new_bpts |
Optional matrix of new boundary points (points not in
|
criterion |
String specifying the criterion for selecting which (existing + new) candidate to take as the next origin. See DETAILS. |
W |
If |
lsetFirst |
Logical scalar. If TRUE (the default), candidate origins that belong to the level set are always preferred over those that do not, regardless of their criterion value. |
maxCand |
The maximum number of candidate origins to return. If |
maxDist |
Positive integer. Soft limit on the total number of elements allowed for
a distance matrix, during the selection of new origins. (Note: Not
universally enforced, only within |
Details
The selected new origin will be the existing or new candidate that
optimizes the criterion specified by criterion:
The maximindist criterion maximizes the minimum distance to any
existing origin. Distance is computed as Euclidean distance after
transforming point coordinates by matrix W.
The minimaxdist criterion minimizes the maximum distance of any
(existing + new) boundary point to the nearest (existing + new) origin.
The candidate merit in this case is the negative of the
maximum distance. Distance is computed as Euclidean distance after
transforming point coordinates by matrix W. Computing the
criterion exactly is expensive when the numbers of boundary points and
candidate origins is large. Therefore an approximation is used: only the
d boundary points with the largest distances to any existing origin
are included in the minimization.
The maxproj criterion maximizes the position of the new origin when
projected onto the line specified by srchDirection in
curr_state. (Position is equal to the inner product of the origin
vector with the search direction vector, divided by the square of the
length of the latter.) Note that the projection does not use any
transformation of input space coordinates.
Value
List with components:
curr_state |
List like the argument, updated to reflect the new candidates
|
cand_merit |
Vector of merit values for each of the existing + new candidate origins,
according to |
See Also
bdrySearch, bdrySearch_cand_origins,
bdrySearch_minimax_calc
Ray Intersections with the Boundary of a Level Set
Description
For a given set of rays (origin, ray directions, and position 1 points are all fixed), find the ray intersections with a level set. This is an internal utility function, not intended to be called by package users.
Usage
bdrySearch_fixed_rays(rays, fnobj, lsetthresh, profiles=NULL,
control=list())
Arguments
rays |
|
fnobj |
|
lsetthresh |
Response function value that defines the level set of interest. |
profiles |
Optional |
control |
List with options to control the search process. The only components
relevant to this function are |
Details
This is a helper function that underlies bdryFromRays,
bdrySearch, slicedBdryFromRays, and slicedBdrySearch.
It works with a single, fixed set of rays, and it assumes the arguments
have already been checked and put into standardized form.
Value
lsetSegs object containing level set segments found along the rays.
The inpRays() component of the object will be the same as argument
rays.
See Also
bdryFromRays, bdrySearch,
slicedBdryFromRays, slicedBdrySearch.
bdrySearch_1slice also calls this function.
Helper Function for 'bdrySearch_cand_select'
Description
Helper function for bdrySearch_cand_select, when the selection
criterion is minimaxdist. Calculates the (de)merit of each
candidate in cand, for a given set of boundary points and origins.
This is an internal utility function, not intended to be called by package
users.
Usage
bdrySearch_minimax_calc(bpts, origins=NULL, bo_mindist=NULL, cand,
candBlockSize, W)
Arguments
bpts |
Matrix with coordinates of current level set boundary points. |
origins |
Matrix with coordinates of existing origins. |
bo_mindist |
Vector of minimum distances from each boundary point to the origins in
|
cand |
Matrix with coordinates for candidate origins. |
candBlockSize |
The maximum number of candidates for which candidate-boundary points distances will be calculated at one time. This is used to avoid storing a huge distance matrix when both the number of candidates and number of boundary points are large. |
W |
Transformation matrix used when computing distances between points in input space. |
Value
List with components:
bo_mindist |
Vector of minimum distances from each boundary point to the origins in
|
cand_merit |
Vector of criterion values for the candidate origins. It is the negative
of the maximum distance of any boundary point to any origin, when a given
candidate is added to |
Helper Function for 'bdrySearch'
Description
Derive or update rect and scale objects to be used in level
set boundary search, from an existing set of level set segments. This is
an internal utility function, not intended to be called by package users.
Usage
bdrySearch_rect_scale(lsetsegs, rect=NULL, scale=NULL,
slice=rbind(rep(NA_real_, d)), updateRect, updateScale)
Arguments
lsetsegs |
Non-empty |
rect |
|
scale |
|
slice |
1-row matrix specifying a slice of input space. The slice must intersect
|
updateRect |
Numeric scalar. If >0, |
updateScale |
Numeric scalar, 0, 1, or 2. If 0, |
Details
This function assumes rect, scale and slice have been
preprocessed to be mutually consistent (say by srchsetup_args).
Only the dimensions of rect and scale corresponding to the
free dimensions of slice are updated.
Value
List with components rect and scale, possibly updated
inpRect and inpScale objects.
See Also
bdrySearch, segBoundingRect,
boundingRect
Helper Function for 'respProfiles'
Description
Find feasible region boundary crossings, and optionally level set boundary crossings, for a single line in input space, starting from its current profile. Add those crossings to the profile. This is an internal utility function, not intended to be called by package users.
Usage
bdry_1line(targ_fun, curr_prof)
Arguments
targ_fun |
Function that evaluates the response function at specified positions along
the line. See |
curr_prof |
pre- |
Details
The level set is defined by curr_prof$lsetThresh. If that is NA,
only feasible region boundary crossings are searched for.
Value
A pre-respProfiles list with all of the information in
curr_prof, augmented with any crossings found, and sorted by
posn.
See Also
respProfiles, profile_1line,
crossings, bdry_1line_intrsctn,
bdry_1line_newtestposn, merge_pre_respProfiles
Helper Function for 'bdry_1line'
Description
Find feasible region and/or level set boundary intersections for a single line, starting from the current line profile. Add those intersections to the profile. This is an internal utility function, not intended to be called by package users.
Usage
bdry_1line_intrsctn(curr_prof, targ_fun)
Arguments
curr_prof |
pre- |
targ_fun |
Function that evaluates the response function at specified positions along
the line. See |
Value
A pre-respProfiles list with all of the information in
curr_prof, augmented with any crossings found, and sorted by
posn. Info columns feasbdry and lsetbdry will be
updated.
See Also
bdry_1line, profile_1line,
crossings, merge_pre_respProfiles
Helper Function for 'bdry_1line'
Description
Helper function for bdry_1line. Given a pair of positions on a
single line, find new positions internal to the pair, that maximize and/or
minimize response in the interval. These are potentially new positions at
which to start a search for additional contour crossings. This is an
internal utility function, not intended to be called by package users.
Usage
bdry_1line_newtestposn(posn_pair, targ_fun, goal, abstol_pair, opttol)
Arguments
posn_pair |
Two-element vector of distinct, ordered positions along the line. |
targ_fun |
Function that evaluates the response function at specified positions along
the line. See |
goal |
One- or two-element character vector specifying what optimizations of
|
abstol_pair |
Two-element vector with absolute tolerances for the positions in
|
opttol |
Positive scalar, on the scale of |
Details
Optimization is done using stats::optimize.
Value
Two-column matrix with number of rows equal to length of goal.
Each row contains a (position, response) pair strictly internal to the
interval in posn_pair.
See Also
Helper Function for 'bdryFromRays' and 'lsetSegs'
Description
Helper function for bdryFromRays and lsetSegs. Given a
response function profile (including any detected boundary intersections)
for a single line, identify intervals along the line that appear to be
entirely in a level set. This is an internal utility function, not
intended to be called by package users.
Usage
bdry_1line_segs(prof, lineidx=NULL)
Arguments
prof |
A pre- |
lineidx |
Integer index for this line/ray within a future |
Details
This function does not search the line for interval limits (see
bdry_1line for that). It only examines the discrete set of line
points in prof.
A profile point is considered to belong to the level set if its
lset value (from prof$respInfo) is TRUE. A level set
segment consists of a run of consecutive profile points that all belong to
the level set, and is represented by the first and last points in the run.
Runs consisting of a single point are dropped (i.e., segment endpoints
must be distinct.) A given profile may have zero, one, or more than one
level set segment.
A segment is considered uncensored at one of its endpoints if the endpoint
belongs to the level set and either lsetbdry or feasbdry is
TRUE. It is considered censored otherwise. Therefore the censoring
indicator lsetcens for segment endpoints will never be NA.
The returned list sets the line column of respInfo and
pairInfo according to the lineidx argument.
Value
A pre-lsetSegs list with all the components of an lsetSegs
object for a single line, except inpLines. It contains zero or
more point pairs that define segments along the line which appear to lie
entirely in the level set. The respInfo and pairInfo data
frames will have all the necessary columns.
The calling function can make a full lsetSegs object by adding an
inpLines component.
See Also
lsetSegs, bdryFromRays,
bdry_1line, profile_1line,
crossings This function is called by:
bdryFromRays, lsetSegs.respProfiles,
lsetSegsCheck.
Hyper-Rectangle Bounding a Set of Points in Input Space
Description
Create an axis-aligned hyper-rectangle just large enough to contain a specified set of points in input space. Optionally expand or contract the hyper-rectangle from that size.
Usage
boundingRect(..., refpt=NULL, spec=NULL, expand=1.0, warnEmpty=TRUE)
Arguments
... |
One or more vectors, matrices, or |
spec |
|
refpt |
A vector or one-row matrix containing the coordinates of the point to use
as the reference point for the new hyper-rectangle. The new
hyper-rectangle will always include it. This is also the point relative
to which |
expand |
Scalar expansion factor for the hyper-rectangle, relative to what is
required to just contain all the points in |
warnEmpty |
Logical scalar. If TRUE, a warning will be raised if |
Details
All the objects in ... are combined into a single matrix of point
coordinates. For inpRect objects, the lower and upper corner
points are used. For inpRays objects the position 0 and position 1
points are used. For lsetSegs objects, the coordinates of the
segment endpoints are used.
Each point in the combined matrix is adjusted so that its distance from
refpt is multiplied by factor expand. The smallest
axis-aligned hyper-rectangle containing all of the adjusted points and
refpt is calculated.
inpRect objects are required to have positive volume, so any sides
of the hyper-rectangle that have near-zero length will be increased by an
amount based on inpTol(spec).
Value
An inpRect object containing the calculated hyper-rectangle, or
NULL if ... does not contain any points.
See Also
inpRect. segBoundingRect is a similar function
specifically for bounding level set segments. It handles expansion of the
bounding rectangle differently.
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
fspec <- fnSpec(inpnames=c("X1", "X2"))
set.seed(1)
pts <- matrix(runif(10), ncol=2) # 5 points in unit square
rect <- boundingRect(pts, refpt=c(0, 0), spec=fspec)
plot(rect, main="Bounding rectangle for 5 points and a reference point")
points(pts) # rectangle just includes 'refpt' and 'pts'
# Expand the rectangle away from 'refpt':
rect <- boundingRect(pts, refpt=c(0, 0), spec=fspec, expand=1.2)
plot(rect, main="Bounding rectangle expanded away from 'refpt'")
points(pts) # rectangle includes 'refpt' and a margin around 'pts'
# Rectangle is guaranteed to have non-zero volume, even when points lie in
# a lower dimensional space:
rect <- boundingRect(pts[1, ], refpt=pts[1, ], spec=fspec)
rectSize(rect) # sides are small but not 0
lsetPkgOpt(oldopt)
Does a Matrix Represent a Valid Hyper-Rectangle in Input Space
Description
Test whether a two-row matrix represents a valid hyper-rectangle in input space. This is an internal utility function, not intended to be called by package users.
Usage
boxValid(x, noInf=TRUE, positiveVolume=TRUE, inptol)
Arguments
x |
Two-row matrix, the first row giving the coordinates of the lower corner of the hyper-rectangle and the second row the coordinates of the opposite, upper corner. |
noInf |
If TRUE, all elements of |
positiveVolume |
If TRUE, then in each column of |
inptol |
|
Details
When positiveVolume is TRUE, argument inptol is needed to
make the volume test consistent with the test for membership in
inBox. (Don't want volume called positive when every point in the
hyper-rectangle is called a boundary point.)
Value
Logical scalar, TRUE or FALSE. If FALSE, it will have a msg
attribute containing a text string about which check failed.
See Also
Intersections of Lines with the Boundary of a Hyper-Rectangle
Description
Find the intersections of one or more lines in input space with the boundary of a hyper-rectangle. This is an internal utility function, not intended to be called by package users.
Usage
box_bdry_from_lines(x1, x0, box, inptol, whichFaces=FALSE)
Arguments
x1, x0 |
Matrices with the coordinates of the position 0 ( |
box |
2-row matrix with the coordinates of the lower and upper corners of a
finite hyper-rectangle. The box may have zero |
inptol |
2-row matrix with tolerance specifications for input space coordinates. |
whichFaces |
Logical scalar. If TRUE the return value will include which face(s) of
|
Details
The boundary of box consists of 2*d faces, each itself a
hyper-rectangle lying in a d-1-dimensional hyperplane of input
space. Each hyperplane is defined by one of the coordinates of the two
points that specify the lower and upper corners of the hyper-rectangle;
i.e., one of the elements of the 2 x d matrix box.
A line may intersect the boundary of box (a) not at all (so there
will be no entry for that line in bdryPts, bdryInfo, or
faces, and the corresponding column of pairIdxs will contain
NA); (b) at a single point (e.g., at a corner or edge point of box
if it has positive volume, or in a face interior if it does not), and its
column in pairIdxs will contain the same point index twice; (c) at
two distinct points (when the line intersects the interior of box);
or (d) as a line segment, when the line lies in the same plane as a face
of box. In the case of (d), just the two endpoints of that segment
are included in the return value.
Deciding whether a point is on the boundary of box is subject to
floating point representation error and roundoff error. Numerical
tolerance factors to allow for that are taken from argument inptol.
Value
List with components:
box |
Same as the argument. |
bdryPts |
Matrix containing the coordinates of the intersections of lines in
|
bdryInfo |
Data frame with one row per point in
posn : Position of the intersection point along the line. |
pairIdxs |
2-row matrix w/ one column per line. Contains indexes into rows of
|
faces |
(Only if |
Points in each column of pairIdxs will be sorted in order of
increasing posn values.
See Also
inBox, inpTol, absTolCoord,
posn_to_coord2
Intersection of Rays with the Boundary of a Hyper-Rectangle
Description
Find the intersection of one or more rays with the boundary of a hyper-rectangle. This is an internal utility function, not intended to be called by package users.
Usage
box_bdry_from_rays(x1, origin, box, inptol, whichFaces=FALSE)
Arguments
x1 |
Matrix with the coordinates of the position 1.0 points for the rays. All
points must be distinct from |
origin |
Vector or 1-row matrix with the coordinates of the ray origin. It must be
a point in the hyper-rectangle |
box |
2-row matrix with the coordinates of the lower and upper corners of a
finite hyper-rectangle. The box may have zero |
inptol |
2-row matrix with tolerance specifications for input space coordinates. |
whichFaces |
Logical scalar. If TRUE the return value will include which face(s) of
|
Details
This is just a wrapper for box_bdry_from_lines with a slightly
simplified return value–exactly one boundary point per ray. It takes
advantage of the fact that when the ray origin belongs to box,
every ray intersects the box boundary. In cases where the ray intersects
the boundary at more than one point (e.g., if it lies in a boundary
hyperplane) the point with maximum position along the ray is returned.
Points in bdryPts may not differ much, or at all, from the ray
origin (i.e., rays may become degenerate when restricted to box).
Note that any given ray-box boundary intersection point may belong to more than one face of the box.
Value
List with components:
box |
Matrix like the argument, but adjusted if necessary to put the ray origin exactly on its boundary, if it was slightly (within a numerical tolerance) outside it. |
bdryPts |
Matrix containing the coordinates of the intersection of each ray in
|
posn |
Vector with the position of the boundary intersection for each ray.
Position is measured in units of the distance from the ray origin
(position=0) to its second defining point in |
faces |
(Only if |
See Also
inpRays, absTolCoord,
box_bdry_from_lines
Combine Objects from the 'ptsClass' Set of Classes
Description
Combine objects from the ptsClass set of classes (which all inherit
from inpPts). This is an internal utility method, not intended to
be used by package users.
Usage
## S3 method for class 'inpPts'
c(...)
Arguments
... |
One or more objects inheriting from |
Value
An object with the same class as the first argument, containing all the points (and point pairs, if relevant) of the arguments, in order.
Note
Objects that inherit from respProfiles or lsetSegs include
an internal inpLines or inpRays object defining profile
lines/rays. If all the objects in ... include inpRays
objects, and all of the latter have the same origin, the result of
combining them will as well. In other cases any internal inpRays
objects will be changed to inpLines objects.
See Also
inpPts, inpLines, inpRays,
respProfiles
Modified Version of 'cat'
Description
Wrapper for base::cat that by default does not insert a space
between printed elements, and that automatically adds a newline character
at the end of its output. This is an internal utility function, not
intended to be called by package users.
Usage
cat2n(..., sep="")
Arguments
... |
Objects that will be concatenated and printed. (Other arguments to
|
sep |
Character string that will be inserted between objects in |
Value
Invisible NULL.
Check Input Space and Response Specifications for an Object
Description
Check whether an object is consistent with the input space and response
function specifications in spec, and/or the level set defined by
lsetthresh. This is an internal utility function, not intended to
be called by package users.
Usage
chkSpecCompat(x, spec=NULL, lsetthresh=NULL, exclude=NULL)
Arguments
x |
An object containing an |
spec, lsetthresh |
|
exclude |
Optional character vector naming |
Details
For inp* objects only input space-related components of an
fnSpec object are relevant. Other components are excluded
automatically.
Value
Logical scalar. If FALSE the object is not consistent with at least one
of spec and lsetthresh. Then the return value will have an
attribute notCompat, a character vector with names of the
components that are inconsistent.
See Also
ptsClassStruc, ptsClassComp,
fnSpec
Example of a 3D Confidence Region as a Level Set
Description
List with components that illustrate the use of the levelSets package
to identify and visualize a confidence region for the parameters of a
statistical model.
Usage
circuitFailure_3dEx
Format
The list has components:
fobjfnObjobject with the response function, input space specifications, and feasible region function.threshLog-likelihood value that defines the 95% asymptotic confidence region.
theta_mleThree-element vector containing the maximum likelihood estimates of the parameters.
theta_vcov3-by-3 matrix containing the approximate variance-covariance matrix for 'theta_mle'.
bsrchList returned by
bdrySearch()with results from a search for level set boundary points and segments.slsrchList returned by
slicedBdrySearch(), with results from a level set search within six slices of input space, each defined by a specified value of parameter 'scale'.
The theta_mle and theta_vcov components were obtained with
stats::optim.
Details
The data are failure times of integrated circuits under accelerated testing. 4156 circuits were tested for 1370 hours at elevated temperature and humidity. The goal was to estimate the proportion of circuits with a manufacturing defect that leads to relatively early failure. 28 of the 4156 circuits failed, at various times, during the test; the failure time of the remaining circuits was censored at 1370 hours.
The data and proposed statistical model are given in section 18.1 of Meeker, Hahn, and Escobar (2017). The model assumes that a fraction 'dfrac' of circuits are defective, with failure times having a Weibull distribution with parameters 'shape' and 'scale'. The remaining fraction '1 - dfrac' are assumed to have essentially infinite failure times. Meeker, Hahn, and Escobar refer to this as the limited failure population (LFP) model. It is also a version of a "cure model", where '1 - dfrac' is the proportion of patients who are cured and thus never succumb to the disease being studied.
Here we examine the 3-dimensional likelihood ratio-based 95% confidence
region for the full set of model parameters (dfrac, shape, scale).
Therefore the response function is the log-likelihood, and the
confidence region is the level set consisting of parameter vectors whose
log-likelihood is no more than qchisq(0.95, df=3) / 2 = 3.907 below its
maximum.
Source
The code that creates the above list is included in the package, in the
location returned by
system.file("data_create/circuitFailure_3dEx.create.r",
package="levelSets").
References
Meeker, William Q., Hahn, Gerald J., Escobar, Luis A. Statistical Intervals: A Guide for Practitioners and Researchers, 2nd ed. John Wiley & Sons, 2017.
Positions where a Response Function Crosses a Target Value
Description
Find positions, within a specified range, where a response function crosses from >= to < a target value, or the reverse. This is an internal utility function, not intended to be called by package users.
Usage
crossings(posn, resp=respfn(posn, ...), respfn,
known_crossing=rep(FALSE, length(posn)), target_resp,
target_posn=NULL, abstol_posn=absTol(posn, tol=c(1e-5,
sqrt(.Machine$double.eps))), abstol_resp=absTol(target_resp,
tol=c(1e-5, sqrt(.Machine$double.eps))), ...)
Arguments
posn, resp |
Equal-length vectors with an initial set of response function evaluations
( |
respfn |
Function that takes a vector of positions as its first argument, and returns a vector of responses at those positions. Responses may be either numeric or logical. See DETAILS. |
known_crossing |
Logical vector with the same length as |
target_resp |
Scalar, the target response. Ignored if the response function returns logical rather than numeric values. |
target_posn |
Optional scalar. If not NULL, then only the single solution position closest to this value is returned (in case there is more than one crossing). |
abstol_posn |
Vector of strictly positive scalars with the same length as |
abstol_resp |
Non-negative scalar, used to decide whether a crossing has occured. See
DETAILS. Ignored if |
... |
Additional arguments passed to |
Details
The response is assumed to be a function of a single, scalar argument,
here called "position". It is not assumed to be continuous. Crossings
will only be found within the range of positions specified in posn,
and only if they are bracketed by a pair of positions in posn whose
response values are on opposite sides of target_resp.
respfn may return numeric or logical (TRUE/FALSE) values. The
latter are treated as a numerical response with TRUE=1 and FALSE=0, and
target_resp=0.5.
respfn may return NA values at certain positions. However no
crossing will be searched for between any two positions for which either
endpoint has an NA response value, or if NA is found at any intermediate
position.
A crossing is defined to occur within the interval between two positions
x1 and x2 if: (a) the response is greater than or equal to
target_resp at x1; (b) response is strictly less than
(target_resp - abstol_resp) at x2; and (c) if there are any
additional posn values between x1 and x2, all their
response values are in the half-open interval [target_resp -
abstol_resp, target_resp). A non-zero abstol_resp avoids
declaring a crossing due simply to small round-off or approximation errors
in response values near target_resp. *Note that it does not*
specify how close the response value at a solution position must be to
target_resp; the search for a solution is controlled by
abstol_posn, as described next.
Having found such a pair x1, x2, and supposing x1 <
x2, binary search is used to find the largest position x* between
them for which response is still >= target_resp. (Intermediate
points from (c) above are ignored, and no search is performed if any
intermediate point is already a known crossing.) The iterative search
stops when further binary division of the interval would create a
subinterval with length <= abstol_posn. (An analogous search in
the other direction is used if x1 > x2.)
Value
If responses are logical: a numeric vector of new positions (not positions
where known_crossing is TRUE) where response transitions from TRUE
to FALSE, or the reverse. Positions are selected to be (barely) on the
TRUE side of the transition.
If responses are numeric: a numeric vector of new positions where response
transitions from greater than or equal to target_resp to less than
target_resp, or the reverse. Positions are selected to be on the
greater than or equal to side of the transition.
The return value may have length 0 (if no new crossings are found), or
length greater than 1 (if the response function has multiple crossings
within the range of posn, and target_posn is NULL).
Example of a Multi-Part Level Set in a 2D Input Space
Description
Lists with components that illustrate the use of the levelSets package
to identify and visualize a level set of a function. The input space has
two dimensions, the response function has two peaks, and the level set
consists of two separate elliptical regions around those peaks. The only
difference between dbl_ellipse_2dEx and dbl_ellipse_X1bnd_2dEx
is that the latter adds an arbitrary constraint to illustrate the
specification of a feasible region for the response function.
Usage
dbl_ellipse_2dEx
Format
Each list (dbl_ellipse_2dEx and dbl_ellipse_X1bnd_2dEx)
has components:
fobjfnObjobject with the response function, input space specifications, and feasible region function.threshValue of the response function that defines the level set of interest (-40).
origin01-row matrix with the coordinates of a point in input space to use as a ray origin.
rect0inpRectobject with a hyper-rectangle in input space, to use as an initial search region for the level set boundary.rays0inpRaysobject containing 50 random rays, with origin and position 1 rectangle given byorigin0andrect0respectively.segs, segs_checkedlsetSegsobjects with level set segments forfobj.segswas obtained by applyingbdryFromRays()torays0. Some of the segments are invalid, andsegs_checkedcontains the segments after being checked and fixed bylsetSegsCheck().
Source
The code that creates the above lists is included in the package, in the
location returned by
system.file("data_create/dbl_ellipse_2dEx.create.r",
package="levelSets").
Extract the 'derivMethod' Setting from an 'fnObj' Object
Description
Extract the derivMethod setting from an fnObj object. This
is an internal utility function, not intended to be called by package
users.
Usage
derivMethod(x)
Arguments
x |
An |
Value
Character string, one of gradient, finite difference, or
none.
See Also
Test for Valid Input Space Dimension Names
Description
Test the validity of a character vector as names for the dimensions of an input space. This is an internal utility function, not intended to be called by package users.
Usage
dnamesValid(inpnames)
Arguments
inpnames |
Character vector. |
Value
TRUE or FALSE. If FALSE the return value will have an attribute
msg, a character string with information about the first test that
failed.
Reduce an 'inp*' Object to a Lower Dimensional Subspace
Description
Reduce an inp* object to a lower dimensional subspace of input
space. This is an internal utility function, not intended to be called by
package users.
Usage
drop_inp_dims(x, dropdims)
Arguments
x |
An |
dropdims |
Logical, character, or numeric vector indicating which input space
dimensions are to be removed from |
Details
dropdims is allowed to specify that none of the input space
dimensions are to be dropped (e.g., dropdims=numeric(0) or
dropdims=FALSE). But it cannot remove all the input space
dimensions–at least one must remain.
The allowed classes for x are the simplest to handle. With other
classes such as inpPairs or classes inheriting from it, we would
have to worry about elements becoming degenerate when certain dimensions
are dropped.
By necessity, this function works with the internal representation of
inp* objects, in addition to higher level accessor functions.
???????? Might be useful to replace this w/ more general
drop_slice_dims, add_slice_dims(x, slice) functions.
Value
An object with the same class as x, but with the specified input
space dimensions removed.
Evaluate a Response Function at Positions along a Single Line
Description
Evaluate a response function at one or more positions along a single line. At each point also optionally calculate the function derivative with respect to position, and classify the function as increasing, decreasing, or flat in the direction of the line. This is an internal utility function, not intended to be called by package users.
Usage
eval_1line(posn, targ_fun, lsetthresh=NA_real_)
Arguments
posn |
Numeric vector of line positions. May have length 0 (resulting in an
empty pre- |
targ_fun |
Function that evaluates the response function at specified positions along
the line. See |
lsetthresh |
Response function value that defines a level set of interest. The default is NA; i.e. no level set is specified. |
Details
Trend at each position in posn is determined by calculating or
approximating the derivative of the response function with respect to
position along the line. To judge whether a derivative is negligibly
different from zero, treat it as a slope and look at the implied change in
response for a 1 unit change in position. Compare that to the magnitude
of a negligible change in response (based on resptol extracted from
the environment of targ_fun). If the predicted change is less than
or equal to the absolute response tolerance, the derivative at the
position is considered near-zero and the trend is called flat.
Otherwise the trend is labeled increasing or decreasing
based on the sign of the derivative.
targ_fun is created by function make_line_profile_fun. See
that function for how targ_fun calculates derivatives.
Value
A pre-respProfiles list with all the components of a
respProfiles object for a single line, except inpLines. The
line column in the respInfo data frame is filled with
lineidx taken from the environment of targ_fun.
This function does no boundary searching, so feasbdry and
lsetbdry are set to their defaults of FALSE if
feas/lset are FALSE and NA otherwise.
See Also
make_line_profile_fun. This function is called by
profile_1line, bdry_1line, and
bdry_1line_intrsctn.
Box Constraints on a Feasible Region
Description
Return any box constraints on point coordinates in the feasible region of a response function.
Usage
feasBnds(x)
Arguments
x |
An |
Details
These represent only the box constraints on the feasible region that were
specified by the feasbnds argument to fnObj. The actual
feasible region may be more complicated: the box constraints are combined
with any other feasible region restrictions specified by argument
feasfn when an fnObj object is created.
Value
Two-row matrix with d columns, where d is the number of
dimensions in the input space. Each column contains the lower and upper
bounds for coordinates for the corresponding dimension, as specified by
x. If no box constraint was specified for a given dimension, the
default is -Inf for lower bound and Inf for upper bound.
See Also
Examples
# See examples in '?fnSpec'
Reverse the Direction of a Set of Rays
Description
Reverse the direction of a set of rays. This is an internal utility function, not intended to be called by package users.
Usage
flipRays(rays, namePrefix="rev_", warnDegenerate=TRUE)
Arguments
rays |
An |
namePrefix |
If |
warnDegenerate |
Integer or logical scalar. In certain cases flipped rays may be
degenerate (positions 0 and 1.0 are the same point, to within a numerical
tolerance). See DETAILS. Degenerate rays are not allowed.
|
Details
If rays has an associated hyper-rectangle, position 1.0 on the
flipped rays will be their intersections with the boundary of that
rectangle. Therefore if the ray origin is not at the center of the
rectangle, the Euclidean distance between the origin and position 1 on
flipped rays may differ from the original rays.
If the ray origin itself is on the boundary of the rectangle, essentially all flipped rays are likely to be dropped: In general the original rays will point from the boundary toward the interior of the rectangle, so their flipped versions will lie outside the rectangle except for their origin. Once truncated to their intersection with the boundary (the origin) the flipped rays will be degenerate and will be dropped. The only exception would be rays that lie in the rectangle face(s) containing the origin; then their flipped versions will also lie in the same face(s).
Testing for degenerate rays uses a numerical tolerance; i.e., it tests for
practical degeneracy, rather than requiring exactly zero length. See
inpTol().
Value
A inpRays object like rays, but with the directions of the
rays reversed relative to the their origin. Note that if rays has
an associated hyper-rectangle and the ray origin is on its boundary, rays
may be dropped. See DETAILS.
See Also
Create an Object that Represents a Response Function
Description
Create an object containing a response function and related information, including about its input space, feasible region, and gradient availability.
Usage
fnObj(x, respfn, feasfn=NULL, hasgrad=FALSE,
derivmethod={ if (hasgrad) "gradient" else "none" }, warnNAresp=2,
warnInfresp=1, ...)
Arguments
x |
A character vector of unique names for the dimensions of the input space.
They must be valid names for R objects (see |
respfn |
Function that takes a matrix of input point coordinates as its first argument (one input point per row), and returns a vector with response function values at those points. |
feasfn |
Optional function that takes a matrix of input point coordinates as its
first argument, and returns a logical vector indicating whether each point
is in the feasible region of |
hasgrad |
Logical scalar. TRUE means that |
derivmethod |
Character string indicating whether and how to calculate the derivative of
the response function with respect to position along a line or ray. One
of |
warnNAresp, warnInfresp |
Scalars specifying how response function values of NA or +/-Inf, at points
called feasible by |
... |
Additional arguments for specific methods (see |
Details
The purpose of fnObj objects is to wrap user-supplied response and
feasibility functions, providing a consistent interface for other package
functions. This includes consistent handling of NA's and infeasible input
points, and a consistent structure for return values.
A simple way to evaluate the response function at a set of points
x, given an fnObj object for the function, is
respInfo(x, fnobj). This will return a data frame that includes
response value and other information (including feasibility) for each
point.
Feasible region of input space. The feasible region can be
specified explicitly and/or implicitly. Explicit specification is through
the feasfn argument (and/or feasbnds for the
.character method). Implicit specification is through
respfn: it can simply return NA for any point it considers
infeasible. (If the latter approach is used, warnNAresp should be
set to 0 or FALSE to turn off warnings/errors due to NA response values.)
A point will be considered feasible only if it passes both implicit and
any specified explicit checks.
If provided, a feasfn function should be robust: it should accept
any set of numeric point coordinates without generating errors, and return
only TRUE or FALSE for each point. (Any NA values returned by
feasfn will be treated as FALSE.) In addition the algorithms in
this package assume that the feasible region is a closed (although
possibly unbounded) set. Thus weak inequalities ("<=", ">=") rather than
strong inequalities ("<", ">") should be used when defining the feasible
region in a feasfn function.
respfn will never be called with input points that explicit
feasibility checks call infeasible. Instead the response value at those
points (and the gradient vector if applicable) is set to NA. Conversely,
any point for which respfn returns NA will implicitly be considered
infeasible. Depending on the value of warnNAresp this will be
handled silently (0 or FALSE), with a warning (1 or TRUE), or as an error
(2). The default is 2, treating unexpected NA response values as errors.
Argument warnInfresp offers the same options to report when
+/-Inf values are returned by respfn. Points with infinite
response are not considered infeasible. The default for
warnInfresp is 1.
Gradients and derivatives. Coding and use of response function
gradients is optional. This package does not assume response functions
are differentiable. The only use of derivatives is to detect possibly
missed level set boundary crossings along rays. (For example, if the
derivative with respect to position along a ray is negative at two
consecutive crossings, that suggests there is another crossing between
them with a positive derivative.) If a level set is known to be a single
convex region of input space this check is superfluous, and
derivmethod can be set to none. Similarly if the response
function is highly discontinuous or piecewise-constant, derivatives won't
be useful and derivmethod should be none.
See ?fnObj.character and ?lsetPkgOpt for a description of
tolerance specifications for coordinates of points in input space, and for
response function values.
Accessor and update functions. Accessor functions can be used to extract
individual specifications from an fnObj object: inpDim(),
inpNames(), feasBnds(), inpTol(), respTol(),
hasGrad(). fnSpec() will extract an fnSpec object
that includes the first five of those.
There is an update method for fnObj objects that can be used
to update some of its specifications. See ?update.fnObj for
details.
Value
An object with S3 class fnObj.
See Also
fnSpec; respInfo to evaluate the response
function in an fnObj object at a set of points.
lsetPkgOpt. lsetPkgOpt("warn.showBadRespPts")
controls whether and how many point coordinates are printed as part of
warnings or errors due to NA or infinite response function values.
Examples
oldopt <- lsetPkgOpt(reset=TRUE) # default options
# Function of 3 input variables ("X1", "X2", "X3"), with gradient available,
# and an extra argument 'powr'.
f <- function(x, inclGrad=FALSE, powr) {
y <- x[, "X1"]^powr[1] + x[, "X2"]^powr[2] + x[, "X3"]^powr[3]
if (inclGrad) {
grad <- array(NA_real_, dim=dim(x), dimnames=dimnames(x))
for (j in 1:3) {
grad[, j] <- { if (powr[j] == 0) 0
else powr[j] * (x[, j]^(powr[j] - 1)) }
}
attr(y, "gradient") <- grad
}
y
}
# Associated feasibility function, always passed the same extra argument(s).
feasf <- function(x, powr) {
feas <- rep(TRUE, nrow(x))
# Want to avoid applying non-integer powers to negative numbers.
fracpow <- (powr != round(powr))
for (j in which(fracpow)) {
feas <- feas & (x[, j] >= 0) # NOTE: '>=', not '>'. Feasible set
# should be _closed_.
}
feas
}
fobj <- fnObj(c("X1", "X2", "X3"), respfn=f, feasfn=feasf, hasgrad=TRUE,
powr=c(-1, 0, 2.5))
# Evaluate the response function at a set of points.
pts <- rbind(c(3, -2, 0), c(2, 0, -1), c(1, 6, 1), c(-1, 1, 1))
colnames(pts) <- inpNames(fobj)
resp1 <- respInfo(pts, fnobj=fobj) # data frame
resp1 # response is NA for infeasible points. No level set threshold has
# been set, so 'lset' is NA for feasible points.
# Define a threshold for a level set of the response, and ask for gradients.
resp2 <- respInfo(pts, fnobj=fobj, lsetthresh=1.2, inclGrad=TRUE)
resp2
attr(resp2, "gradient")
# Box constraints on the feasible region can be specified directly in
# 'feasbnds', without the need for a separate feasibility function.
fobj <- fnObj(c("X1", "X2", "X3"), respfn=f, hasgrad=TRUE,
feasbnds=rbind(rep(0, 3), rep(NA, 3)), powr=c(-1, 0, 2.5))
respInfo(pts, fnobj=fobj)
# Accessor functions:
inpDim(fobj) # 3
inpNames(fobj)
inpTol(fobj) # 2 x 3 matrix
respTol(fobj) # 2-element vector
feasBnds(fobj) # 2 x 3 matrix
hasGrad(fobj)
fnSpec(fobj)
lsetPkgOpt(oldopt) # restore starting options
Create an Object that Represents a Response Function
Description
Create an object containing a response function and related information, including about its input space, feasible region, and gradient availability.
Usage
## S3 method for class 'character'
fnObj(x, respfn, feasfn=NULL, hasgrad=FALSE,
derivmethod={ if (hasgrad) "gradient" else "none" }, warnNAresp=2,
warnInfresp=1, feasbnds=matrix(NA_real_, nrow=2, ncol=length(x)),
inptol=lsetPkgOpt("inptol"), resptol=lsetPkgOpt("resptol"), ...)
Arguments
x |
Character vector of unique names for the dimensions of the input space.
They must be valid names for R objects (see |
respfn, feasfn, hasgrad, derivmethod, warnNAresp, warnInfresp |
See the documentation for the generic. |
feasbnds |
Optional matrix or list specifying lower and upper bounds (box
constraints) on the feasible region of the response function. Bounds are
applied strictly, without any numerical tolerance from |
inptol |
Two-row matrix with |
resptol |
Two-element vector with the relative and minimum absolute tolerances to
use for response function values. Valid values are the same as for
|
... |
Additional arguments to be included in each call to |
Details
This method for the generic fnObj function constructs an
fnObj object from scratch, starting with a vector of names for the
input space dimensions. See the documentation of the generic for the
purpose and details of fnObj objects.
Value
An object with S3 class fnObj.
See Also
fnSpec; lsetPkgOpt for more information about
the tolerances specified by inptol and resptol.
Examples
# See the examples in '?fnObj'
Create an Object that Represents a Response Function
Description
Create an object containing a response function and related information, including about its input space, feasible region, and gradient availability.
Usage
## S3 method for class 'fnSpec'
fnObj(x, respfn, feasfn=NULL, hasgrad=FALSE,
derivmethod={ if (hasgrad) "gradient" else "none" }, warnNAresp=2,
warnInfresp=1, ...)
Arguments
x |
|
respfn, feasfn, hasgrad, derivmethod, warnNAresp, warnInfresp |
See the documentation for the generic. |
... |
Additional arguments to be included in each call to |
Details
This method for the generic fnObj function constructs an
fnObj object based on the specifications in an fnSpec
object. See the documentation of the generic for the purpose and details
of fnObj objects.
Value
An object with S3 class fnObj.
See Also
Input Space and Related Specifications
Description
Create an fnSpec object or extract one from another object.
fnSpec objects contain a subset of the information in an
fnObj object. For package users their main value is as a way to
specify enough information to create inpRect and inpRays
objects that are not tied to a specific response function.
Usage
fnSpec(x=NULL, inpnames, feasbnds=NULL, inptol=NULL, resptol=NULL)
Arguments
x |
Optional object from which an |
inpnames, feasbnds, inptol, resptol |
See |
Details
An fnSpec object describes selected properties of a response
function: the number and names of its input variables, limits on the
ranges of those variables, and numerical tolerances associated with point
coordinates and response values. It does not contain code to actually
calculate response values at given input points; for that see
fnObj.
If the first argument x is already an fnSpec object or
contains one, the fnSpec object will be returned, updated with any
of the other arguments that are not NULL. However the number and names of
the input space dimensions (argument inpnames) cannot be updated.
As for fnObj objects, accessor functions can be used to extract
individual specifications from an fnSpec object: inpDim(),
inpNames(), feasBnds(), inpTol(), and
respTol(). There is also a print method.
Value
An object with S3 class fnSpec.
See Also
Examples
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"))
# 'fspec' has default tolerances and other specifications.
inpTol(fspec) # 2 x 3 matrix
respTol(fspec) # 2-element vector
feasBnds(fspec) # 2 x 3 matrix
# Other accessor functions:
inpDim(fspec) # 3
inpNames(fspec)
# Create rays or hyper-rectangles independently of any specific response
# function in an 'fnObj' object.
rays <- axisRays(fspec) # 3 rays, one along each coordinate axis
rect <- inpRect(rbind(c(0, 0, 0), c(1, 2, 3)), spec=fspec)
# Updating:
fspec2 <- fnSpec(fspec, feasbnds=list(X2=c(0, 10), X1=c(NA, 5), X3=c(NA, 6)),
resptol=c(1e-4, 2e-6))
feasBnds(fspec2)
respTol(fspec2)
# Extract an 'fnSpec' from another object.
identical(fnSpec(rays), fspec)
identical(fnSpec(rect), fspec)
Helper Function for 'fnSpec' Accessors
Description
Helper function for accessor functions of an fnSpec object, or
objects containing one. This is an internal utility function, not
intended to be called by package users.
Usage
fnspec_accessor(x, which)
Arguments
x |
An |
which |
Character string naming the component to extract from |
Value
The value of the fnSpec component specified by which.
Can a Response Function Calculate Gradient Vectors?
Description
Inquire whether the response function in an fnObj object is able to
calculate gradient vectors as well.
Usage
hasGrad(x)
Arguments
x |
An |
Value
Logical scalar (may be NA).
See Also
Examples
# See examples in '?fnObj'
Do Points in Input Space Belong to a Hyper-Rectangle?
Description
Check whether points in input space belong to a hyper-rectangle. This is
an internal utility function, not intended to be called by package users.
(It works with unclassed matrices and assumes consistency between
arguments. See inRect for the user-level interface.)
Usage
inBox(x, corners, bdryOnly=FALSE, abstol=NULL, inptol)
Arguments
x |
Matrix containing point coordinates. (A plain vector is treated as a 1-row matrix.) |
corners |
two-row matrix defining a hyper-rectangle in input space. The first row contains the coordinates of the lower corner of the rectangle, and the second row the coordinates of the upper corner. |
bdryOnly |
Logical scalar. If TRUE, the check is whether points belong to the boundary of the rectangle; i.e., the interior is excluded. |
abstol |
|
inptol |
An alternative way to specify tolerances: |
Details
For each coordinate dimension there are two bounding (hyper)planes of a
hyper-rectangle, one at each end. A point is considered to lie in
bounding plane i of dimension j if its j-th
coordinate is within atol of corners[i, j]. atol is
an absolute tolerance taken directly from abstol[i, j] if provided,
or calculated by applying the relative and minumum tolerances for
dimension j in inptol[, j] to corners[i, j]. See
absTolCoord for details.
[A previous version of this function set abstol to the minimum of
absTol(corners[i, j], tol) and absTol(side[j], tol), where
side[j] is the length of the j-th side of the rectangle.
Use of an absolute tolerance based on rectangle sides was dropped because
(a) the test used by rectBdryFromRays to decide whether a point
belongs to a boundary hyperplane doesn't consider side length; and b) if
corners[i,j] is big but side[j] is small, the min abstol may
be so small that the difference from corners[i,j] is not
representable.]
Value
Logical vector with as many elements as x has points. An element
is TRUE if the corresponding point in x belongs to the
hyper-rectangle (to within tolerances specified by inptol), FALSE
if it does not, and NA if any coordinate of a point is NA.
See Also
Do Points in Input Space Belong to a Hyper-Rectangle?
Description
Check whether points in input space belong to a hyper-rectangle. This is an internal utility function, not intended to be called by package users.
Usage
inRect(x, rect, bdryOnly=FALSE, inptol=inpTol(rect))
Arguments
x |
Matrix containing point coordinates. (A plain vector is treated as a 1-row matrix.) |
rect |
|
bdryOnly |
Logical scalar. If TRUE, the check is whether points belong to the boundary of the rectangle; i.e., the interior is excluded. |
inptol |
|
Details
Deciding whether a point is in (or on the boundary of) rect is
subject to floating point representation error and roundoff error, as well
as practical limits on the precision of point coordinates. Therefore this
function allows some fuzziness around the boundary of rect in
deciding membership. The details are as follows.
For each coordinate dimension there are two bounding (hyper)planes of a
hyper-rectangle, one at each end. A point is considered to lie in
bounding plane i (i equal to 1 or 2) of dimension j
if its j-th coordinate is within amount atol[i, j] of
corners[i, j]. The two-row matrix corners contains the
coordinates of the lower and upper corners of rect, as returned by
rectCorners(rect). atol[i, j] is an absolute tolerance
calculated by applying the relative and minumum tolerances for dimension
j in inptol[, j] to corners[i, j]. (See
?lsetPkgOpt.)
Thus a point with coordinate vector x is considered to be in
rect if for all j, x[j] >= corners[1, j] - atol[1, j]
and x[j] <= corners[2, j] + atol[2, j]. It is considered on the
boundary of rect if it is in rect, and also abs(x[j] -
corners[i, j]) <= atol[i, j] for any i and j.
Value
Logical vector with as many elements as x has points. An element
is TRUE if the corresponding point in x belongs to rect (to
within numerical tolerances specified by inptol), FALSE if it does
not, and NA if any coordinate of a point is NA.
See Also
inpRect, inpTol, absTol,
lsetPkgOpt.
Number of Dimensions for the Input Space
Description
Return the number of dimensions for the input space associated with an object.
Usage
inpDim(x)
Arguments
x |
An |
Value
Scalar, the number of dimensions of the input space associated with
x.
See Also
Examples
# See examples in '?fnSpec'
Lines in Input Space
Description
Create an inpLines object, or extract one from another object.
inpLines objects represent sets of 1-dimensional lines in input
space. Each line is defined by a pair of distinct points, the first
representing position 0 on the line, and the second position 1.0.
Usage
inpLines(x, ...)
Arguments
x |
Either a matrix of point coordinates to be used to create a set of lines
(see |
... |
Additional arguments for specific methods. |
Details
This is an S3 generic function. There is a default method (to create a new set of lines), and methods to extract an existing set of lines from another object. (Package users should call the generic.)
inpLines class objects are represented internally as pairs of
distinct points in input space, which can be extracted as matrices by
function ptCoord. Lines can be given names via the names
and names<- generic functions.
The class also has methods for length (the number of lines),
[ (selecting lines), and c (to combine sets of lines).
Positions along a line (see inpRays) can be converted to point
coordinates using function posnToCoord().
inpRays objects are a special case of inpLines, where all
lines have the same position 0 point.
Value
An object with S3 class inpLines (and possibly also inpRays,
if x is a respProfiles or lsetSegs object).
See Also
inpRays, inpLines.default,
ptCoord, posnToCoord
Examples
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"))
pts <- rbind(c(0, 1, 3), c(2, 2, 4), c(5, -1, 2), c(1, 1, 1))
# The default method of defining positions 0 and 1 for each line is
# to use consecutive pairs of rows of 'pts':
ilines <- inpLines(pts, spec=fspec)
ilines
length(ilines) # 2, the number of lines
# Alternative way of specifying positions 1 and 0 is by two matrices. The
# first has position 1 points, the second position 0 points:
ilines2 <- inpLines(pts[c(2, 4), ], x0=pts[c(1, 3), ], spec=fspec)
ilines2
# Extract coordinates of the defining points (positions 0 and 1) for
# each line.
ptCoord(ilines, which="paired") # 4 rows: first two for line 1, second two for line 2
# Set and retrieve names for lines.
names(ilines) <- c("foo", "bar")
names(ilines)
# Combine multiple 'inpLines' objects.
ilines3 <- inpLines(rbind(c(1, 2, 3), c(2, 3, 4)), spec=fspec) # 1 line
ilines13 <- c(ilines, ilines3)
length(ilines13) # 3 lines
# Select a subset of lines.
length(ilines13[2:3]) # 2
length(ilines13[0]) # 0 (still an 'inpLines' object, but empty)
ilines13[0]
# Rays are a special case of lines (they share the same position 0 point).
rays <- axisRays(fspec) # 3 rays, one along each coordinate axis
inherits(rays, "inpLines") # TRUE
Lines in Input Space
Description
Create an inpLines object from a matrix of point coordinates.
Usage
## Default S3 method:
inpLines(x, x0=NULL, pairidxs=NULL, spec, warnDegenerate=TRUE, ...)
Arguments
x |
Matrix containing coordinates of points in input space. NA coordinates are not allowed. |
x0 |
Optional matrix containing coordinates of points in input space. NA
coordinates are not allowed. If specified it must have the same number of
rows as |
pairidxs |
Alternative to argument |
spec |
|
warnDegenerate |
Integer or logical scalar. If 1 or TRUE (the default), a warning will be raised if any lines are dropped because their position 0 and 1 points are equal, to within a numerical tolerance. If 0 or FALSE, degenerate lines are dropped silently. If 2, degenerate lines will be treated as an error. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class inpLines. See the documentation for the
generic function for details.
Examples
# See the examples in '?inpLines'
Lines in Input Space
Description
Create an empty inpLines object from just an input space
specification. This is an internal utility method, not intended to be
called by package users.
Usage
## S3 method for class 'fnSpec'
inpLines(x, ...)
Arguments
x |
An |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class inpLines. See the documentation for the
generic function for details.
Lines in Input Space
Description
Extract an inpLines object from an object that inherits from that
class. This is an internal utility method, not intended to be called by
package users.
Usage
## S3 method for class 'inpLines'
inpLines(x, strictClass=TRUE, ...)
Arguments
x |
An object inheriting from class |
strictClass |
Logical scalar. If TRUE (the default), the returned object will be
reduced to an |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
If strictClass is TRUE, an object with S3 classes
c("inpLines", "inpPairs", "inpPts"). See the documentation for the
generic function for details.
If strictClass is FALSE, x (which already inherits from
inpLines) is returned unchanged (e.g., an inpRays object).
Lines in Input Space
Description
Create an inpLines object from point pairs. This function just
drops any extending classes and components in x and then adds the
inpLines class. This is an internal utility method, not intended
to be called by package users.
Usage
## S3 method for class 'inpPairs'
inpLines(x, ...)
Arguments
x |
An object inheriting from class |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 classes c("inpLines", "inpPairs", "inpPts").
Lines in Input Space
Description
Extract the lines or rays associated with an lsetSegs object. This
is an internal utility method, not intended to be called by package users.
Usage
## S3 method for class 'lsetSegs'
inpLines(x, ...)
Arguments
x |
An object inheriting from |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
There are two ways one might want to obtain lines in input space from a
set of level set segments. One is to simply extract the existing
inpLines or inpRays object from x. That is what this
method does.
The other is to use each segment to define its own line, with segment
endpoints serving as positions 0 and 1. For that one can force the
segment endpoints to be treated simply as pairs of points in input space:
inpLines(ptCoord(x, which="paired"), spec=fnSpec(x)).
Value
An object with S3 class inpLines, and possibly also inpRays.
See the documentation for the generic function for details.
Lines in Input Space
Description
Extract the lines or rays that are profiled in a respProfiles
object. This is an internal utility method, not intended to be called by
package users.
Usage
## S3 method for class 'respProfiles'
inpLines(x, ...)
Arguments
x |
An object inheriting from |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class inpLines, and possibly also inpRays.
See the documentation for the generic function for details.
Names of the Dimensions of the Input Space
Description
Return the names of the input space dimensions associated with an object.
Usage
inpNames(x)
Arguments
x |
An |
Value
Character vector. Dimension names are unique and are valid R object names.
See Also
Examples
# See examples in '?fnSpec'
Point Pairs in Input Space
Description
Generic function to create an inpPairs object, or to extract one
from another object. inpPairs objects represent pairs of points in
input space. Points in a pair must be distinct, and therefore these
objects also represent line segments in input space. This is an internal
utility class, not intended to be used or seen by package users.
Usage
inpPairs(x, ...)
Arguments
x |
Object containing information from which an |
... |
Additional arguments for specific methods. |
Details
An inpPairs object is represented essentially as an inpPts
object plus a two-row matrix pairIdxs that contains the indices of
the points belonging to each pair. A given point may belong to more than
one pair (i.e., the same index may appear more than once in
pairIdxs). And a given point may belong to no pair (i.e., its
index may not occur in pairIdxs at all; such points may be removed
by indexing the object with drop=TRUE).
Degenerate pairs (where the same index is used for both points in a pair)
are not allowed. Nor are pairs where both points are essentially tied, to
within a numerical tolerance (see inpTol()).
Function ptCoord will extract point coordinates as a matrix,
pairIdxs will extract the pairing information.
The class has methods for length (the number of _pairs_), [,
c, and print. Other methods will be inherited from the
classes it extends (inpPts).
Value
An object with S3 class c("inpPairs", "inpPts").
See Also
Point Pairs in Input Space
Description
Create an inpPairs object manually, from a matrix of point
coordinates and a matrix specifying pairing of points. This is an
internal utility method, not intended to be called by package users.
Usage
## Default S3 method:
inpPairs(x, pairidxs=NULL, spec=NULL, warnDegenerate=TRUE,
objType="pairs", ...)
Arguments
x |
Matrix or |
pairidxs |
Two-row matrix. Each column contains the indices in |
spec |
|
warnDegenerate |
Integer or logical scalar. If 1 or TRUE (the default), a warning will be raised if any pairs are dropped because the two points are equal, to within a numerical tolerance. If 0 or FALSE, degenerate pairs are dropped silently. If 2, degenerate pairs will be treated as an error. |
objType |
Character string describing the type of object being created. Only used for error messages about tied pairs. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
Points in a pair must be numerically distinct, after allowing for the
coordinate tolerances in spec. warnDegenerate controls what
happens if tied ("degenerate") pairs are found.
Value
An object with S3 class c("inpPairs", "inpPts"). See the
documentation for the generic function for details.
Point Pairs in Input Space
Description
Create an empty inpPairs object from just an input space
specification. This is an internal utility method, not intended to be
used by package users.
Usage
## S3 method for class 'fnSpec'
inpPairs(x, ...)
Arguments
x |
An |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class c("inpPairs", "inpPts"). See the
documentation for the generic function for details.
Point Pairs in Input Space
Description
Extract an inpPairs object from an object that inherits from that
class. This is an internal utility method, not intended to be called by
package users.
Usage
## S3 method for class 'inpPairs'
inpPairs(x, ...)
Arguments
x |
An object inheriting from class |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
If x is belongs to an extending class (e.g. inpLines or
inpRays) any names associated with the lines/rays will be removed.
Value
An object with S3 class c("inpPairs", "inpPts"). See the
documentation for the generic function for details.
Points in Input Space
Description
Generic function to create an inpPts object, or to extract one from
another object. inpPts objects contain the coordinates of points
in the input space of a response function. This is an internal utility
class and generic, not intended to be visible to package users.
Usage
inpPts(x, ...)
Arguments
x |
Object containing information from which an |
... |
Additional arguments for specific methods. |
Details
inpPts is the base class for most other point- and response-related
classes. See ptsClassStruc and ptsClassComp.
inpPts objects have a special subscripting method ([) that
only accepts a single index vector, allowing selection of points. This is
necessary in order that the result remain an inpPts object
containing points in the same input space. To use coordinates from an
inpPts object in ordinary matrix calculations, extract them using
ptCoord().
length() returns the number of points in the object.
range() returns the minimum and maximum coordinate value for each
dimension. c() can be used to combine inpPts objects,
provided they have the same input space. fnSpec() extracts the
input space specification.
Value
An object of S3 class inpPts.
See Also
fnSpec, ptCoord, ptsClassStruc,
ptsClassComp
Points in Input Space
Description
Create an inpPts object, containing the coordinates of points in
the input space of a response function. This is an internal utility
method, not intended to be called by package users.
Usage
## Default S3 method:
inpPts(x, spec, ...)
Arguments
x |
Matrix or data frame, each row containing the coordinates of one input
point. (A plain vector |
spec |
|
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
If spec is specified but x is not, an empty inpPts
object is created.
x must be consistent with the input space specified by spec:
If x does not have column (input space dimension) names, they are
taken from spec, so the number of columns must match the length of
inpNames(spec). If x does have column names, all the
dimension names in inpNames(spec) must be present, and just that
set of columns will be extracted from x.
Value
An object of S3 class inpPts. See the documentation for the
generic.
See Also
Points in Input Space
Description
Create an empty inpPts object from just a function spec. This is
an internal utility method, not intended to be used by package users.
Usage
## S3 method for class 'fnSpec'
inpPts(x, ...)
Arguments
x |
|
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object of S3 class inpPts. See the documentation for the
generic.
Points in Input Space
Description
Extract an inpPts object from one inheriting from inpPairs.
This is an internal utility method, not intended to be used by package
users.
Usage
## S3 method for class 'inpPairs'
inpPts(x, which=c("raw", "1st", "2nd", "both", "paired"), ...)
Arguments
x |
Object inheriting from class |
which |
Character string indicating the form in which points are to be extracted.
|
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
When which is not "raw", points are extracted using the
pairIdxs component of x. Therefore the same point may
appear multiple times, if it belongs to multiple pairs, or not at all, if
it appears in no pairs.
Value
An object of S3 class inpPts. See the documentation for the
generic.
See Also
Points in Input Space
Description
Extract an inpPts object from an object that inherits from that
class. This is an internal utility method, not intended to be called by
package users.
Usage
## S3 method for class 'inpPts'
inpPts(x, spec=NULL, ...)
Arguments
x |
Object inheriting from class |
spec |
Optional |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object of S3 class inpPts. (Any extra components in x
are removed.) See the documentation for the generic.
See Also
inpPts, fnSpec. ptCoord
extracts the point coordinates as a plain matrix.
chkSpecCompat to check input space specification.
Rays in Input Space
Description
Create an inpRays object, or extract one from another object.
inpRays objects represent sets of 1-dimensional rays in input
space, with all the rays sharing the same origin.
Usage
inpRays(x, ...)
Arguments
x |
Either a matrix of point coordinates to be used to create a set of rays
(see |
... |
Additional arguments for specific methods. |
Details
This is an S3 generic function. There is a default method (to create a new set of rays), and methods to extract or update an existing set of rays. (Package users should call the generic however.)
A ray in input space is defined by two points: an origin and a second,
distinct point that defines the direction of the ray. All rays in an
inpRays object must have the same origin. inpRays objects
are thus a special case of inpLines objects, in which all lines
have the same position 0 point (the origin).
The second, direction-defining point represents position 1.0 for that ray.
Other positions along a ray are defined by linear interpolation or
extrapolation from those two points. Function posnToCoord()
converts positions along rays to the corresponding point coordinates. The
rayOrigin() function extracts the origin as a 1-row matrix,
rayPosn1() extracts the position 1 points as a matrix, and
rayVec() extracts the ray direction vectors.
inpRays objects optionally include an inpRect object (a
hyper-rectangle in input space). If present, the hyper-rectangle must
contain the ray origin, and the reference point of the hyper-rectangle
will be set to that origin. Position 1.0 on each ray will be set to the
ray's intersection with the boundary of the hyper-rectangle. The
hyper-rectangle associated with an inpRays object can be extracted
with the rayRect() function (which returns NULL if the object has
no associated inpRect).
In order for a ray to be well-defined, its origin and position 1 points
must be distinct. Testing for degenerate rays uses a numerical tolerance;
i.e., it tests for practical degeneracy, rather than requiring exactly
zero length. The tolerance is specified by an fnSpec specification
object.
When a hyper-rectangle is specified and the ray origin is on its boundary, it is possible for a ray to lie entirely outside the hyper-rectangle except for its origin. Such rays will be dropped, because once their position 1 points are required to intersect the hyper-rectangle they become degenerate.
Since inpRays objects are also inpLines objects, they
inherit the latter's methods for length (number of rays), [
(selecting a subset of rays), and names and names<- (extract
and set ray names). There are also plot and update methods
for inpRays objects.
Value
An object with S3 class inpRays, inheriting from inpLines.
See Also
Methods inpRays.default, update.inpRays.
inpRect, inpLines, rayOrigin,
rayPosn1, rayVec, posnToCoord,
rayRect, plot.inpRays,
update.inpRays. axisRays and
randomRays generate common types of rays.
Examples
oldopt <- lsetPkgOpt(reset=TRUE) # default options
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"))
# Rays may be defined by specifying their position 1 points and origin:
pts <- rbind(c(0, 1, 3), c(2, 2, 4), c(5, -1, 2))
orig <- c(0.2, 1.1, 5.5)
rays <- inpRays(pts, origin=orig, spec=fspec)
# Or by specifying their direction vectors and origin:
vecs <- sweep(pts, 2, orig, "-") # equivalent to 'rayVec(rays)'
rays2 <- inpRays(vecs=vecs, origin=orig, spec=fspec)
all.equal(rays, rays2) # TRUE
# Methods and accessor functions:
length(rays) # 3
rayOrigin(rays) # 1 x 3 matrix
rayPosn1(rays) # 3 row matrix
rayVec(rays) # 3 row matrix
plot(rays, dims=c(1, 3)) # rays projected to X1, X3 plane
# Quick generation of common types of rays:
axisRays(spec=fspec, degree=2, origin=orig)
set.seed(1)
randomRays(n=5, spec=fspec, origin=orig)
#-- Ray names:
rownames(pts) <- paste0("ray", seq_len(nrow(pts)))
rays3 <- inpRays(pts, spec=fspec, origin=orig)
names(rays3) # taken from row names of 'pts'
names(rays3) <- LETTERS[1:3]
names(rays3) # changed
#-- Selecting subsets of rays.
rays23 <- rays[2:3]
length(rays23) # 2
#-- Empty 'inpRays' objects are allowed:
rays0 <- inpRays(spec=fspec, origin=orig) # no rays, but origin still defined
length(rays0) # 0
identical(rays0, rays[0]) # TRUE
#-- Ray position 1 points can be (re)defined by each ray's intersection
# with the boundary of a hyper-rectangle:
rect1 <- inpRect(rbind(c(0,0,0), c(1,1,1)), spec=fspec)
# (default reference pt is center: c(0.5, 0.5, 0.5))
vecs1 <- rbind(c(-1,-1,0), c(0,0,1), c(0, -1, 1))
rays1 <- inpRays(vecs=vecs1,
rect=rect1) # default 'origin' and 'spec' taken from 'rect'
# Position 1 points for all rays are on the boundary of 'rect1':
print(rays1, vecForm=FALSE)
# Extract the hyper-rectangle associated with rays (which might be NULL).
rayRect(rays1) # 'inpRect' object
# An explicit 'origin' argument takes precedence over 'rect': the hyper-
# rectangle must include 'origin', and the copy of the rectangle stored
# within the 'inpRays' object has its reference point set to the ray origin.
rays1 <- inpRays(vecs=vecs1, origin=c(1, 1, 0.5), rect=rect1)
print(rays1, vecForm=FALSE)
all(rectRefPt(rayRect(rays1)) == rayOrigin(rays1)) # TRUE
# An existing 'inpRays' object can be updated with a new origin and/or
# hyper-rectangle (the updated rectangle must contain the updated origin).
rect2 <- inpRect(rbind(c(-1, -2, -3), c(1, 2, 3)), spec=fspec)
rays2 <- update(rays1, origin=c(0, -1, 2), rect=rect2)
rayRect(rays2) # now set to 'rect2'
rayOrigin(rays2) # updated
#-- Degenerate rays are not allowed, and will be dropped.
vecs <- rbind(c(-1,-1,0), c(0,0,0), c(0, -1, 1)) # 2nd vector has 0 length
rays <- inpRays(vecs=vecs, origin=orig, spec=fspec,
warnDegenerate=FALSE) # turns off default warning/error
length(rays) # 2, not 3
# One can also end up with a degenerate ray if a rect is specified and
# its reference point is on the boundary. In that case a ray's only
# intersection with the rect boundary may be the origin:
rect <- inpRect(rbind(c(0,0,0), c(1,1,1)), spec=fspec)
orig <- c(1,1,0.5) # on the boundary of 'rect'
vecs <- rbind(c(-1,-1,0), c(0,1,1), c(0, -1, 1))
# The second direction vector points away from the interior of 'rect',
# relative to 'orig'.
rays <- inpRays(vecs=vecs, rect=rect, spec=fspec,
origin=c(1,1,0.5), # on the boundary of 'rect'
warnDegenerate=FALSE)
# (Second ray's only intersection with 'rect' is the origin, so dropped.)
length(rays) # 2, not 3
lsetPkgOpt(oldopt) # restore starting options
Rays in Input Space
Description
Create an inpRays object directly from point coordinates in a
matrix. Can also be used to create an empty inpRays object.
Usage
## Default S3 method:
inpRays(x, vecs=NULL, origin=NULL, rect=NULL, spec=NULL,
warnDegenerate=TRUE, ...)
Arguments
x |
Matrix, each row giving the coordinates of a point in input space. Rays
are defined as the lines starting at |
vecs |
Matrix, each row specifying a vector in input space. This is an
alternative to |
origin |
Vector or 1-row matrix specifying a single point in the input space. All
rays start from this point (i.e., it is position 0 for all rays). The
default is the reference point of |
rect |
Optional |
spec |
|
warnDegenerate |
Integer or logical scalar. If 1 or TRUE (the default), a warning will be
raised if any rays are dropped because their position 1.0 point is equal
to |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
If neither x nor vecs is specified, the result will be an
inpRays object with no rays but with a defined origin.
origin defines position 0 along each ray, and the points specified
by x (directly, or indirectly via vecs) define position 1
along each ray.
Value
An object with S3 class inpRays, inheriting from inpLines.
Ray names are taken from the row names of x or vecs, if any.
Examples
# See the examples in '?inpRays'
Rays in Input Space
Description
Convert an acceptable inpLines object to an inpRays object,
optionally adding a reference hyper-rectangle. This is an internal
utility method, not intended to be used by package users.
Usage
## S3 method for class 'inpLines'
inpRays(x, origin=NULL, ...)
Arguments
x |
An object inheriting from class |
origin, ... |
Additional arguments passed to the default method for |
Value
An object with S3 class inpRays, inheriting from inpLines.
See Also
Rays in Input Space
Description
Extract an inpRays object from one inheriting from that class.
(Basically a no-op, but seems logical and friendly that
inpRays(rays) should work, given the "create or extract" idea.)
Updating operation moved to update.inpRays method. This is an
internal utility method, not intended to be used directly by package
users.
Usage
## S3 method for class 'inpRays'
inpRays(x, ...)
Arguments
x |
|
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
Any extending classes of x are droppped.
Value
An object with S3 class inpRays, inheriting from inpLines.
Rays in Input Space
Description
Extract the inpRays component from a respProfiles or
lsetSegs object. (There is no such component in a solely
respPts or respPairs object, but the respPts class is
shared by both respProfiles and lsetSegs, so it's convenient
to provide a single method for both.) This is an internal utility method,
not intended to be used by package users.
Usage
## S3 method for class 'respPts'
inpRays(x, ...)
Arguments
x |
A |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class inpRays, inheriting from inpLines.
See Also
Hyper-Rectangle in Input Space
Description
Create an inpRect object, representing a finite, axis-aligned,
hyper-rectangle in the input space of a response function.
Usage
inpRect(x, refpt=NULL, spec)
Arguments
x |
A two-row matrix. The first row contains the coordinate vector of the lower corner of the hyper-rectangle, and the second the coordinate vector of the upper corner. |
refpt |
Optional vector or one-row matrix containing the coordinates of a single point. The point must be in the hyper-rectangle (see DETAILS). It can be used to indicate a reference or special point of the rectangle. If not specified, the center of the rectangle will be used. |
spec |
|
Details
All coordinates in x must be non-NA and finite, and the
hyper-rectangle must have non-zero volume (see below).
If refpt is specified it will be checked to make sure it belongs to
the hyper-rectangle. If it is slightly outside, to within tolerances
specified by spec, then x will be adjusted to put
refpt exactly on its boundary.
Positive volume is defined as follows: For each dimension j,
absolute tolerances for the lower and upper limits are calculated as
atol[, j] <- absTol(x[, j], inptol=inpTol(spec)[, j]). The
separation between x[1, j] and x[2, j] is considered
non-zero if x[2, j] - x[1, j] is strictly greater than
1.5*(atol[2] + atol[1]). The hyper-rectangle is considered to have
positive volume only if this separation is non-zero for all dimensions.
The corners of an inpRect object can be extracted with function
rectCorners(), the reference point with rectRefPt(), and the
lengths of the sides with rectSize().
There are plot, print, and update methods for this
class.
Value
An object with S3 class inpRect.
See Also
rectCorners, rectRefPt,
rectSize, absTol
Examples
oldopt <- lsetPkgOpt(reset=TRUE) # default settings
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"))
# Directly create a hyper-rectangle:
rect1 <- inpRect(rbind(c(0, -1.1, -4), c(2, -0.5, 1000)), spec=fspec)
rect1
# Accessor functions.
rectCorners(rect1)
rectRefPt(rect1)
rectSize(rect1)
# Non-default reference point:
rect2 <- inpRect(rbind(c(0, 1, 1), c(0.5, 3, 6)), refpt=c(0, 1, 4),
spec=fspec)
rectRefPt(rect2)
# Update reference point:
rect2b <- update(rect2, refpt=c(0.2, 3, 3))
rectRefPt(rect2b)
# The reference point must belong to the rectangle. However if it is only
# slightly outside (within a numerical tolerance) the rectangle will
# be adjusted to accomodate it.
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"),
inptol=c(0, 1e-3)) # defines "slightly"
rect3 <- inpRect(rectCorners(rect2), spec=fspec)
update(rect3, refpt=c(0.2, 3 + 5e-4, 3)) # slightly bigger, ref pt on boundary
lsetPkgOpt(oldopt) # restore starting settings
Scaling Information for Dimensions of Input Space
Description
Create an inpScale object, containing scaling information for the
dimensions of the input space of a response function.
Usage
inpScale(x=rep(1, d), spec)
Arguments
x |
Vector or matrix. If a vector, its length must equal the number of dimensions of the input space, and all values must be strictly positive and finite. A matrix must be square, symmetric, and positive-definite, with dimensions matching the input space. See DETAILS. |
spec |
|
Details
When dimensions of the input space have different units; or point
coordinates for different dimensions have different magnitudes; or the
level set of interest is elongated in certain directions, it may be useful
to rescale and/or weight the dimensions when calculating distances or
angles in input space. inpScale objects provide a way to specify
such scaling.
The simplest case is when x is a vector of scaling factors, one
scale factor per input space dimension. For example if the input space
has three dimensions X1, X2, and X3, and in the
region of interest their typical magnitudes are 2,000, 0.003, and 5, then
set x to c(2e3, 3e-3, 5). The goal is that dividing
coordinates by their scaling factors should standarize them: coordinates
for different dimensions should be roughly similar in magnitude,
preferably with a magnitude close to 1.
A matrix x generalizes this by effectively allowing a rotation of
the coordinate axes before applying scaling. Details are given below, in
terms of the components of the returned object. Note that specifying a
vector x is equivalent to a matrix x where the diagonal
contains the _squares_ of the vector values, and off-diagonal elements are
0.
In the following, let V denote the matrix specified by x
(either x itself, or diag(x^2) if x is a vector).
Weighted distance in input space. The weighted distance between
points u and v in input space is defined as the square root
of the quadratic form t(u - v) %*% V^(-1) %*% (u - v), where
V^(-1) is the inverse of V. Defining square matrix W
so that t(W) %*% W = V^(-1), the weighted distance between u
and v is the ordinary unweighted Euclidean distance between vectors
W %*% u and W %*% v.
The analogous statistical concept is Mahalanobis distance, where V
represents a covariance matrix.
Other interpretations of inpScale objects. A related use for
inpScale objects is to convert back and forth between point
coordinates in input space, and coordinates in a more generic,
standardized space where all dimensions and directions are considered
equivalent. If y represents a point in input space and z
represents the same point in standardized space, the transformations are:
z = W %*% y and y = W^(-1) %*% z.
For example, points that lie on the ellipsoid t(y) %*% V^(-1) %*% y
= 1 in input space can be transformed to points that lie on the unit
hypersphere t(z) %*% z = 1 in standardized space, and vice versa.
Yet another way to think about an inpScale object is that it
defines a new coordinate system in input space, with axes given by the
columns of W^(-1). For a given point y in the original
coordinate system, its coordinates in the new system are z = W %*%
y.
Note that coordinate vectors in this package are stored as rows of
d-column matrices, rather than as individual column vectors. So
the way to apply transformation matrix W to a set of points in
n-by-d matrix X is tcrossprod(X, W), yielding
another n-by-d matrix, and analogously for W^(-1).
Construction of transformation matrices. In this function W
is constructed from the spectral decomposition of V: W =
diag(1 / sqrt(lambda)) %*% t(P), where P is a matrix whose columns
are the eigenvectors of V and lambda is the vector of
eigenvalues of V. Thus W^(-1) = P %*% diag(sqrt(lambda)).
However in the special case when V is diagonal, the columns of
P (which are just permutations of c(1, 0, ..., 0)) and
elements of lambda (which is just w^2) are sorted to match
the dimensions of input space, rather than sorted by decreasing
lambda. This preserves a correspondence between individual
dimensions in input and standardized spaces, when standardization only
involves scaling, not rotation.
The sign of eigenvectors is arbitrary. To increase consistency of the
returned object, the sign of the i-th column of P is chosen
so that its i-th element is positive, provided the latter is not
negligible in magnitude (i.e., it is greater than 1/(100*sqrt(d))).
Otherwise the sign is chosen so that the element with the largest
magnitude is positive.
Value
An object of S3 class inpScale. This is a list with components:
V |
Square, symmetric, positive definite matrix equal to argument |
w |
Vector, the reciprocals of the square root of the diagonal of |
W |
Square matrix, a square root of the inverse of |
Winv |
Square matrix, the inverse of |
V_is_diag |
Logical scalar, TRUE if |
fnSpec |
|
See Also
fnSpec. Examples for randomRays show effects
of specifying various inpScale objects.
Examples
oldopt <- lsetPkgOpt(reset=TRUE) # default settings
dat <- data.matrix(iris[, 1:4]) # 150 points in 4D space
fspec <- fnSpec(inpnames=colnames(dat))
covmat <- cov(dat)
sds <- sqrt(diag(covmat))
cormat <- cor(dat)
# Mahalanobis distances of points from 0-origin.
mdist <- apply(dat, 1, function(y) { sqrt( t(y) %*% solve(covmat) %*% y) })
# 'inpScale' objects include a matrix to transform point coordinates so that
# Euclidean distances for transformed points equal Mahalanobis distances
# for original points.
scl <- inpScale(covmat, spec=fspec)
tdat <- tcrossprod(dat, scl$W) # Transformed points
edist <- sqrt(rowSums(tdat^2)) # Euclidean dist using transformed vectors
all.equal(mdist, edist) # TRUE
# Coordinate system rescaling/rotation.
chk1 <- sweep(dat, 2, scl$w, "*") # re-scale each dimension to unit SD
all.equal(cov(chk1), cormat) # TRUE
chk2 <- tcrossprod(dat, scl$W) # both re-scale and orthogonalize
all.equal(cov(chk2), diag(4)) # TRUE
# Reverse the transformation:
z_to_y <- scl$Winv
chk3 <- tcrossprod(chk2, z_to_y)
dimnames(chk3) <- dimnames(dat)
all.equal(chk3, dat) # TRUE
# Default 'inpScale' contains only identity transformations ('w', a vector
# of 1's, 'V' the identity matrix):
scl <- inpScale(spec=fspec)
scl$w
scl$V
scl$V_is_diag
#----- 2D example of change of coordinate system.
fspec <- fnSpec(inpnames=c("X1", "X2"))
scl <- inpScale(matrix(c(5, 2, 2, 1), nrow=2), spec=fspec)
W <- scl$W
Winv <- scl$Winv
# Point in original coordinate system:
y <- c(3, 1)
plot(c(-1, 5), c(-1, 5), type="n", axes=FALSE, xlab="X1", ylab="X2")
axis(side=1, pos=0)
axis(side=2, pos=0)
points(x=y[1], y=y[2])
# Draw axes of new coordinate system, with tick marks ('x') at unit intervals.
ax1units <- rbind(c(1, 0), c(2, 0), c(3, 0))
ax2units <- rbind(c(0, -1), c(0, 1), c(0, 2), c(0, 3), c(0, 4))
abline(a=0, b=Winv[2, 1] / Winv[1, 1], col="orchid1")
points(ax1units %*% t(Winv), pch=4, col="orchid1")
abline(a=0, b=Winv[2, 2] / Winv[1, 2], col="orchid1")
points(ax2units %*% t(Winv), pch=4, col="orchid1")
# Same point in new coordinate system:
z <- W %*% y
cat("Point coordinates in new system= ", toString(round(z, 3)), "\n")
# Projection of the point onto the new axes (expressed in the original
# coordinates, because that's what the plot uses):
y_z1 <- Winv %*% c(z[1], 0)
y_z2 <- Winv %*% c(0, z[2])
segments(x0=y[1], y0=y[2], x1=c(y_z1[1], y_z2[1]), y=c(y_z1[2], y_z2[2]),
lty=3, col="orchid1")
lsetPkgOpt(oldopt) # restore starting settings
Numerical Tolerance Specifications for the Input Space
Description
Return tolerance specifications for each dimension of the input space associated with an object.
Usage
inpTol(x)
Arguments
x |
An |
Value
Two-row matrix with d columns, where d is the number of
dimensions in the input space. The first row contains a relative
tolerance for each dimension and the second row contains a minimum
absolute tolerance.
See Also
lsetPkgOpt and absTol describe how tolerances
are specified in this package. fnSpec,
fnObj.character
Examples
# See examples in '?fnSpec'
Internal (Non-Public) Settings and Controls
Description
Internal (non-public) settings and controls for the package. This is an internal utility function, not intended to be called by package users.
Usage
internalOpt(..., reset=FALSE)
Arguments
... |
Either a single unnamed character vector, or one or more |
reset |
Logical. If TRUE, options are reset to their |
Details
The current set of option values is stored as object .internalOpt
in the function environment or package namespace.
Value
If reset is TRUE, the whole list of previous (before the reset)
option values is returned, invisibly.
Otherwise the return value depends on the form of .... If the
first argument does not have a name and is a plain character vector then
the rest of ... is ignored and a list containing the values of the
options named by the vector is returned. However, if the vector contains
only a single option name, the actual value of the option is returned (not
wrapped in a list of length 1).
If the first argument does not have a name and is a list with named
components then the rest of ... is ignored and the list components
are used to set the values of the named options. A list of the previous
values of those options is returned (invisibly).
If ... is a series of name=value pairs, they are treated as
if they were a single list with named components.
In all cases it is an error to request or set the value of an unknown package option.
internalOpt() returns a list with current values of all options.
See Also
Merge Intervals on the Real Line
Description
Merge a set of possibly overlapping intervals on the real line into a set of non-overlapping intervals. This is an internal utility function, not intended to be called by package users.
Usage
interval_merge(x, abstol=0)
Arguments
x |
Two-row matrix. Each column contains the sorted endpoints of a single interval. |
abstol |
Non-negative tolerance. If the lower end of one interval is no more than this amount above the upper end of another interval, the two intervals are considered touching, and are merged. |
Value
Two-row matrix. Each column contains the sorted endpoints of a single interval. The intervals do not overlap.
Number of Point Pairs/Lines/Rays/Segments Defined by an Object
Description
length method for objects inheriting from class inpPairs.
It returns the number of _point pairs/lines/rays/segments_ defined by the
object. This is an internal utility method, not intended to be used by
package users.
Usage
## S3 method for class 'inpPairs'
length(x)
Arguments
x |
An object inheriting from class |
Value
One-element vector: number of point pairs/lines/rays defined by x.
This will match the number of columns in pairIdxs(x).
See Also
Number of Input Space Points in an Object
Description
length method for objects inheriting from class inpPts (but
not from inpPairs). It returns the number of points in input space
contained in the object represented by the object. This is an internal
utility method, not intended to be used by package users.
Usage
## S3 method for class 'inpPts'
length(x)
Arguments
x |
An object inheriting from class |
Value
One-element vector: number of input space points in x.
See Also
'length' Method for 'respProfiles' Objects
Description
length method for respProfiles objects. It returns the
number of lines/rays profiled in the object. This is an internal method,
package users should call the generic function.
Usage
## S3 method for class 'respProfiles'
length(x)
Arguments
x |
A |
Value
One-element vector: number of lines/rays profiled in x.
See Also
Coordinates of Position 0 on a Set of Lines in Input Space
Description
Extract the coordinates of the points representing position 0 on each of
the lines defined by an inpLines object. This is an internal
utility function, not intended to be called by package users.
Usage
linePosn0(x)
Arguments
x |
An object inheriting from class |
Details
inpLines objects contain 1-dimensional lines in input space. Each
line is defined by a pair of distinct points, with the first point in a
pair defining position 0 on the line, and the second point position 1.0.
This function returns the coordinates of the position 0 points.
Value
Matrix with one row for each line in x.
See Also
inpLines, inpRays, linePosn1,
lineVec
Coordinates of Position 1 on a Set of Lines in Input Space
Description
Extract the coordinates of the points representing position 1 on each of
the lines defined by an inpLines object. This is an internal
utility function, not intended to be called by package users.
Usage
linePosn1(x)
Arguments
x |
An object inheriting from class |
Details
inpLines objects contain 1-dimensional lines in input space. Each
line is defined by a pair of distinct points, with the first point in a
pair defining position 0 on the line, and the second point position 1.0.
This function returns the coordinates of the position 1.0 points.
Value
Matrix with one row for each line in x.
See Also
inpLines, inpRays, linePosn0,
lineVec
Direction Vectors for a Set of Lines in Input Space
Description
Extract the direction vectors of the lines defined by an inpLines
object. This is an internal utility function, not intended to be called
by package users.
Usage
lineVec(x)
Arguments
x |
An object inheriting from class |
Details
inpLines objects contain 1-dimensional lines in input space. Each
line is defined by a pair of distinct points, with the first point in a
pair defining position 0 on the line, and the second point position 1.0.
This function returns the vectors equal to the difference between points
at positions 1 and 0 on each line.
Value
Matrix with one row for each line in x.
See Also
inpLines, inpRays, linePosn0,
linePosn1
Extract or Set Options for the 'levelSets' Package
Description
Extract or set user-level options for the levelSets package.
Usage
lsetPkgOpt(..., reset=FALSE)
Arguments
... |
Either a single unnamed character vector, or one or more |
reset |
Logical. If TRUE, options are reset to their |
Details
The available options, with their factory-fresh defaults are:
- resptol, inptol
Tolerances to use when deciding whether two response values, or coordinates for two points in input space, should be treated as equal or equivalent. Tolerances are necessary to allow for representation and roundoff errors in floating point calculations. In addition, for most applications there are limitations on measurement, data, or model accuracy which are even larger than floating point errors. These mean that small numerical differences are not meaningful in practice. Therefore tolerances larger than those required just by floating point errors are usually appropriate.
Values for these options are handled like the
tolargument toabsTol(), so are two-element vectors in general. The first value specifies a relative tolerance (i.e., as a proportion of the magnitude of a number), and the second specifies a minimum absolute tolerance (constant regardless of the magnitude of a number). If only a single value is specified it is used as the relative tolerance, and the minimum absolute tolerance is set tosqrt(.Machine$double.eps). Relative tolerances must be no larger than1e-3(implying at least three significant digits in response or point coordinate values). The minimum absolute tolerance must be strictly greater than 0.The default for
resptolisc(1e-5, sqrt(.Machine$double.eps)). Forinptolit isc(1e-6, sqrt(.Machine$double.eps)).- warn.showBadRespPts
Non-negative integer. The maximum number of feasible points with NA or infinite response values for which coordinates will be printed, as part of warnings/errors. (See
?fnObj.) Default is 3.- warn.invalidProfile
Non-negative integer. Whether to generate warnings about response profiles along a line/ray that show an unexpected pattern of level set boundary crossings. (For example, two consecutive boundary crossings where the response trend is increasing for both or decreasing for both–such a pattern suggests there should be an intermediate crossing with the opposite trend.) Such warnings depend on derivative/ trend information, so will not be generated if
derivMethodisnone. A value of 0 suppresses the warning, 1 generates just the warning, and 2 also prints the problematic profile. Default is 1.
Value
If reset is TRUE, the whole list of previous (before the reset)
option values is returned, invisibly.
Otherwise the return value depends on the form of .... If the
first argument does not have a name and is a plain character vector then
the rest of ... is ignored and a list containing the values of the
options named by the vector is returned. However, if the vector contains
only a single option name, the actual value of the option is returned (not
wrapped in a list of length 1).
If the first argument does not have a name and is a list with named
components then the rest of ... is ignored and the list components
are used to set the values of the named options. A list of the previous
values of those options is returned, invisibly.
If ... is a series of name=value pairs, they are treated as
if they were a single list with named components.
In all cases it is an error to request or set the value of an unknown package option.
lsetPkgOpt() returns a list with current values of all options.
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
# Default 'factory-fresh' options:
defopt <- lsetPkgOpt()
str(defopt)
# Single option requested: returns plain vector, not list
tol1 <- lsetPkgOpt("resptol")
oldtol1 <- lsetPkgOpt(resptol=1e-4) # returns old value as list of length 1
identical(tol1, oldtol1[[1]])
# Two or more options requested: list is returned
opts <- lsetPkgOpt(c("warn.invalidProfile", "warn.showBadRespPts"))
oldopts <- lsetPkgOpt(warn.invalidProfile=0, warn.showBadRespPts=10)
identical(opts, oldopts) # both lists with two components
lsetPkgOpt(reset=TRUE) # restores defaults
identical(lsetPkgOpt(), defopt) # TRUE
# Restore starting options.
lsetPkgOpt(oldopt)
Line Segments in a Level Set of a Response Function
Description
Create an lsetSegs object, or extract one from another object.
lsetSegs objects contain 1-dimensional line segments in the input
space of a response function. Each segment is defined by a pair of
distinct points, the segment endpoints, that belong to the level set, with
the assumption that every point on the segment connecting them also
belongs to the level set.
Usage
lsetSegs(x, ...)
Arguments
x |
Object containing information from which an |
... |
Additional arguments for internal methods only. |
Details
An lsetSegs object contains pairs of points that represent
endpoints of line segments in input space. The restrictions on the
endpoints are that (a) all endpoints belong to the level set; (b) the
endpoints in a pair are distinct points; (c) it can be assumed that all
the points on the line segment connecting a pair also belong to the level
set; and (d) each pair of endpoints lies along a line that is explicitly
represented in the object (by an inpLines or inpRays
object).
Requirement (c) follows trivially from (a) if the level set is a single, convex region of input space. However if the level set may be non-convex or has disconnected parts, it is up to the function that creates the object to ensure that the assumption is reasonable.
Function inpLines() extracts the input space lines or rays from
requirement (d). A given line/ray may have 0, 1, or >1 level set segments
in the lsetSegs object.
Requirement (b) for distinct points means segment endpoints must be
separated by at least an amount calculated from input tolerances in the
response function specification. (See ?lsetPkgOpt and
?fnObj.character).
Function respInfo() applied to an lsetSegs object returns a
data frame with response values and other information about the segment
endpoints. Function segInfo() applied to an lsetSegs
object returns a data frame with one row per segment. See their
documentation for the columns included. Note that column line
indexes the line (in the object returned by applying inpLines() to
the lsetSegs object) along which the endpoint or segment lies.
The class has methods for length (the number of segments, which
might be 0), [ (selecting segments), c (to combine sets of
segments), summary, plot, and pairs.
Extraction from other objects. This function will extract the
lsetSegs object contained in the return value from functions
bdryFromRays, bdrySearch, and lsetSegsCheck.
If x is a respProfiles object, this function will create an
lsetSegs object from it, using the threshold specified when
x was created (which must not be NA). Note that this function does
not actually search for level set boundary points (see the functions
mentioned in the previous paragraph for that). It only examines the
existing discrete set of profile points in x.
A profile point is considered to belong to the level set if its
lset value (from respInfo(x)) is TRUE. A level set segment
consists of a run of consecutive profile points that all belong to the
level set, and is represented by the first and last points in the run.
Runs consisting of a single point are dropped (since segment endpoints
must be distinct.) A given profile may have zero, one, or more than one
level set segment.
A segment is considered uncensored at one of its endpoints if either
lsetbdry or feasbdry for the point is TRUE, and censored
otherwise. Therefore the censoring indicator lsetcens for segment
endpoints will never be NA.
Value
An object with S3 classes c("lsetSegs", "respProfiles").
See Also
lsetSegs objects are created by functions
bdryFromRays and bdrySearch and their sliced
versions, and by lsetSegsCheck. Useful accessor functions
and methods are: segInfo, respInfo,
summary.lsetSegs, plot.lsetSegs,
pairs.lsetSegs. lsetThresh extracts the
response value that defines the level set, and fnSpec
extracts information about the response function and its input space.
Examples
# see examples in '?bdryFromRays', '?respInfo', '?segInfo'
Line Segments in a Level Set of a Response Function
Description
Extract an lsetSegs object from a list that contains one as a
component names segs. This is an internal utility method, not
intended to be called by package users.
Usage
## Default S3 method:
lsetSegs(x, ...)
Arguments
x |
List with a component named |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 classes c("lsetSegs", "respProfiles"). See the
generic function for more details.
See Also
Line Segments in a Level Set of a Response Function
Description
Create an empty lsetSegs object from a fnSpec. This is an
internal utility method, not intended to be called by package users.
Usage
## S3 method for class 'fnSpec'
lsetSegs(x, lsetthresh, lines=NULL, checkArg=FALSE, ...)
Arguments
x |
|
lines |
Optional object inheriting from class |
lsetthresh |
Scalar with the response function value that defines the level set of interest. |
checkArg |
Logical scalar. If TRUE, |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
The lines on which level set segments lie are specified by argument
lines
Value
An object with S3 classes c("lsetSegs", "respPairs", "inpPairs",
"respProfiles", "respPts", "inpPts").
See Also
Line Segments in a Level Set of a Response Function
Description
Return an lsetSegs object unchanged. This method is needed to
avoid dispatching to the respProfiles method. This is an internal
utility method, not intended to be called by package users.
Usage
## S3 method for class 'lsetSegs'
lsetSegs(x, ...)
Arguments
x |
An |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
Same as x.
See Also
Line Segments in a Level Set of a Response Function
Description
Manually create an lsetSegs object from a set of point pairs
belonging to the level set, by adding information about the lines/rays the
pairs lie on. This is an internal utility method, not intended to be
called by package users.
Usage
## S3 method for class 'respPairs'
lsetSegs(x, lines, checkArg, ...)
Arguments
x |
Object inheriting from class |
lines |
Object inheriting from class |
checkArg |
Logical scalar. If TRUE, |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
The lines on which the point pairs lie are specified by argument
lines, and this is verified if checkArg is TRUE. The
respPairs object containing the point pairs must have the necessary
respInfo and pairInfo data frame columns for an
lsetSegs object; and points must actually belong to the lines
specified by their respInfo(x)[, "line"] values.
Value
An object with S3 classes c("lsetSegs", "respProfiles").
See Also
Line Segments in a Level Set of a Response Function
Description
Given response function profiles along a set of lines (a
respProfiles object), including any detected level set boundary
intersections, identify intervals along each line that appear to be
entirely in a level set. Results are returned as an lsetSegs
object. This is an internal utility method, not intended to be called by
package users.
Usage
## S3 method for class 'respProfiles'
lsetSegs(x, ...)
Arguments
x |
Object inheriting from class |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
This function does not search lines for intersections with the level set
boundary (see bdryFromRays for that). It only examines the
existing discrete set of line points in x.
A profile point is considered to belong to the level set if its
lset value (from respInfo(x)) is TRUE. A level set segment
consists of a run of consecutive profile points that all belong to the
level set, and is represented by the first and last points in the run.
Runs consisting of a single point are dropped (since segment endpoints
must be distinct.) A given profile may have zero, one, or more than one
level set segment.
A segment is considered uncensored at one of its endpoints if either
lsetbdry or feasbdry for the point is TRUE, and censored
otherwise. Therefore the censoring indicator lsetcens for segment
endpoints will never be NA.
Value
An object with S3 classes c("lsetSegs", "respProfiles"). See the
generic function for more details.
See Also
Check the Validity of Level Set Line Segments
Description
Check the validity of level set line segments in an lsetSegs
object. A segment is valid if every point along it belongs to the level
set; this function checks at a series of user-specified positions.
Optionally attempt to fix invalid segments by replacing them with one or
more sub-segments that are valid. Also check the consistency of multiple
segments along the same line/ray.
Usage
lsetSegsCheck(x, fnobj, posns, fixCycles=1, resptol=respTol(x))
Arguments
x |
An |
fnobj |
|
posns |
Vector of values in the interval [0, 1] specifying positions along each
segment in |
fixCycles |
Non-negative integer. If greater than 0 an attempt will be made to fix
invalid segments by finding valid subintervals. Those subintervals will
themselves be checked and fixed, using up to |
resptol |
Optional vector of length 2, specifying tolerance parameters for the
function response. The default is taken from |
Details
The result may still contain invalid level set segments (those unable to
be fixed after fixCycles attempts). They can be removed by
subseting the segs component by the validOut component.
Note that the presence of invalid segments implies the level set is non-convex or has disconnected parts along the lines containing those segments.
If x contains any lines/rays with more than one segment, there will
be a check whether the segments are overlapping or contiguous, and if so,
whether they are consistent and can be merged:
Contiguous or overlapping segments on a line are consistent if all segment
endpoints in the interior of the merged segment are censored. They are
merged into a single segment. Uncensored interior endpoints indicate that
the individual searches that produced them probably missed some
intermediate boundary crossings. (For example, initPosns was too
coarse relative to fluctuations in the response function.) Inconsistent
pairs of segments are identified in component inconOut but are not
merged.
Value
A list with components:
validIn |
Logical vector with one element per segment in |
validOut |
Logical vector similar to |
inconOut |
Two-column matrix. Each row contains the indices of a pair of segments in
|
segs |
|
resp |
Matrix of response values at each position (column) on each segment (row)
of |
See Also
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
fobj <- Ex$fobj
segs <- Ex$segs
rect0 <- Ex$rect0
plot(segs, rect=rect0, main="Original segments from 'bdryFromRays()'")
# Some segments cross the gap between parts of the level set, making them
# invalid:
chk <- lsetSegsCheck(segs, fnobj=fobj, posns=(1:4)/5)
table(chk$validIn) # 8 invalid segments ...
table(chk$validOut) # all appear to have been fixed by splitting into
# two valid segments
segs_fixed <- chk$segs # could also use 'lsetSegs(chk)'
plot(segs_fixed, rect=rect0,
main="Segments after processing by 'lsetSegsCheck()'")
lsetPkgOpt(oldopt)
Response Function Value that Defines a Level Set
Description
Extract the response function value that defines a particular level set,
from a respProfiles or lsetSegs object.
Usage
lsetThresh(x)
Arguments
x |
An object inheriting from class |
Value
Numeric scalar, possibly NA (including if x is NULL).
See Also
Examples
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
segs <- Ex$segs # 'lsetSegs' object
lsetThresh(segs)
# See '?respProfiles' for other examples
Response/Feasibility as Functions of Position along a Line
Description
Utility function for working with fnObj objects. Create a function
that reparameterizes the response and feasibilty functions, so that they
are functions of position along a line in input space. The line is
specified by two distinct points that define positions 0 and 1.0 along the
line. Optionally the returned function also evaluates the derivative of
the target function with respect to position. This is an internal utility
function, not intended to be called by package users.
Usage
make_line_profile_fun(fnobj, x0, x1, lineidx=NA_integer_,
def_dmethod=derivMethod(fnobj))
Arguments
fnobj |
A |
x0, x1 |
1-row matrices with the coordinates of two distinct (with respect to
tolerance |
lineidx |
Optional integer line number, to include in the environment of the returned function. |
def_dmethod |
The derivative method that the created |
Details
The way the returned function calculates the derivative of the response
function with respect to position along the line depends on its argument
derivmethod.
If derivmethod is gradient, the derivative at a point is
calculated as the inner product of the gradient at that point with the
direction vector x1 - x0. It will be NA if the gradient returned
by targ_fun is NA.
If derivmethod is finite difference, the response function
will be evaluated at positions shifted by 2*atol_posn up and down
from a point, and changes across those three points will be used to
approximate the derivative. atol_posn is calculated from
posn using function absTolPosn_1line. trend will be
NA if the point is infeasible or if both shifted points are infeasible.
The returned function includes a number of variables in its environment
(including x0, x1, lineidx, derivmethod and
tolerance parameters), that may be extracted by other functions that use
it.
The conversion of line positions to point coordinates introduces roundoff
error, which can then lead to points that do not strictly belong to the
line's slice, or even to the feasible region. So the returned function
detects dimensions with identical coordinates in x0 and x1
and forces all positions on their line to match the coordinates for those
dimensions. (This is also done in posn_to_coord2.)
Value
A function that takes arguments:
posn |
Vector of positions along the line defined by |
type |
Character string, one of |
returnVec |
Logical scalar. |
derivmethod |
Character string specifying whether and how to calculate the derivative of
the response function with respect to position along the line. One of
"none", "finite difference", or "gradient". Ignored when |
The return value of the function depends on type and
returnVec: If type is feasibility, a logical vector
with the same length as posn. If type is response
and returnVec is TRUE, a numeric vector of response values with the
same length as posn. If type is response and
returnVec is FALSE, a data frame with one row per position, and
columns posn; resp; feas (TRUE or FALSE); and
deriv (derivative of response function with respect to position
along the ray–NA if derivmethod is none). The data frame
will have a gradient attribute if derivmethod is
gradient.
See Also
fnObj, absTolPosn_1line.
tied_endpts to test whether two points are considered
distinct.
Merge Two Pre-respprofiles Lists
Description
Helper function for profiling a response function along lines/rays. This
function merges a new pre-respProfiles list into an existing list
for a single line. These lists are intermediates between respPts
and respProfiles objects, with all the components of a
respProfiles except inpLines, but extra respInfo
columns compared to a respPts. This is an internal utility
function, not intended to be called by package users.
Usage
merge_pre_respProfiles(curr_prof, new_prof, mergeTies=TRUE,
abstol_posn)
Arguments
curr_prof, new_prof |
Lists, with structure intermediate between |
mergeTies |
Logical scalar; if TRUE, points in |
abstol_posn |
Numeric vector with the same length as |
Details
Points in new_prof are added to those in curr_prof, and the
result is sorted by posn.
However if mergeTies is TRUE, there is some preprocessing. If a
given point in new_prof has the same position (to within its
numerical tolerance in abstol_posn) as one or more points in
curr_prof, the latter are dropped after transferring some
information to the new point. Specifically, if any tied current point has
feasbdry or lsetbdry TRUE, the corresponding variable for
the new point is set to TRUE. If all the tied current points have
feasbdry or lsetbdry FALSE, and the corresponding variable
for the new point is NA, it is set to FALSE.
Note that the preprocessing does not search for position ties
within curr_prof or new_prof.
Value
List combining curr_prof and new_prof, with points sorted by
posn.
See Also
For Each Line/Ray in an 'lsetSegs' Object, Check Whether Multi..
Description
For each line/ray in an lsetSegs object, check whether multiple
segments are overlapping or contiguous, and if so, whether they are
consistent and should be merged. Identify but don't merge overlapping but
inconsistent segments. This is an internal utility function, not intended
to be called by package users.
Usage
merge_segs(x)
Arguments
x |
|
Details
Segments in x on the same line that are contiguous or overlapping,
and that are consistent (see below), are merged. Inconsistent segments
are identified but not merged.
Contiguous or overlapping segments on a line are consistent if all segment
endpoints in the interior of the merged segment are censored. Uncensored
interior endpoints indicate that the individual searches that produced
them probably missed some intermediate boundary crossings. (For example,
initPosns was too coarse relative to fluctuations in the response
function.)
If two segments in x are inconsistent, then the segments in
xmrg that contain them must also be inconsistent. Conversely, if
two segments in xmrg are inconsistent, they must contain
inconsistent segments from x; i.e., merging never creates
inconsistency that was not already present.
Value
List with components:
xmrg |
Object like |
mrgidx |
Vector parallel to |
incon_x |
Two-column matrix. Each row contains the indices of a pair of segments in
|
incon_xmrg |
Two-column matrix. Each row contains the indices of a pair of segments in
|
See Also
seg_consistency_1line, sort.lsetSegs,
interval_merge
Version of 'utils::modifyList' that Allows 'val' to be NULL
Description
Local copy of utils::modifyList that allows val to be NULL
(leading to a no-op). This is an internal utility function, not intended
to be called by package users.
Usage
modify_list(x, val, keep.null=FALSE)
Arguments
x |
Named list, possibly empty. |
val |
Named list with components to replace corresponding components of
|
keep.null |
Logical scalar. See |
Value
List, a modified version of x.
See Also
utils::modifyList
Change NA Values in a Logical Vector or Array to FALSE
Description
Change NA values in a logical vector or array to FALSE. This is an internal utility function, not intended to be called by package users.
Usage
naF(x)
Arguments
x |
Logical vector or array. |
Value
Logical vector or array with the same length/shape as x
Names of Lines/Rays
Description
names method for objects inheriting from class inpLines. It
returns a character vector with the names of the lines/rays in x,
or NULL if they have no names. This is an internal utility method.
Package users should call the generic names function.
Usage
## S3 method for class 'inpLines'
names(x)
Arguments
x |
An object inheriting from class |
Details
There is also a method names<-.inpLines, not separately documented,
to assign/change the names of lines.
Value
Character vector or NULL.
See Also
'names' Method for 'respProfiles' Objects
Description
Extract the names of the lines/rays profiled in a respProfiles
object. This is an internal method, package users should call the generic
function.
Usage
## S3 method for class 'respProfiles'
names(x)
Arguments
x |
An object inheriting from class |
Value
Character vector with the names of the lines/rays profiled in x, or
NULL if they have no names.
See Also
Numeric Matrix from a Data Frame or Vector
Description
Convert a simple numeric or logical vector to a 1-row matrix, or a data
frame with (only) numeric and logical variables into a numeric matrix. It
is an error if any columns (or, if specified, just the columns in
inpnames) are not numeric or logical. This is an internal utility
function, not intended to be called by package users.
Usage
num_matrix(x, inpnames=NULL)
Arguments
x |
A data frame with numeric or logical variables only, or a numeric or
logical vector or matrix. May also be an object inheriting from class
|
inpnames |
Optional character vector with the names of columns to extract from
|
Value
A numeric matrix. If x is a simple vector, the returned matrix
will have one row.
See Also
base::data.matrix
Ordering Permutation for Points, Point Pairs, or Line Segments
Description
order method for ptsClass objects. (Not strictly an S3 method
since order is not generic.) Ordering is by one or more of the
variables in data frame respInfo(x), pairInfo(x), or
segInfo(x). This is an internal utility function, not intended to
be called by package users.
Usage
order_ptsClass(x, by, ...)
Arguments
x |
Object inheriting from class |
by |
Character vector with the names of one or more columns in the data frame
|
... |
Additional arguments passed to |
Value
An index vector into x such that x[ord] is sorted by the
by variables.
See Also
respPts, respPairs, respInfo,
pairInfo, segInfo
Indices of the Points Defining Point Pairs
Description
Extract the indices of the points defining each point pair in an object
inherting from class inpPairs. This is an internal utility
function, not intended to be called by package users.
Usage
pairIdxs(x)
Arguments
x |
An object inheriting from class |
Details
inpPairs objects contain pairs of points in input space. Since
points in a pair must be distinct, each pair defines a line in input
space. Row 1 of the returned matrix contains the indices (into rows of
ptCoord(x) or respInfo(x) for example) of the points
defining position 0 on each line, and row 2 contains the indices of the
points defining position 1.
Value
Two-row matrix. Each column contains the indices of the points forming one pair.
See Also
inpPairs, linePosn0, linePosn1,
lineVec
Information About Point Pairs
Description
Extract or create a data frame of information about each point pair in an
object inherting from class inpPairs or respPairs. This is
an internal utility function, not intended to be called by package users.
Usage
pairInfo(x)
Arguments
x |
An object inheriting from class |
Details
This data frame differs from respInfo(x) in that it contains
information associated with each pair of points, rather than with
individual points. See the documentation for respPairs for the
standard columns in the pairInfo data frame for those objects.
inpPairs objects don't contain a pairInfo data frame. The
returned data frame will have columns pairType (all NA) and
idx1, idx2 the point indices for each pair (essentially the
transpose of pairIdxs).
Value
Data frame with one row per pair in x.
See Also
'pairs' Method for Plotting 'lsetSegs' Objects
Description
pairs method for lsetSegs objects. Base graphics are used
to plot line segments in a level set, projected onto pairs of input space
dimensions.
Usage
## S3 method for class 'lsetSegs'
pairs(x, dims=NULL, rect=NULL, pt0=NULL, ...)
Arguments
x |
An |
dims |
Numeric or character vector indicating which of the input space dimensions are to be displayed. The plot will have a panel for each pair of the listed dimensions. The default is to use all input space dimensions. |
rect, pt0, ... |
Additional arguments passed to the |
Details
Projection of a point onto the plane spanned by a pair of coordinate axes just amounts to using the point's coordinates for those dimensions. Coordinates for other dimensions are ignored.
Value
NULL, invisibly.
See Also
Examples
# Example with 3-dimensional input space.
Ex <- circuitFailure_3dEx # see '?circuitFailure_3dEx'
bsrch <- Ex$bsrch # list as returned by 'bdrySearch()'
segs <- lsetSegs(bsrch) # 'lsetSegs' object, containing level set segments
pairs(segs, rect=bsrch$rect,
main="95% confidence region, circuit failure example")
Check Validity and Consistency of '*Pairs' Arguments
Description
Check validity and consistency of common arguments to functions creating
*Pairs objects. This is an internal utility function, not intended
to be called by package users.
Usage
pairsetup_args(pts=NULL, pairidxs=NULL, inptol=NULL, pairinfo=NULL)
Arguments
pts |
Matrix containing coordinates of points in input space. NA coordinates are not allowed. |
pairidxs |
Optional two-row matrix. Each column contains the indices in |
inptol |
2-row matrix with tolerance specifications for input space coordinates. |
pairinfo |
Optional data frame with one row per point pair. The following columns are expected, or will be created with NA values if not provided: pairType : Character string describing the nature of the pair. |
Details
This function detects degenerate pairs but does not remove them. The
calling function can use degen to do so.
Value
List with components:
pairidxs |
Two-row integer matrix. Same as the argument if specified, or created if not. Column names, if any, are retained. |
inptol |
Same as the argument. |
pairinfo |
Data frame with one row per pair (column of |
degen |
Logical vector with length equal to the number of pairs. TRUE means the
pair is degenerate, allowing for the tolerances in |
See Also
inpPairs.default, respPairs.respPts use this
function to process their arguments.
Plot Method for 'inpRays' Objects
Description
Plot method for inpRays objects. Base graphics are used to display
the projection of rays onto the plane defined by a pair of input space
dimensions.
Usage
## S3 method for class 'inpRays'
plot(x, y=NULL, dims=1:2, showRect=TRUE, eqAxes=FALSE, rayPar=list(),
add=FALSE, ...)
Arguments
x |
An object inheriting from class |
y |
Ignored. (Only present for compatibility with the |
dims |
Numeric or character vector specifying two input space dimensions. The rays are projected onto the plane spanned by their coordinate axes. |
showRect |
Logical scalar. If TRUE and |
eqAxes |
Logical scalar. If TRUE, equal axes are used for both dimensions. |
rayPar |
Optional list with graphics parameters used to draw the rays. Available
parameters are arguments to |
add |
Logical scalar. If TRUE, the display is added to the current plot rather than starting a new plot. |
... |
Additional arguments passed to |
Details
Rays are shown as arrows extending from their origin to position 1.0 for each ray.
Projection of a point onto the plane spanned by a pair of input space dimensions just amounts to using the point's coordinates for those dimensions. Coordinates for other dimensions are ignored.
Value
NULL, invisibly.
See Also
inpRays, rayOrigin, rayPosn1,
rayRect, graphics::arrows
Examples
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"))
# Rays can be defined by specifying their position 1 points and origin:
pts <- rbind(c(0, 1, 3), c(2, 2, 4), c(5, -1, 2))
orig <- c(0, 1, 2)
rays <- inpRays(pts, origin=orig, spec=fspec)
names(rays) <- paste0("Ray", 1:3)
plot(rays, dims=c("X2", "X3"), eqAxes=TRUE, rayPar=list(col="blue"))
Plot Method for 'inpRect' Objects
Description
Plot method for inpRect objects. Base graphics are used to display
the border of the hyper-rectangle in the plane defined by a pair of input
space dimensions.
Usage
## S3 method for class 'inpRect'
plot(x, y=NULL, dims=1:2, eqAxes=FALSE, showRefPt=NULL, lty=NULL,
lwd=NULL, border=NULL, add=FALSE, ...)
Arguments
x |
An |
y |
Ignored. (Only present for compatibility with the |
dims |
Numeric or character vector specifying two input space dimensions. The
border of |
eqAxes |
Logical scalar. If TRUE, equal axes are used for both dimensions. |
showRefPt |
Logical scalar. If TRUE the reference point of |
lty, lwd, border |
Graphical parameters used to display the border of |
add |
Logical scalar. If TRUE, the display is added to the current plot rather than starting a new plot. |
... |
Additional arguments passed to |
Details
Defaults for display properties depend on add. If add is
FALSE they are showRefPt=TRUE, lty=1, lwd=par("lwd"),
border=par("fg"). If add is TRUE they are showRefPt=FALSE,
lty=2, lwd=par("lwd"), border="lightgray".
Projection of a hyper-rectangle onto the plane spanned by a pair of input space dimensions just amounts to using the its coordinates for those dimensions. Coordinates for other dimensions are ignored.
Value
NULL, invisibly.
See Also
inpRect, rectCorners, rectRefPt
Examples
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"))
rect1 <- inpRect(rbind(c(0, 0, 1), c(1, 2, 4)), spec=fspec)
plot(rect1, dims=2:3)
plot(rect1, dims=2:3, eqAxes=TRUE)
# Add a 'rect' to an existing plot. (Uses different default lty and color)
set.seed(1)
rays1 <- randomRays(25, origin=c(1, 1, 2), spec=fspec)
plot(rays1, dims=c("X2", "X3"), eqAxes=TRUE,
main="Random 3D rays projected to 2D")
plot(rect1, dims=c("X2", "X3"), add=TRUE)
# Note that this is different from including the rectangle in the definition
# of the rays:
set.seed(1)
rays2 <- randomRays(25, origin=c(1, 1, 2), rect=rect1, spec=fspec)
plot(rays2, dims=c("X2", "X3"), eqAxes=TRUE,
main="Random 3D rays with hyper-rect set, projected to 2D")
Plot Method for 'lsetSegs' Objects
Description
Plot method for lsetSegs objects. Base graphics are used to
display the projection of line segments in a level set onto individual
coordinate axes of the input space, or onto the plane defined by a pair of
input dimensions.
Usage
## S3 method for class 'lsetSegs'
plot(x, y=NULL, dims=y, oneD=NULL, showSegs=TRUE, rect=NULL,
pt0=NULL, add=FALSE, ...)
Arguments
x |
An |
y |
Ignored. (Only present for compatibility with the |
dims |
Numeric or character vector specifying the input space dimensions onto
which the projection of the line segments are to be displayed. Must have
length 2 if |
oneD |
Logical scalar. If TRUE, projections onto individual coordinate axes are
displayed. If FALSE, projection onto the plane defined by a single pair
of axes is displayed. The default is FALSE if |
showSegs |
If FALSE only the endpoints of line segments are plotted. If TRUE the segment connecting the endpoints is added as a light gray line. |
rect |
Optional |
pt0 |
Optional vector or 1-row matrix with the coordinates of a point in input
space, to be displayed with the symbol "0". (For example the ray origin
when |
add |
Logical scalar. If TRUE, the display is added to the current plot rather than starting a new plot. |
... |
Additional arguments passed to |
Details
Segment endpoints on the level set boundary are displayed with a blue "*"
symbol. Endpoints on the boundary of the feasible region are displayed
with an orange "x". Endpoints that are in the level set but not on its
boundary are shown with a blue "+" symbol. If showSegs is TRUE,
endpoints of each segment are connected by a solid gray line. If
rect is provided, the projected boundary of the hyper-rectangle is
shown with a dashed gray line.
Projection of a point onto a coordinate axis, or the plane spanned by a pair of coordinate axes, just amounts to using the point's coordinates for that/those dimension(s). Coordinates for other dimensions are ignored.
Value
NULL, invisibly.
See Also
lsetSegs, summary.lsetSegs.
pairs.lsetSegs shows projections onto multiple pairs of axes
in a single plot.
Examples
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
segs <- Ex$segs_checked
rect0 <- Ex$rect0
plot(segs, rect=rect0, main="Segments found along 50 random rays")
# 1D projections
plot(segs, oneD=TRUE, rect=rect0, main="Segments found along 50 random rays")
Plot Profiles of a Response Function along Lines/Rays
Description
Plot method for respProfiles objects. Uses ggplot2
graphics.
Usage
## S3 method for class 'respProfiles'
plot(x, y, groupBy=NULL, wrap=list(ncol=ceiling(sqrt(nprofs))), ...)
Arguments
x |
A |
y |
Ignored. (Only present for compatability with the generic.) |
groupBy |
Optional vector or factor with one element per line or ray in |
wrap |
List that will be passed as arguments to |
... |
Ignored, with a warning. (Only present for compatability with the generic.) |
Details
The x-axis for the plot panels is position along the lines/rays.
(See the definition of position in ?inpRays.) In general any given
position value will represent different Euclidean distances from the line
origin for different lines or rays.
A dashed horizontal line indicates the response threshold defining a level
set, if one was specified in x. Any intersections of a profile
line with the boundary of the level set are marked with a blue plotting
symbol. Plotting symbols are an upward-pointing triangle if response is
increasing along the line at that point, a downward-pointing triangle if
it is decreasing, and a circle if it is flat or the trend is NA. An
orange vertical line and plotting symbol are used for feasible region
boundary intersections found in x.
To show ray profiles in separate panels, set groupBy to have a
distinct value for each ray, such as 1:length(x), or
names(x) if x has ray names.
Value
A ggplot object containing the plot.
See Also
respProfiles, inpLines, inpRays
Examples
# See the examples in '?respProfiles.fnObj'.
Plot Sets of Level Set Segments in Separate Panels
Description
Given a list of lsetSegs objects, plot their projections onto the
same 2-D plane, each in a separate panel. ggplot2 graphics are
used.
Usage
plotSegsList(x, dims, showSegs=TRUE, rect=NULL, ptSize=2,
wrap=list(ncol=ceiling(sqrt(nx)), drop=FALSE))
Arguments
x |
List of |
dims |
Numeric or character vector of length 2, specifying the pair of input space dimensions onto which the line segments will be projected. |
showSegs |
If FALSE only the endpoints of line segments are plotted. If TRUE the segment connecting the endpoints is added as a light gray line. |
rect |
Optional 2-row matrix or |
ptSize |
Size of point plotting symbols. Nominally in millimeters, but in practice displayed sizes are smaller. This size applies to level set boundary points; feasible region boundary points are 0.6 times as large. |
wrap |
List that will be passed as arguments to |
Details
Each lsetSegs object in x is plotted in a separate panel.
Names of components in list x are used to label the panels.
Segment endpoints on the level set boundary are displayed with a blue "*"
symbol. Endpoints on the boundary of the feasible region are displayed
with an orange "x". Endpoints that are in the level set but not on its
boundary are shown with a blue "+" symbol. If showSegs is TRUE,
endpoints of each segment are connected by a solid gray line. If
rect is provided, the projected boundary of the hyper-rectangle is
shown with a dashed gray line.
Value
A ggplot object containing the plot.
See Also
lsetSegs. pairs.lsetSegs shows projections of
a single lsetSegs object onto multiple pairs of dimensions
in a single plot. slicedBdryFromRays and
slicedBdrySearch return lists where each component contains
an lsetSegs object, one per slice; those lists can be
plotted using this function.
Examples
Ex <- circuitFailure_3dEx # see '?circuitFailure_3dEx'
slsrch <- Ex$slsrch # list returned by 'slicedBdrySearch()'
# Number of level set segments found per slice:
slsegs <- lapply(slsrch, lsetSegs) # list of 'lsetSegs' objects
sapply(slsegs, length)
if (use("ggplot2")) { # package 'ggplot2' required
plt <- plotSegsList(slsrch, dims=c("dfrac", "shape"))
print(plt + labs(title="Confidence region sliced by 'scale'"))
}
Convert Positions on Lines or Rays to Point Coordinates
Description
Convert positions on lines or rays to point coordinates.
Usage
posnToCoord(posn, lineidx, lines)
Arguments
posn |
Vector of position values. NA is allowed, and will produce a point with NA coordinates. |
lineidx |
Vector of line or ray numbers (indices into |
lines |
An object inheriting from class |
Details
Lines and rays are defined by pairs of distinct points in input space, as
represented by objects inheriting from class inpLines. The first
point in a pair defines position 0 along the line, and is called the line
origin. The second point defines position 1.0. Positions of other points
on a line are based on linear interpolation or extrapolation from those
points.
Value
A matrix with number of rows equal to the length of posn,
containing point coordinates.
See Also
Examples
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"))
rays <- inpRays(rbind(c(1, 1, 1), c(1, 2, 3)), origin=c(0, 0, 0),
spec=fspec) # two rays
posnToCoord(lineidx=c(1, 1, 1, 2, 2), posn=c(0, 0.5, NA, -0.5, 2),
lines=rays)
Convert Positions on Lines or Rays to Point Coordinates
Description
Convert (position, line number) pairs to a matrix with point coordinates in input space. This is an internal utility function, not intended to be called by package users.
Usage
posn_to_coord2(posn, lineidx, x0, x1)
Arguments
posn |
Vector of positions of points along a line or ray. NA is allowed, and will produce a row of NA coordinates. |
lineidx |
Vector of line or ray numbers (indices into rows of |
x0, x1 |
Matrices with the coordinates of the position 0 ( |
Details
Corresponding rows of x0 and x1 are assumed (but not
checked) to be distinct points, so that the line connecting them is well
defined.
Value
A matrix with number of rows equal to the length of posn,
containing point coordinates. It has the same column names as x0.
See Also
posnToCoord is a user-level version of this function that
works with inpLines and inpRays objects
representing multiple lines.
'print' Method for 'fnSpec' Objects
Description
print method for fnSpec objects. This is an internal
utility method. Package users should call the generic print
function.
Usage
## S3 method for class 'fnSpec'
print(x, ...)
Arguments
x |
An object inheriting from class |
... |
Additional print-related arguments that will be passed to the default print method for matrices. |
Value
x, invisibly.
'print' Method for 'inpLines' and 'inpRays' Objects
Description
print method for inpLines objects (including inpRays
objects). Package users should call the generic print function.
Usage
## S3 method for class 'inpLines'
print(x, vecForm=inherits(x, "inpRays"), includeNames=inherits(x,
"inpRays"), ...)
Arguments
x |
An object inheriting from class |
vecForm |
Logical scalar. If TRUE lines/rays are presented as position 0
points/origin point and direction vectors away from position 0. If FALSE,
they are presented as position 0 points/origin and position 1 points. The
default is TRUE for |
includeNames |
Logical scalar. If TRUE, line/ray names, if any, will be included in the
output. The default is TRUE for |
... |
Additional print-related arguments that will be passed to the default print method for matrices. |
Value
x, invisibly.
See Also
rayOrigin, rayPosn1, rayVec to
extract individual components of inpRays objects.
Examples
fspec <- fnSpec(inpnames=c("a", "b", "c"))
pts <- rbind(c(0, 1, 3), c(2, 2, 4), c(5, -1, 2))
rays <- inpRays(pts, origin=c(0, 1, 2), spec=fspec)
print(rays)
print(rays, vecForm=FALSE)
names(rays) <- paste0("ray", seq_len(length(rays)))
print(rays)
lines <- inpLines(rbind(rayOrigin(rays), pts), spec=fspec,
pairidxs=cbind(c(1, 2), c(1, 3), c(1, 4)))
print(lines)
print(lines, vecForm=TRUE)
'print' Method for Objects from Non-Public 'ptsClass' Classes
Description
print method for objects in non-public classes that inherit from
inpPts. (Public classes have their own methods.) This is an
internal utility method, not intended to be used by package users.
Usage
## S3 method for class 'inpPts'
print(x, inclGrad=FALSE, ...)
Arguments
x |
An object from one of the |
inclGrad |
Logical scalar. If TRUE and |
... |
Additional print-related arguments that will be passed to the default print methods for matrices and data frames. |
Details
Point coordinates in x are printed as a matrix, and the response
function values at those points, if present, are printed as a data frame.
Value
x, invisibly.
'print' Method for 'inpRect' Objects
Description
print method for inpRect objects. This is an internal
utility method. Package users should call the generic function.
Usage
## S3 method for class 'inpRect'
print(x, ...)
Arguments
x |
An |
... |
Additional print-related arguments that will be passed to the default print method for matrices. |
Details
The coordinates of the hyper-rectangles corners and reference point are printed as matrices.
Value
x, invisibly.
See Also
rectCorners, rectRefPt.
rectSize to get the lengths of its sides.
'print' Method for 'respProfiles' and 'lsetSegs' Objects
Description
print method for respProfiles and lsetSegs objects.
Package users should call the generic print function.
Usage
## S3 method for class 'respProfiles'
print(x, inclGrad=FALSE, ...)
Arguments
x |
An object inheriting from class |
inclGrad |
Logical scalar. If TRUE and |
... |
Additional print-related arguments that will be passed to the default print methods for matrices and data frames. |
Details
Point coordinates in x are printed as a matrix, and the response
function values at those points are printed as a data frame. If x
is an lsetSegs object, the two endpoints for each segment are
printed in consecutive rows.
Value
x, invisibly.
Examples
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
segs <- Ex$segs_checked # 'lsetSegs' object
print(segs[1:5])
Print a Summary of an 'lsetSegs' Object
Description
Print a summary of an lsetSegs object. This is an internal utility
method. Package users should call the generic print function.
Usage
## S3 method for class 'summary.lsetSegs'
print(x, ...)
Arguments
x |
An object inheriting from S3 class |
... |
Additional print-related arguments that will be passed to the default print method for matrices (for printing the bounding box). |
Value
x, invisibly.
See Also
Print a Summary of a 'respProfiles' Object
Description
Print a summary of a respProfiles object. This is an internal
utility method. Package users should call the generic print
function.
Usage
## S3 method for class 'summary.respProfiles'
print(x, ...)
Arguments
x |
An object inheriting from S3 class |
... |
Additional print-related arguments that will be passed to the default print method for matrices (for printing the bounding box). |
Value
x, invisibly.
See Also
summary.respProfiles, respProfiles
Print a Summary of a 'respPts' Object
Description
Print a summary of a respPts object. This is an internal method,
not intended to be used by package users.
Usage
## S3 method for class 'summary.respPts'
print(x, ...)
Arguments
x |
An object inheriting from S3 class |
... |
Additional print-related arguments that will be passed to the default print method for matrices. |
Value
x, invisibly.
See Also
Print an Object with Indentation
Description
Wrapper for print that allows printed lines to be indented by a
specified amount or prefixed with a specified string. This is an internal
utility function, not intended to be called by package users.
Usage
print2(x, ..., width=getOption("width"), indent=0)
Arguments
x, ..., width |
Arguments passed to |
indent |
Scalar, the number of spaces to indent each line. Or a character string that will be prefixed to each line. |
Value
x, invisibly
Profile a Response Function at Positions along a Single Line
Description
Evaluate a response function at positions along a single line in input space. Optionally find positions where the profile crosses the boundary of a specified level set or the boundary of the feasible region of the response function. This is an internal utility function, not intended to be called by package users.
Usage
profile_1line(fnobj, x0, x1, initposns, curr_prof=NULL,
lsetthresh=NULL, lineidx=NULL, feasbdry=!is.na(lsetthresh),
derivmethod=derivMethod(fnobj))
Arguments
fnobj |
A |
x0, x1 |
1-row matrices with the coordinates of two distinct (with respect to
tolerance |
initposns |
Vector of positions along the line at which the response function is to be evaluated initially. May have length 0. Must be strictly increasing, and all must be finite. |
curr_prof |
Optional pre- |
lsetthresh |
Response function value that defines a level set of interest. A search
will be made for positions along the line where it crosses the boundary of
the level set. The search will be internal to the range of
|
lineidx |
Optional integer line number, to fill the |
feasbdry |
Logical scalar. If TRUE a search will be made for positions along the
line where it intersects the boundary of the feasible region of the
response function. If level set boundary crossings are requested
( |
derivmethod |
Character string indicating the method to calculate the derivative of the
response function with respect to position along the line, evaluated at
individual points. One of |
Details
This function wraps internal functions make_line_profile_fun,
eval_1line, merge_pre_respProfiles, and bdry_1line.
Value
A pre-respProfiles list with all the components of a
respProfiles object for a single line, except inpLines.
Points will include those provided in curr_prof, those specified by
initposns, and any additional points along the line evaluated
during the search for level set and/or feasible region boundary crossings.
The line column in the respInfo data frame is filled with
the value in argument lineidx.
Points will be sorted by posn.
Project a Set of Points Onto a Set of Lines/Rays
Description
Projections of a set of points onto a set of lines or rays, optionally weighted. Results are returned as line/ray positions. This is an internal utility function, not intended to be called by package users.
Usage
proj_pt_to_line(pts, lineidx=NULL, x0, x1, scale=NULL)
Arguments
pts |
Matrix of point coordinates. Must not contain +/-Inf. |
lineidx |
Optional vector of line or ray numbers (indices into rows of |
x0, x1 |
Matrices with the coordinates of the position 0 ( |
scale |
Optional |
Details
If x0_i and x1_i are the points at positions 0 and 1 on line
i, the position of the projection of point y onto that line
is t(x1_i - x0_i) %*% (y - x0_i) divided by the squared length of
(x1_i -x0_i), t(x1_i - x0_i) %*% (x1_i - x0_i).
When scale is specified, each of the difference vectors (* -
x0_i) is premultiplied by the transformation matrix W (see
?inpScale).
It is an error for x0[i, ] and x1[i, ] to be numerically
equal, since that represents a degenerate line. It is also an error if
the ratio of the length of vector (y - x0[i, ]) or (y - x1[i,
]) to the length of vector (x1[i, ] - x0[i, ]) (after any
weighting) is NaN or infinite. That represents a scaling problem,
where the distance between positions 0 and 1 on a line/ray is too small
relative to the locations of the points that are being projected. By
rejecting those situations, this function guarantees that all returned
projection positions will be finite.
Value
If lineidx is NULL: Numeric matrix with one row per point and one
column per line/ray. Element [i,j] contains the position on line
j of the projection of point i.
If lineidx is specified: Vector of positions of the projection of
each point onto the line specified by the corresponding element of
lineidx.
See Also
posn_to_coord2 to convert positions on lines to point
coordinates. This function is used by box_bdry_from_lines,
pt_on_line2.
Extract a Matrix of Point Coordinates
Description
Extract a matrix containing coordinates of points in input space from an object.
Usage
ptCoord(x, ...)
Arguments
x |
An object containing point coordinates (for example, a |
... |
Additional arguments for specific methods. In particular, when |
Details
This is an S3 generic function. There are methods to handle
inpLines, respProfiles, and lsetSegs objects.
(Package users should call the generic however.)
For a respProfiles object, points are ordered by the line/ray being
profiled, and then by position within each line/ray.
For an inpLines object (which also includes inpRays
objects), there are two points per line/ray, in consecutive rows of the
returned matrix: odd-numbered rows are position 0 points and even-numbered
rows are position 1 points.
For an lsetSegs object, a which argument is available. It
is a character string indicating the form in which points are to be
extracted. "1st" and "2nd" extract just the first or just the second
endpoint of each segment. "both" returns the coordinates of the first
endpoints of all the segments followed by those of the second endpoints.
"paired" (the default) returns coordinates of first and second endpoints
of each segment in consecutive rows (i.e., odd-numbered rows are first
endpoints, even-numbered rows are second endpoints).
For both respProfiles and lsetSegs objects the number and
order of the points matches rows of the data frame returned by
respInfo for the same object and value of which.
Value
Matrix with one row per extracted point. Columns will be named with the input space dimension names.
See Also
respInfo; rayOrigin, rayPosn1
extract coordinates of specific points for rays.
Examples
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
segs <- Ex$segs_checked # 'lsetSegs' object
pts1 <- ptCoord(segs, which="1st") # first endpoint of each segment
pts2 <- ptCoord(segs, which="2nd") # second endpoint of each segment
pts12 <- ptCoord(segs, which="both")
identical(pts12, rbind(pts1, pts2))
# Default is 'which="paired"', endpoints for each segment in consecutive rows
head(ptCoord(segs), 10)
Matrix of Point Coordinates
Description
Extract a matrix containing coordinates of points in input space from an
object inheriting from inpPairs. This is an internal utility
method, not intended to be used by package users.
Usage
## S3 method for class 'inpPairs'
ptCoord(x, which=c("raw", "1st", "2nd", "both", "paired"), ...)
Arguments
x |
Object inheriting from class |
which |
Character string indicating the form in which points are to be extracted.
"raw" (the default except for |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
When which is not "raw", points are extracted using the
pairIdxs component of x. Therefore the same point may
appear multiple times, if it belongs to multiple pairs, or not at all, if
it appears in no pairs.
Value
Matrix with one row per extracted point.
See Also
Matrix of Point Coordinates
Description
Extract a matrix containing coordinates of points in input space from an
inpPts object. This is an internal utility method, not intended to
be used by package users.
Usage
## S3 method for class 'inpPts'
ptCoord(x, ...)
Arguments
x |
Object inheriting from class |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
When x is an inpPairs object and which is not "raw",
points are extracted using the pairIdxs component of x.
Therefore the same point may appear multiple times, if it belongs to
multiple pairs, or not at all, if it appears in no pairs.
Value
Matrix with one row per extracted point.
See Also
Test Whether Points Lie in Specified Slices
Description
Test whether points in input space lie in specified slices, to within a numerical tolerance. This is an internal utility function, not intended to be called by package users.
Usage
pt_in_slice(pts, sliceidx, slicemat, inptol)
Arguments
pts |
Matrix of point coordinates. |
sliceidx |
Vector of slice numbers (indices into rows of |
slicemat |
Matrix of slice specifications. The identity slice (no dimensions with fixed values) is allowed. |
inptol |
2-row matrix with tolerance specifications for input space coordinates. |
Details
A point y is considered to lie in a slice s if its
j-th coordinate y[j] is equal to s[j] (to within a
numerical tolerance based on inptol[, j]), for all j for
which s[j] is not NA. (So an NA value for s[j] matches any
value for y[j].)
This function is similar to sliceMatch, but only tests one slice
per point, rather than identifying all points for each slice.
Value
Logical vector with one element per point. TRUE means the point lies in
the slice specified by the corresponding element of sliceidx, to
within the numerical tolerances specified by inptol.
See Also
sliceMatch, inpTol, pt_on_line2
Test Whether Points Lie on Specified Lines
Description
Test whether points in input space lie on specified lines, to within a numerical tolerance. This is an internal utility function, not intended to be called by package users.
Usage
pt_on_line2(pts, lineidx, x0, x1, inptol)
Arguments
pts |
Matrix of point coordinates. |
lineidx |
Vector of line or ray numbers (indices into rows of |
x0, x1 |
Matrices with the coordinates of the position 0 ( |
inptol |
2-row matrix with tolerance specifications for input space coordinates. |
Details
All comparisons of points allow for a numerical tolerance as specified by
inptol.
A line is degenerate if x0[i, ] and x1[i, ] are tied points.
This function must allow degenerate lines because, if we are working with
d_s-dimensional slices, x0, x1 will be subvectors of
the point pairs defining d-dimensional lines. The subvectors may
be identical even if the full pair points are distinct. In that case this
function returns TRUE for points in pts tied with either x0
or x1, and FALSE otherwise. Attribute projposn will be a
value in the set (0, 0.5, 1).
For non-degenerate lines, testing is based on the fact that a point lies
on a line if it is the same as its projection onto that line. Projection
is done by proj_pt_to_line.
NOTE: Projection is inherently unstable. If position 0 and 1 points are numerically close enough to be considered tied, all projections are reported to be at positions in [0, 1], i.e. essentially those points. However if the 0 and 1 points are even slightly further apart, projection position may be many orders of magnitude larger and the projection point very far from those points.
Value
Logical vector with one element per point. TRUE means the point lies on
the line specified by the corresponding element of lineidx, to
within the numerical tolerances specified by inptol.
The vector will have attribute projposn, a vector with the position
of the point when projected onto its line.
See Also
proj_pt_to_line, tied_endpts. This function
is used to test whether and where lines intersect slices, e.g. in
box_bdry_from_lines.
List the Components of Most Package Classes
Description
Return a list describing the components of each class. This is an internal utility function, not intended to be called by package users.
Usage
ptsClassComp()
Details
Each class is a list with named components, and this function returns the component names for each class. A given component name has the same meaning for all classes that use it. Class B inherits from class A if and only if class B contains all the components of a class A object, plus one or more additional components. (I.e., class B extends class A.)
The documentation for this function also describes the structure of the components.
Package users should not rely on the details of this class structure. Instead they should use user-level accessor functions to extract components of interest.
Value
A named list of character vectors. There is one vector per class, containing the names of the components of the class.
See Also
List the Relationships among Most Package Classes
Description
Return a list describing the relationships among classes for points, lines, line segments, and response function profiles. This is an internal utility function, not intended to be called by package users.
Usage
ptsClassStruc()
Details
All classes inherit from the most basic class, inpPts.
In the list returned by this function, the component named A is the
character vector that will be returned by class(x), if x is
an object of class A.
Going from inp* to resp*: Add *Info data frame(s).
Going from *Pts to *Pairs: Add pairIdxs. Going from
resp* to respProfiles or lsetSegs: Add
inpLines. Going from inpPairs to inpLines: Add
line/ray names.
Package users should not rely on the details of this class structure. Instead they should use user-level methods and accessor functions to work with classes of interest.
Value
A named list of character vectors. There is one vector per class, containing the sequence of classes each class inherits from.
See Also
Helper Function for 'c' Methods for 'ptsClass' Classes
Description
Helper function for c methods for objects in the ptsClass
set of classes. This is an internal utility function, not intended to be
called by package users.
Usage
ptsClass_combine(x, target_class, x_idx=seq_len(length(x)))
Arguments
x |
List, each component an object in one of the |
target_class |
Character string with the name of the leading class for the combined
object. All objects in |
x_idx |
Integer vector with the same length as |
Details
This function works explicitly with list components of objects, rather than using accessor functions.
This function requires strict equality of the fnSpec and
lsetThresh components of all the objects being combined. (In
principle this should not be required for components that are not relevant
to target_class–for example the respTol component for
inp* objects. But it is hard to find a policy for resolving
differences that might not cause problems in downstream use of the
combined object.)
When combining inpRays, all must have the same origin. They do not
have to have the same (or any) associated hyper-rectangle. The combined
object with use the hyper-rectangle, if any, from the first object.
Value
An object of the class specified by target_class.
See Also
Test Points for (Near-)Equality to a Reference Point
Description
Test input space points for (near-)equality to a single reference point. This is an internal utility function, not intended to be called by package users.
Usage
pts_equal_pt(pts, refpt, inptol=NULL)
Arguments
pts |
Matrix or |
refpt |
One-row matrix or |
inptol |
|
Value
Logical vector with length equal to the number of points in pts.
TRUE means a point is equal to refpt to within a tolerance
specified by inptol.
See Also
Generate Rays in Input Space
Description
Generate rays with random directions in input space.
Usage
randomRays(n, spec=NULL, scale=NULL, origin=NULL, rect=NULL,
slice=NULL, warnDegenerate=TRUE)
Arguments
n |
The number of rays to generate. |
spec |
An |
scale |
Optional |
origin |
Vector or 1-row matrix with the coordinates of a single point in input
space. All rays start from this point (i.e., it is position 0 for each
ray). |
rect |
Optional |
slice |
Optional vector or 1-row matrix specifying one slice of input space. (See
|
warnDegenerate |
Integer or logical scalar. When |
Details
Let d denote the number of input space dimensions. Rays are
generated following the same steps as those described in ?axisRays,
with the exception of the initial set of unit vectors. Rather than being
based on coordinate axes, here n vectors are sampled from the
uniform distribution on the surface of the unit hypersphere in d_s
dimensions. (d_s is the number of NA coordinates in slice,
or equal to d if no slice is specified.)
Note that if some sides of rect are much longer than others,
scale should probably be specified to reflect that. Otherwise few
rays are likely to sample the long dimensions of rect. See the
examples. Thus the default is scale=inpScale(rectSize(rect),
spec=spec).
Value
An inpRays object. The origin will be the point specified by
origin. The position 1.0 point for each ray will by default be
distance 1 from the origin, but distances may differ if scale or
rect is specified.
See Also
Examples
oldopt <- lsetPkgOpt(reset=TRUE) # default options
layout(matrix(1:4, nrow=2, byrow=TRUE))
#----- Rays pass through random points on circle centered at (3,2) with
# radius 1:
spec <- fnSpec(inpnames=c("A", "B"))
set.seed(1)
rslt <- randomRays(50, spec=spec, origin=c(3, 2))
plot(rslt, eqAxes=TRUE, main="Random rays, unit length")
# Effect of 'scale':
# Ellipsoid with wider range for A axis relative to B (semi-major and
# semi-minor axis lengths given by sqrt(diag(mat))).
scl <- inpScale(matrix(c(5, 0, 0, 1), nrow=2), spec=spec)
set.seed(1)
rslt <- randomRays(50, origin=c(3, 2), scale=scl)
plot(rslt, eqAxes=TRUE, main="Ray lengths scaled to an ellipse")
# Ellipsoid with wider range for A axis relative to B, and rotated:
scl <- inpScale(matrix(c(5, 2, 2, 1), nrow=2), spec=spec)
set.seed(1)
rslt <- randomRays(50, origin=c(3, 2), scale=scl)
plot(rslt, eqAxes=TRUE, main="Rays scaled and rotated")
# ... adjust lengths to put position 1.0 on the boundary of a rectangle:
rect <- inpRect(rbind(c(1, 1), c(5, 2.5)), spec=spec)
set.seed(1)
rslt <- randomRays(50, origin=c(3, 2), scale=scl, rect=rect)
plot(rslt, eqAxes=TRUE, main="Ray position 1 on a 'rect' boundary")
#-- When the sides of 'rect' have very different lengths, 'scale' makes
# a big difference.
layout(matrix(c(1:3, 0), nrow=2, byrow=TRUE))
# To highlight the effect, create a long, narrow rect, and use an off-center
# 'origin'.
corners <- rbind(c(0.5, 3), c(5.5, 3.5))
rect <- inpRect(corners, spec=spec)
# Default for 'scale' adjusts for the side lengths, so rays fill 'rect':
set.seed(1)
rslt <- randomRays(50, origin=c(1, 3.25), rect=rect)
plot(rslt, eqAxes=FALSE, main="Default 'scale' adjusts for 'rect' sides")
# If we intentionally ignore differences in side lengths, rays may be sparse
# in the long directions:
set.seed(1)
rslt <- randomRays(50, origin=c(1, 3.25), rect=rect,
scale=inpScale(spec=spec))
plot(rslt, eqAxes=FALSE, main="No adjustment for 'rect' sides")
#-- When 'origin' is itself on the boundary of 'rect', direction vectors
# that point outside 'rect' and lead to degenerate rays are instead reversed.
set.seed(1)
rslt <- randomRays(50, origin=c(2, 3.5), rect=rect)
plot(rslt, eqAxes=FALSE, main="Ray origin on boundary of 'rect'")
layout(matrix(1))
lsetPkgOpt(oldopt) # restore starting options
Randomly Rotate a Set of Points Around the Origin
Description
Randomly rotate a set of points around the origin. This is an internal utility function, not intended to be called by package users.
Usage
random_rotate(x)
Arguments
x |
Matrix, each row containing the coordinates of one point. |
Value
Matrix with the same shape as x, containing coordinates of the
rotated points.
Range of a Set of Input Space Points along Coordinate Axes
Description
Find the range (minimum and maximum value along each input space dimension) of a set of points in input space. This is an internal utility method, not intended to be called by package users.
Usage
## S3 method for class 'inpPts'
range(..., which=c("coordinates"), na.rm=FALSE)
Arguments
... |
One or more objects inheriting from class |
which |
Character string. The only valid value is the default |
na.rm |
Logical scalar, indicating if NA's should be omitted when calculating ranges. |
Details
For objects inheriting from inpPairs, representing lines/point
pairs, the range is calculated only from those points that actually belong
to pairs (i.e., from ptCoord(x, which="paired") rather than
ptCoord(x, which="raw")).
If all the objects in ... collectively have no points (empty
objects), the range for each dimension will be c(Inf, -Inf) (in
that order), following the convention of base::range. Warnings
will also be generated.
Value
2 x d matrix, where d is the dimension of the input space.
Column i contains the the minimum and maximum value spanned by the
points along the i-th coordinate axis.
See Also
inpPts. range.respPts also allows calculating
the range of response function values.
Range of Point Coordinates or Response Function Values
Description
Find the range of point coordinates or response function values in objects
inheriting from respPts. This is an internal utility method, not
intended to be used by package users.
Usage
## S3 method for class 'respPts'
range(..., which, na.rm=FALSE)
Arguments
... |
One or more objects inheriting from class |
which |
Character string, either |
na.rm |
Logical scalar, indicating if NA's should be omitted when calculating ranges. |
Value
If which is coordinates, a 2 x d matrix, where
d is the dimension of the input space. Column i contains
the the minimum and maximum value spanned by the points along the
i-th coordinate axis.
If which is response, a two-element vector with the minumum
and maximum response function value.
If all the objects in ... collectively have no points (empty
objects), the range for each dimension and for the response will be
c(Inf, -Inf) (in that order), following the convention of
base::range. Warnings will also be generated.
See Also
Hyper-Rectangle Faces Intersected by a Set of Rays
Description
When an inpRays object has an associated hyper-rectangle, this
function returns the face(s) of the rectangle that each ray intersects.
This is an internal utility function, not intended to be called by package
users.
Usage
rayFace(x, onlyOneFace=FALSE)
Arguments
x |
An |
onlyOneFace |
Logical scalar. A ray may intersect the hyper-rectangle boundary at more
than one boundary plane (i.e., at an edge or corner). If
|
Details
A hyper-rectangle in d dimensions has 2*d faces, defined by
the lower and upper limits for each of the dimensions. Since the ray
origin is required to belong to the rectangle, every ray will intersect at
least one face; if it intersects the rectangle boundary at an edge or
corner it is considered to intersect each of the involved faces. In the
latter case the returned data frame will have a row for each intersected
face, unless onlyOneFace is TRUE.
Value
NULL if rays in x have no associated hyper-rectangle. Otherwise a
data frame with columns rayidx (indexing rays in x) and
face (a factor with one level per face of the hyper-rectangle,
indicating which face(s) the hyper-rectangle a ray intersects). Level
names for the factor are formed from the input space dimension names
followed by ".lower" or ".upper".
See Also
Coordinates of the Origin of a Set of Rays in Input Space
Description
Extract the coordinates of the origin from an inpRays object. The
origin is the point that defines position 0 along each ray.
Usage
rayOrigin(x)
Arguments
x |
An |
Value
One-row matrix with the coordinates of the ray origin.
See Also
inpRays, rayPosn1, rayVec,
rayRect
Examples
# See the examples in '?inpRays'
Coordinates of the Position 1 Points of a Set of Rays
Description
Extract the coordinates of the points that define position 1 for a set of
rays in input space, from an inpRays object.
Usage
rayPosn1(x)
Arguments
x |
An |
Details
inpRays objects do not allow degenerate rays, so rayPosn1(x)
will always be different from rayOrigin(x).
Value
Matrix with one row per ray. Row names will be the ray names, if any.
See Also
inpRays, rayOrigin, rayVec,
rayRect
Examples
# See the examples in '?inpRays'
Hyper-Rectangle Associated with a Set of Rays
Description
Extract the hyper-rectangle in input space associated with an
inpRays object.
Usage
rayRect(x)
Arguments
x |
An |
Value
An inpRect object, or NULL if no hyper-rectangle is associated with
x. When not NULL, the ray origin rayOrigin(x) will belong
to the hyper-rectangle, and position 1 for each ray (rayPosn1(x))
will lie on its boundary.
See Also
inpRays, rayOrigin, rayVec,
rayPosn1, inpRect
Examples
# See the examples in '?inpRays'
Ray Direction Vectors from an 'inpRays' Object
Description
Extract the vectors that define ray directions from an inpRays
object. The vectors point away from the ray origin. They are simply the
differences between position 1 points and the ray origin, and are not
normalized.
Usage
rayVec(x)
Arguments
x |
An |
Value
A matrix with one row per ray. Row names will be the ray names, if any.
See Also
Examples
# See the examples in '?inpRays'
Check Validity and Consistency of Ray Function Arguments
Description
Check validity and consistency of common arguments to functions creating rays. This is an internal utility function, not intended to be called by package users.
Usage
raysetup_args(spec=NULL, scale=NULL, origin=NULL, rect=NULL,
slice=NULL)
Arguments
spec |
|
scale |
Optional |
origin |
Vector or 1-row matrix or one-point |
rect |
Optional |
slice |
Optional vector or 1-row matrix specifying one slice of input space. All
the generated rays will lie in the slice. If specified it must intersect
|
Value
List with components matching the arguments, possibly standardized:
spec will be an fnSpec object. If slice is not NULL,
it will always be a 1-row matrix. origin will always be a 1-row
matrix. origin may be slightly modified so that any coordinates
fixed by slice will exactly match those in slice. If
rect is not NULL, and origin is slightly (within a numerical
tolerance) outside it, rect will be adjusted so that origin
is exactly on its boundary. (Thus rect will strictly (without a
numerical tolerance) contain origin, which will strictly belong to
slice, and slice and rect will intersect.) The
reference point of rect will be set to origin. If not NULL,
scale will be an inpScale object, modified so that the
associated transformations preserve point membership in the specified
slice.
See Also
axisRays, randomRays,
inpRays.default, bdrySearch use this function
to process their arguments.
Transform Generic Direction Vectors to Rays in Input Space
Description
Create a set of rays (inpRays object) in a d-dimensional
input space (specified by spec), from a set of direction vectors in
a generic, isotropic, d_s-dimensional space. The transformation
uses scale, origin, rect, and slice, which are
assumed to be standardized and checked (see raysetup_args). This
is an internal utility function, not intended to be called by package
users.
Usage
raysetup_vecs(vecs_s, spec, scale=NULL, origin=NULL, rect=NULL,
slice=NULL, tryReverse, warnDegenerate=TRUE)
Arguments
vecs_s |
Matrix of direction vectors in a generic, isotropic,
|
spec |
|
scale |
Optional |
origin |
One-row matrix with the coordinates to use for the ray origin. It must
belong to |
rect |
Optional |
slice |
Optional 1-row matrix specifying one |
tryReverse |
Logical scalar. If TRUE and a direction vector leads to a degenerate ray, the negative of the direction vector will be tried instead. (It may also fail.) |
warnDegenerate |
Integer or logical scalar. If 1 or TRUE (the default), a warning will be
raised if any rays created from |
Value
List with components:
degen |
Logical vector with one element per vector in |
reversed |
Logical vector with one element per vector in |
rays |
An |
See Also
raysetup_args prepares arguments to use when calling this
function. inpRays.default, axisRays,
randomRays, bdrySearch use this function to
generate rays from direction vectors.
Specialized Version of 'rbind' for Data Frames
Description
Specialized version of rbind for data frames. The main difference
from rbind.data.frame is that the data frames can have different
sets of columns: The default is that the combined data frame has the union
of all the columns in the individual data frames, with NA values inserted
for observations from data frames missing a given column. This is an
internal utility function, not intended to be called by package users.
Usage
rbind_dataframe(x, maxCols=NULL, ...)
Arguments
x |
List of data frames to be combined. |
maxCols |
Optional character vector of column names. If specified, any columns not listed will be dropped from the combined data frame. |
... |
Additional arguments passed to the |
Value
A data frame.
Coordinates of the Corner Points of a Hyper-Rectangle
Description
Extract the coordinates of the lower and upper corners of a
hyper-rectangle in input space, from an inpRect object.
Usage
rectCorners(x)
Arguments
x |
An |
Value
Two-row matrix with the coordinates of the lower and upper corners of the hyper-rectangle.
See Also
Examples
# See examples '?inpRect'
Coordinates of the Reference Point of a Hyper-Rectangle
Description
Extract the coordinates of the reference point of a hyper-rectangle in
input space, from an inpRect object.
Usage
rectRefPt(x)
Arguments
x |
An |
Value
One-row matrix with the coordinates of the reference point for
hyper-rectangle x. The reference point is an arbitrary point in
the hyper-rectangle, defined when an inpRect object is created or
modified.
See Also
inpRect, rectCorners, rectSize
Examples
# See examples '?inpRect'
Lengths of the Sides of a Hyper-Rectangle
Description
The lengths of the sides of a hyper-rectangle in input space, from an
inpRect object.
Usage
rectSize(x)
Arguments
x |
An |
Value
Vector containing the lengths of the sides of the hyper-rectangle.
See Also
inpRect, rectCorners, rectRefPt
Examples
# See examples '?inpRect'
Response Function Values at Input Points
Description
Evaluate a response function at a set of points, or extract previous evaluations from another object. The result is a data frame with response function values and related information for each point.
Usage
respInfo(x, ..., inclGrad=FALSE)
Arguments
x |
Matrix of points at which the response function is to be evaluated, or an
object from which existing response function values will be extracted (for
example a |
... |
Additional arguments for specific methods. |
inclGrad |
Logical scalar. If TRUE and the response function supports gradient calculations, gradient vectors will be included with the return value. |
Details
This is an S3 generic function. In addition to the default method when
x is a matrix of evaluation points, there are methods to extract
response values from respProfiles and lsetSegs objects.
(Package users should call the generic however.)
See ?respInfo.default for information about arguments used when
evaluating the response function at the points in matrix x.
When extracting response values from a respProfiles object, points
are ordered by the line/ray being profiled, and then by position within
each line/ray.
For an lsetSegs object, a which argument is available. It
is a character string indicating the form in which points are to be
extracted. "1st" and "2nd" extract responses for just the first or just
the second endpoint of each segment. "both" returns responses at the
first endpoints of all the segments, followed by those at the second
endpoints. "paired" (the default) returns responses at first and second
endpoints of each segment in consecutive rows (i.e., odd-numbered rows are
for first endpoints, even-numbered rows are second endpoints).
For both respProfiles and lsetSegs objects the number and
order of the points matches rows of the matrix returned by ptCoord
for the same object, and the same which value.
Membership in the level set. A point is considered to belong to the
specified level set if its response function value is not NA and is
greater than or equal to lsetthresh - atol, where the absolute
tolerance atol is calculated as absTol(lsetthresh,
tol=respTol(fnobj)).
Value
Data frame with one row per evaluation point. Columns will include:
resp |
Value of the response function at the point. NA for infeasible points. |
feas |
Logical, TRUE if the point is in the feasible region of input space for
the response function. FALSE if and only if |
lset |
Logical. For feasible points, TRUE if the point belongs to the level set (with allowance for a numerical tolerance, see DETAILS); FALSE if it does not; and NA if no threshold has been specified. Always FALSE for infeasible points. |
Other columns may be present in the data frame, depending on the class of
x. In particular, for respProfiles and lsetSegs
objects there will be columns:
line |
Integer index of the line or ray along which the point lies. |
posn |
Position of the point along the line/ray. |
feasbdry |
Logical, TRUE if the point has been identified as one where the line/ray
crosses the boundary of the feasible region. FALSE means the point
is not known to be a boundary crossing along the line/ray, or that
it is not feasible. (The feasible region is assumed to be a closed set,
so |
lsetbdry |
Logical. TRUE if the point has been identified as one where the response
function along the line/ray crosses from at or above the threshold (minus
a tolerance) to below, or vice versa. FALSE means the point is not
known to be a threshold crossing along the line/ray, or that it is
not in the level set. (Level sets are assumed to be closed, so
|
deriv |
Derivative of the response function with respect to position along the line/ray, evaluated at the point. May be NA. |
trend |
Character string categorizing the local trend in response in the direction of the line/ray: "increasing", "decreasing", or "flat". May be NA. |
lsetSegs objects will have an additional column:
lsetcens |
Logical indicating whether the level set appears to extend beyond this
point in the direction of the line/ray containing the segment. Defined as
|
In practical terms the level set of a response function is the set of
feasible points for which response is greater than or equal to a
threshold. Therefore boundary points of the feasible region should also
be considered boundary points of the level set, provided response is at or
above the threshold. However the lsetbdry column of the returned
data frame uses a narrower definition: it is TRUE only if the point is
known to represent a transition of response values across the
threshold. So the practical definition of a level set boundary point is
actually lsetbdry | (lset & feasbdry), which is just
!lsetcens.
If inclGrad is TRUE, the returned data frame will have an attribute
gradient. This is a matrix of gradient vectors for the response
function at the evaluation points (one gradient vector per row). It is an
error to request calculation of gradient values if the response
function does not support them. However if x is an existing object
from which information is being extracted and it does not contain gradient
information, the gradient attribute will be a matrix of NA values.
See Also
respInfo.default, ptCoord,
lsetThresh
Examples
# Define a response function and evaluate it at a set of points.
respf <- function(x, inclGrad=FALSE) {
resp <- x[, "X1"] + x[, "X2"]^2 + x[, "X3"]^3
if (inclGrad) {
grad <- cbind(1, 2*x[, "X2"], 3*x[, "X3"]^2)
structure(resp, gradient=grad)
} else resp
}
fobj <- fnObj(c("X1", "X2", "X3"), respfn=respf, hasgrad=TRUE)
pts <- rbind(c(0, 1, 3), c(2, 2, 4), c(5, -1, 2)) # three input space points
respInfo(pts, fnobj=fobj, lsetthresh=28) # default is not to calc gradients
resp <- respInfo(pts, fnobj=fobj, lsetthresh=28, inclGrad=TRUE)
attr(resp, "gradient")
# Extract response function values from an existing object.
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
segs <- Ex$segs_checked # 'lsetSegs' object
resp1 <- respInfo(segs, which="1st") # first endpoint of each segment
resp2 <- respInfo(segs, which="2nd") # second endpoint of each segment
resp12 <- respInfo(segs, which="both")
identical(resp12, rbind(resp1, resp2))
# Default is 'which="paired"', endpoints for each segment in consecutive rows
head(respInfo(segs), 10)
Response Function Values at Input Points
Description
Evaluate a response function at a set of points in input space, returning
a data frame with response function values and related information.
Package users should call the generic respInfo function.
Usage
## Default S3 method:
respInfo(x, fnobj, lsetthresh=NA_real_, ..., inclGrad=FALSE)
Arguments
x |
Matrix or data frame, each row containing the coordinates of one point in input space. NA values are not allowed. A vector will be treated as a one-row matrix. |
fnobj |
|
lsetthresh |
Scalar, the value of the response function that defines the level set of interest. NA (the default) means no level set is specified. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
inclGrad |
Logical scalar, whether to also calculate gradients at the input points.
Must be FALSE (the default) if the response function in |
Value
Data frame with one row per point. See the documentation for the generic
function for details. If inclGrad is TRUE, the data frame will
have an attribute gradient, a matrix with the same shape as
x containing the gradient vector of the response function at each
point.
See Also
Examples
# Define a response function and evaluate it at a set of points.
respf <- function(x, inclGrad=FALSE) {
resp <- x[, "X1"] + x[, "X2"]^2 + x[, "X3"]^3
if (inclGrad) {
grad <- cbind(1, 2*x[, "X2"], 3*x[, "X3"]^2)
structure(resp, gradient=grad)
} else resp
}
fobj <- fnObj(c("X1", "X2", "X3"), respfn=respf, hasgrad=TRUE)
pts <- rbind(c(0, 1, 3), c(2, 2, 4), c(5, -1, 2)) # three input space points
respInfo(pts, fnobj=fobj, lsetthresh=28) # default is not to calc gradients
resp <- respInfo(pts, fnobj=fobj, lsetthresh=28, inclGrad=TRUE)
attr(resp, "gradient")
Response Function Values at Input Points
Description
Extract a data frame with response function values and related information
from an object inheriting from respPairs. This is an internal
utility method, not intended to be used by package users.
Usage
## S3 method for class 'respPairs'
respInfo(x, which=c("raw", "1st", "2nd", "both", "paired"), ...,
inclGrad=FALSE)
Arguments
x |
Object inheriting from class |
which |
Character string indicating the form in which response values are to be
extracted. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
inclGrad |
Logical scalar. If TRUE, gradient information will be included in the return value. |
Details
respPairs objects consist of pairs of input space points and
response function values at those points. When which is not "raw",
response values are extracted using the pairIdxs component of
x. Therefore response the same point may appear multiple times, if
the point belongs to multiple pairs, or not at all, if it appears in no
pairs.
Value
Data frame with one row per point. If inclGrad is TRUE, it will
have a gradient attribute. See the generic for more details.
See Also
Response Function Values at Input Points
Description
Extract a data frame with response function values and related information
from a respPts object. This is an internal utility method, not
intended to be used by package users.
Usage
## S3 method for class 'respPts'
respInfo(x, ..., inclGrad=FALSE)
Arguments
x |
Object inheriting from class |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
inclGrad |
Logical scalar. If TRUE, gradient information extracted from |
Value
Data frame with one row per point. If inclGrad is TRUE, it will
have a gradient attribute. See the generic for more details.
See Also
Point Pairs and their Response Function Values
Description
Generic function to create a respPairs object, or to extract one
from another object. respPairs objects contain response function
values at defined pairs of points in input space. This is an internal
utility class, not intended to be used or seen by package users.
Usage
respPairs(x, ...)
Arguments
x |
Object containing information from which a |
... |
Additional arguments for specific methods. |
Details
respPairs extends both respPts objects (by defining point
*pairs*), and inpPairs objects (by including response information
at pair points and information about the pairs themselves). The class is
used internally as a bridge to lsetSegs objects, but is probably
not interesting at the package user level.
A respPairs object is essentially a respPts object plus a
two-row matrix pairIdxs that contains the indices of the points
belonging to each pair, and a data frame pairInfo. A given point
may belong to more than one pair (i.e., the same index may appear more
than once in pairIdxs). And a given point may belong to no pair
(i.e., its index may not occur in pairIdxs at all; such points may
be removed by indexing the object with drop=TRUE).
Degenerate pairs, where both points in a pair are (to within a numerical
tolerance) equal, are not allowed. Therefore, like inpPairs
objects, respPairs objects define lines in input space.
The data frame pairInfo has one row per pair. The data
frame may be extracted with the pairInfo() function. It includes
columns: pairType : Character string describing the nature of the pair.
May be NA.
Value
An object with S3 classes c("respPairs", "inpPairs", "respPts",
"inpPts").
See Also
respPts, inpPairs, pairIdxs,
pairInfo
Point Pairs and their Response Function Values
Description
Create an empty respPairs object from just a response function
specification (fnSpec object). This is an internal utility method,
not intended to be called by package users.
Usage
## S3 method for class 'fnSpec'
respPairs(x, lsetthresh=NA_real_, inclGrad=FALSE,
respInfoTemplate=NULL, pairInfoTemplate=NULL, ...)
Arguments
x |
A |
lsetthresh, inclGrad, respInfoTemplate |
Optional arguments passed to the |
pairInfoTemplate |
Optional data frame with the columns to be included in |
Value
An object with S3 class respPairs. See the documentation for the
generic function for details.
Point Pairs and their Response Function Values
Description
Create a respPairs object by evaluating a response function at a
set of point pairs in input space. This is an internal utility method,
not intended to be called by package users.
Usage
## S3 method for class 'inpPairs'
respPairs(x, fnobj, lsetthresh=NA_real_, inclGrad=FALSE,
pairinfo=NULL, ...)
Arguments
x |
|
fnobj, lsetthresh, inclGrad |
Passed as arguments to |
pairinfo |
Data frame with one row per pair in |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class respPairs. See the documentation for the
generic function for details.
Point Pairs and their Response Function Values
Description
Extract a respPairs object from an object that inherits from that
class. This is an internal utility method, not intended to be called by
package users.
Usage
## S3 method for class 'respPairs'
respPairs(x, strictInfoCols=FALSE, ...)
Arguments
x |
A |
strictInfoCols |
Logical scalar. If TRUE, any columns in the |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class respPairs. See the documentation for the
generic function for details.
Point Pairs and their Response Function Values
Description
Create a respPairs object from a respPts object, by adding
information about point pairs. This is an internal utility method, not
intended to be called by package users.
Usage
## S3 method for class 'respPts'
respPairs(x, pairidxs=NULL, pairinfo=NULL, warnDegenerate=TRUE, ...)
Arguments
x |
An object inheriting from |
pairidxs |
Two-row matrix. Each column contains the indices in |
pairinfo |
Data frame with one row per point pair. The following columns are expected, or will be created with NA values if not provided: pairType : Character string describing the nature of the pair. |
warnDegenerate |
Integer or logical scalar. If 1 or TRUE (the default), a warning will be raised if any pairs are dropped because the two points are equal, to within a numerical tolerance. If 0 or FALSE, degenerate pairs are dropped silently. If 2, degenerate pairs will be treated as an error. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class respPairs. See the documentation for the
generic function for details.
Profiles of a Response Function along Lines or Rays
Description
Create a respProfiles object, containing response function values
evaluated at positions along a set of 1-dimensional lines or rays in input
space.
Usage
respProfiles(x, ...)
Arguments
x |
|
... |
Additional arguments for specific methods. |
Details
This is an S3 generic function, but the only user-level method is for
fnObj objects. See ?respProfiles.fnObj for additional
arguments.
Each point and its response function value in the respProfiles
object x is associated with a line or ray, included in an
inpLines or inpRays object within x. Use
inpLines(x) or inpRays(x) to extract those lines/rays.
Points are identified by their position on the associated line. Positions
are relative to the two points that define positions 0 and 1 for that
line/ray: the position of any other point on it is calculated by linear
interpolation or extrapolation from those two points. (See
?inpLines for more details.) Note that the Euclidean distance
between position 0 and position 1 may differ between lines, so a given
difference in positions may represent different Euclidean distances on
different lines.
Function respInfo() will extract information about individual
points from a respProfiles object, as a data frame. Coordinates
for the points can be extracted with the ptCoord() function.
There are length, [, names, c, print,
summary, and plot methods for respProfiles objects.
length returns the number of lines/rays profiled, [ extracts
entire line/ray profiles (not individual points), and names
extracts the names of the lines/rays that were profiled. If a level set
threshold was specified when profiles were created, lsetSegs() will
extract segments of lines/rays that lie within the level set.
Value
An object with S3 class respProfiles. It will contain one profile
for each line/ray.
See Also
inpLines, inpRays,
plot.respProfiles, summary.respProfiles,
respInfo, ptCoord
Examples
# See examples in '?respProfiles.fnObj'
Profiles of a Response Function along Lines or Rays
Description
Evaluate a response function at positions along a set of 1-dimensional lines or rays in input space. For each line optionally find positions where it crosses the boundary of a specified level set or the boundary of the feasible region of the response function.
Usage
## S3 method for class 'fnObj'
respProfiles(x, lines, rays=NULL, posns, lsetthresh=NA_real_,
feasbdrySrch=!is.na(lsetthresh), ...)
Arguments
x |
|
lines |
|
rays |
Alternative to |
posns |
Vector of positions along each line/ray at which the response function is to be evaluated. All must be finite. See DETAILS. |
lsetthresh |
Optional response function value that defines a level set of interest. A
search will be made for positions along each line where it crosses the
boundary of the level set. The search will be internal to the range of
|
feasbdrySrch |
Logical scalar. If TRUE a search will be made for positions along each
line where it intersects the boundary of the feasible region of the
response function. The search will be internal to the range of
|
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
Finding level set boundary crossings along a line/ray relies on finding
pairs of positions such that one position has a response greater than or
equal to lsetthresh and the other has a response less than
lsetthresh. Similarly, finding feasible region boundary
intersections relies on finding pairs of positions such that one position
is feasible and the other is not. Therefore the ability of this function
to find level set or feasible region boundary intersections depends in
part on a suitably wide and dense set of posns. See
?bdryFromRays for more details about finding level set and feasible
region boundary intersections.
Value
An object with S3 class respProfiles. See the documentation for
the generic for more details.
See Also
fnObj, inpLines, inpRays,
bdryFromRays
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
#----- 1D example.
respf <- function(x, ...) { x*cos(x) }
xx <- seq(-3, 10, by=0.25)
plot(xx, respf(xx), type="l")
abline(h=0.2, lty=2)
fobj <- fnObj(c("X1"), respfn=respf)
ray1 <- inpRays(c(1), spec=fobj) # unit vector
prof <- respProfiles(fobj, lines=ray1, posns=seq(-3, 10), lsetthresh=0.2)
# Methods for 'respProfiles' objects:
length(prof) # 1, the number of profiled lines/rays
summary(prof)
if (use("ggplot2")) { # plot method requires 'ggplot2'
print(plot(prof))
}
# Extract and show level set segments.
lssegs <- lsetSegs(prof)
summary(lssegs)
plot(lssegs)
# 3 segments. Note that the left endpoint of the lowest segment is
# marked as censored, because the level set extends further to the
# left, outside the range of 'posns'.
#----- Multimodal example in 2D (surface with two elliptical contours).
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
fobj <- Ex$fobj
# Calculate ray profiles in four standard directions.
rays1 <- axisRays(fobj, degree=2)
prof1 <- respProfiles(fobj, rays=rays1, posns=seq(-8, 15), lsetthresh=-40)
summary(prof1) # 77 of 101 profiled points are in the feasible region,
# including 3 on its boundary. 48 of the feasible points
# lie in the level set, including 8 on its boundary.
if (use("ggplot2")) {
print(plot(prof1)) # Default is all ray profiles in one panel
print(plot(prof1, groupBy=names(prof1))) # each ray in a separate panel
# Note that no points with X1 < 0 are evaluated (not in the feasible
# region).
}
# Extract and show level set segments.
lssegs <- lsetSegs(prof1)
summary(lssegs) # 6 segments: two rays (1st and 4th) have one segment,
# two rays (2nd and 3rd) have two segments.
plot(lssegs) # One segment endpoint is marked as censored: the segment
# does not extend far enough in that direction to reach
# the level set boundary.
# Rather than rays (with a single, shared origin) one can also profile
# along arbitrary lines.
# Position 0, 1 points for three lines:
coords0 <- rbind(c(0, 4), c(8, 7), c(6, 2))
coords1 <- rbind(c(7, 9), c(4, -2), c(8, 2))
lines <- inpLines(x=coords1, x0=coords0, spec=fobj)
names(lines) <- c("(X1,X2) = (0,4) + posn*(7, 5)",
"(X1,X2) = (8,7) + posn*(-4,-9)",
"(X1,X2) = (6,2) + posn*(2,0)")
prof2 <- respProfiles(fobj, lines=lines, posns=(-10:10)/10,
lsetthresh=-40)
if (use("ggplot2")) {
print(plot(prof2, groupBy=names(prof2))) # each ray in a separate panel
}
lsetPkgOpt(oldopt) # restore settings
Profiles of a Response Function along Lines or Rays
Description
Extract a respProfiles object from an lsetSegs object. The
profile for a given line/ray will consist of the endpoints of the level
set segments that lie on it, but the endpoint pairing information will be
lost. (On the other hand, the resulting object can be indexed by
line/ray, rather than by segment/endpoint pair.) This is an internal
utility method, not intended to be used by package users.
Usage
## S3 method for class 'lsetSegs'
respProfiles(x, ...)
Arguments
x |
|
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class respProfiles.
See Also
Points in Input Space and their Response Function Values
Description
Generic function to create a respPts object, or to extract one from
another object. respPts objects contain coordinates of points in
input space and (at a minimum) response function values and feasibility at
those points. Optionally the object may include a response function value
that defines a level set of interest, and whether each point belongs to
that level set. This is an internal utility class, not visible to package
users.
Usage
respPts(x, ...)
Arguments
x |
Object containing information from which a |
... |
Additional arguments for specific methods. |
Details
respPts objects contain coordinates of points in input space (which
can be extracted with the ptCoord() function), and information
about the response function evaluated at each of those points (extracted
with the respInfo() function).
NA is not allowed for point coordinates.
If the response function calculates gradients, those may be extracted
using respInfo(, inclGrad=TRUE). It returns a data frame with
matrix attribute with the same dimensions as ptCoord(). Each row
contains the gradient vector of the response function, evaluated at the
corresponding input point.
fnSpec() extracts the specifications of the input space and
response function, and lsetThresh() extracts the level set
threshold value.
respPts objects have a special subscripting method ([) that
only accepts a single index vector, allowing selection of points.
length() returns the number of points in the object. c()
can be used to combine respPts objects, provided they have the same
input space and response function. Other methods available for
respPts objects are print and summary; see their
documentation for details.
Value
An object with S3 classes c("respPts", "inpPts").
See Also
fnObj, fnSpec, ptCoord,
respInfo
Points in Input Space and their Response Function Values
Description
Assemble a respPts object manually from its individual components.
This is an internal utility method, not intended to be called by package
users.
Usage
## S3 method for class 'data.frame'
respPts(x, spec, ptcoord, respgrad=attr(x, "gradient"),
lsetthresh=NA_real_, checkArg=TRUE, ...)
Arguments
x |
A data frame with one row per point, containing (at least) the following
columns: |
spec |
|
ptcoord |
Matrix or |
respgrad |
Optional matrix with same number of rows as |
lsetthresh |
Scalar, the value of the response function that defines the level set of interest. NA (the default) means no level set is specified. |
checkArg |
Logical scalar. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
This method assembles a respPts object from previously calculated
response function values.
An existing lset column in x will be overridden by the level
set specification implied by arguments spec and lsetthresh.
No data frame columns other than resp, feas and lset
are created or checked. Including columns from other classes may result
in invalid objects.
Value
An object with S3 class respPts. See the documentation for the
generic function for details.
Points in Input Space and their Response Function Values
Description
Create a respPts object by evaluating a response function at a set
of points in input space. This is an internal method, not intended to be
called by package users.
Usage
## Default S3 method:
respPts(x, fnobj, lsetthresh=NA_real_, inclGrad=FALSE, ...)
Arguments
x |
Matrix, each row containing the coordinates of one point in input space.
NA values are not allowed. A vector will be treated as a one-row matrix.
May also be an |
fnobj |
|
lsetthresh |
Scalar, the value of the response function that defines the level set of interest. NA (the default) means no level set is specified. |
inclGrad |
Logical scalar. If TRUE and if the response function supports gradient
calculations, the gradient at each input point will also be calculated.
If |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
If the response function value is NA for any point that fnobj
claims is feasible, information column feas will be changed to
FALSE for that point, with a warning.
A point is considered to belong to a specified level set if it is feasible
and its response function value is not NA and is greater than or equal to
lsetthresh - atolThresh, where the tolerance atolThresh is
calculated as absTol(lsetthresh, tol=respTol(fnobj)).
Value
An object with S3 class respPts. See the documentation for the
generic function for details.
Points in Input Space and their Response Function Values
Description
Create an empty respPts object from just a response function
specification (fnSpec object). This is an internal utility method,
not intended to be used by package users.
Usage
## S3 method for class 'fnSpec'
respPts(x, lsetthresh=NA_real_, inclGrad=FALSE,
respInfoTemplate=NULL, ...)
Arguments
x |
|
lsetthresh |
Scalar, the value of the response function that defines the level set of interest. NA (the default) means no level set is specified. |
inclGrad |
Logical scalar. If TRUE the returned object will have a 0-row matrix gradient component. If FALSE the component will be NULL. |
respInfoTemplate |
Optional data frame with the columns to be included in |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with S3 class respPts. See the documentation for the
generic function for details.
Points in Input Space and their Response Function Values
Description
Extract a respPts object from one inheriting from respPairs.
This is an internal utility method, not intended to be used by package
users.
Usage
## S3 method for class 'respPairs'
respPts(x, which=c("raw", "1st", "2nd", "both", "paired"), ...)
Arguments
x |
Object inheriting from class |
which |
Character string indicating the form in which points are to be extracted.
|
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
When which is not "raw", points are extracted using the
pairIdxs component of x. Therefore the same point may
appear multiple times, if it belongs to multiple pairs, or not at all, if
it appears in no pairs.
The default for which is paired for lsetSegs objects,
raw for other objects.
Extra respInfo columns in x are not removed.
Value
An object of S3 class respPts. See the documentation for the
generic.
See Also
Points in Input Space and their Response Function Values
Description
Extract a respPts object from an object that inherits from that
class. Optionally update the response function threshold or tolerances
that define a level set of interest. This is an internal utility method,
not intended to be used by package users.
Usage
## S3 method for class 'respPts'
respPts(x, lsetthresh=NULL, resptol=NULL, strictInfoCols=TRUE, ...)
Arguments
x |
Object inheriting from class |
lsetthresh |
Optional scalar, the value of the response function that defines the level
set of interest. If specified it updates the value in |
resptol |
Optional two-element vector with tolerance parameters for the response
function (see |
strictInfoCols |
Logical scalar. If TRUE (the default), any columns in the |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
If lsetthresh or resptol is not NULL, column lset in
the respInfo() data frame will be recalculated based on the
specified threshold and tolerance parameters. In that case
strictInfoCols must be TRUE, because there is no simple way to
update lsetbdry.
This method also handles respProfiles objects. With the default
strictInfoCols, the additional respInfo columns line,
posn, feasbdry, lsetbdry, deriv, and
trend will be removed since the context of which lines/rays they
refer to is gone.
Value
An object with S3 class respPts. See the documentation for the
generic function for details.
See Also
Numerical Tolerance Specification for Response Values
Description
Return the tolerance specification for response function values.
Usage
respTol(x)
Arguments
x |
An |
Value
Two-element vector. The first element is the relative tolerance and the second is the minimum absolute tolerance.
See Also
lsetPkgOpt and absTol describe how tolerances
are specified in this package. fnSpec,
fnObj.character
Examples
# See examples in '?fnSpec'
Modify an 'inpScale' Object to Preserve Slice Membership
Description
Modify an inpScale object so that it preserves point membership in
a single specified slice of input space. This is an internal utility
function, not intended to be called by package users.
Usage
scale_w_slice(x, slice)
Arguments
x |
An |
slice |
One-row matrix specifying a slice of input space. If all elements are NA,
|
Details
In order to preserve point membership in a slice, coordinates of the
dimensions specified by the non-NA elements of slice must not be
changed. Therefore the corresponding rows and columns of matrices
W and Winv of the returned inpScale object must be
those from the identity matrix. (Rows and columns for the other
dimensions are also modified, in a less obvious way, to allow for removal
of any correlations with the fixed dimensions.)
This function makes that modification to x$Winv, constructs a new
V matrix as Winv %*% t(Winv), and creates a new
inpScale object by hand.
Value
An inpScale object with the same input space as x, but
modified so that the associated transformations preserve point membership
in the specified slice.
See Also
Hyper-Rectangle Bounding a Set of Level Set Segments
Description
Create an axis-aligned hyper-rectangle just large enough to contain all
the level set points in an lsetSegs object. Optionally expand or
contract the hyper-rectangle from that size.
Usage
segBoundingRect(x, refpt=NULL, expand=c(1.0, 1.0), warnEmpty=TRUE)
Arguments
x |
An |
refpt |
A vector or one-row matrix containing the coordinates of the point to use
as the reference point for the new hyper-rectangle. The new
hyper-rectangle will always include it. The default is the centroid of
the segment endpoints in |
expand |
One or two-element numeric vector of expansion factors for the
hyper-rectangle, relative to what is required to just contain all the
points in |
warnEmpty |
Logical scalar. If TRUE, a warning will be raised if |
Details
The midpoint of each line segment in x is found, and the endpoints
are adjusted so that their distances from the midpoint are multiplied by
factor expand[1] (for uncensored endpoints) or expand[2]
(for censored endpoints). The smallest axis-aligned hyper-rectangle
containing all of the adjusted endpoints and refpt is calculated.
Censoring is defined by the variable lsetcens in the data frame
returned by respInfo(x).
inpRect objects are required to have positive d-dimensional
volume, so any sides of the hyper-rectangle that have near-zero length
will be increased enough to pass a check based on inpTol(x).
Value
An inpRect object containing the calculated hyper-rectangle, or
NULL if x does not contain any segments.
See Also
inpRect, lsetSegs, boundingRect
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
Ex <- dbl_ellipse_2dEx # see '?dbl_ellipse_2dEx'
segs <- Ex$segs_checked
bnding_rect <- segBoundingRect(segs, expand=1.0)
plot(segs, rect=bnding_rect, main="Level set segs with bounding rectangle")
lsetPkgOpt(oldopt)
Information About Level Set Line Segments
Description
Extract a data frame of information about each line segment in an
lsetSegs object.
Usage
segInfo(x)
Arguments
x |
An |
Value
Data frame with one row per segment in x. The returned data frame
has columns:
line |
Index of the line/ray (i.e., in |
posn1, posn2 |
Positions of the segment endpoints along their line. |
feasbdry1, feasbdry2 |
Logicals indicating whether a segment endpoint is known to be on the boundary of the feasible region of the response function. |
lsetcens1, lsetcens2 |
Logicals indicating censoring of the line segment with respect to the boundary of the level set. That is, whether the level set appears to extend beyond each endpoint of the segment, in the direction of the line containing it. Will never be NA. |
See Also
Examples
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
segs <- Ex$segs_checked
summary(segs)
head(segInfo(segs), 10)
Intersection(s) of Line Segments with a Slice of Input Space
Description
Find the intersection(s) of line segments with a single slice of input space. This is an internal utility function, not intended to be called by package users.
Usage
seg_1slice_isctn(coord1, coord2, slice, inptol)
Arguments
coord1, coord2 |
Matrices with the coordinates of segment endpoints. |
slice |
One-row matrix specifying a slice of input space. The identity slice (no dimensions with fixed values) is allowed, and returns the endpoints for any segment. |
inptol |
2-row matrix with tolerance specifications for input space coordinates. |
Details
To reduce roundoff/representation errors, coordinates of intersection
points for the fixed dimensions of slice are set to their exact
values in slice.
Value
List with one component per segment. Each component is a matrix with the coordinates of 0, 1, or 2 points: 0 if the segment does not intersect the slice; 1 if the segment intersects it at a single point; and 2 (i.e., the segment endpoints) if the segment is contained in the slice.
See Also
pt_in_slice, pt_on_line2,
sliceMatch
Post-Process Boundary Search Results along a Single Line
Description
Helper function for bdrySearch_1slice_1d and merge_segs:
Given level set segments along a single line, determine whether each pair
of segments is distinct; contiguous/overlapping and can be merged; or
inconsistent and cannot be merged. This is an internal utility function,
not intended to be called by package users.
Usage
seg_consistency_1line(x)
Arguments
x |
|
Details
Contiguous or overlapping segments along a single line are consistent if
the endpoints in the interior of the merged segment are censored.
Uncensored interior endpoints indicate that the individual searches that
produced them probably missed some intermediate boundary crossings. (For
example, initPosns was too coarse relative to fluctuations in the
response function.)
Value
List with three components. Each is an nsegs x nsegs
logical matrix, where nsegs is the number of segments in x:
distinct |
TRUE if a pair of segments are distinct (separated by at least a tolerance amount). |
mrg |
TRUE if a pair of segments are contiguous or overlapping (within a numerical tolerance), and can be merged. (Diagonal elements will be FALSE.) |
incon |
TRUE if a pair of segments are contiguous or overlapping (within a numerical tolerance), but appear to be inconsistent (see DETAILS) and should not be merged. |
For a pair [i, j] of segments with i != j, exactly one of
distinct[i,j], mrg[i,j] and incon[i,j] will be TRUE.
See Also
merge_segs, bdrySearch_1slice_1d,
interval_merge
Faster Combining of Lists of Segments
Description
Combine a list of sets of segments (e.g., a list of respPairs
objects, or a list of pre-lsetSegs lists) into a single set. This
is a faster way than c methods to combine compatible sets, with no
compatibility or validity checking. This is an internal utility function,
not intended to be called by package users.
Usage
segs_combine(x, class)
Arguments
x |
List of compatible |
class |
Desired form of the returned result, either |
Details
respPairs objects are the same as pre-lsetSegs lists except
for not requiring additional columns in respInfo and
pairInfo data frames. Therefore argument class may be set
to respPairs even when x is a list of pre-lsetSegs
lists, and vice versa if the right columns are present.
Value
A single combined respPairs object or pre-lsetSegs list, as
specified by class.
See Also
This function is called by bdryFromRays,
lsetSegs.respProfiles, lsetSegsCheck.
Cumulative Element Counts Within Runs of Values
Description
Given a vector x, return a parallel vector that counts the
cumulative number of elements but resets to 1 whenever the value in
x changes. This is an internal utility function, not intended to
be called by package users.
Usage
seq_along_runs(x)
Arguments
x |
Vector. |
Value
Vector of positive integers with the same length as x. Element
i is the cumulative number of consecutive elements in x with
the same value as x[i] (a run). The count resets to 1 every time a
new run starts.
Define Slices of Input Space
Description
Create a matrix that specifies slices of input space.
Usage
sliceMat(x, spec, names=NULL)
Arguments
x |
Matrix or list specifying slices. See DETAILS. If omitted, a matrix with 0 rows (i.e., no slices) is returned. |
spec |
|
names |
Character vector or logical scalar. FALSE means the slices will have no
names. TRUE constructs default names of the form |
Details
A slice of d-dimensional input space is defined as an axis-aligned
hyperplane with d_s dimensions, where 1 <= d_s <= d. Points
in a slice have fixed values for d - d_s of their coordinates,
while the coordinates for the remaining d_s > 0 dimensions take any
values. This is reflected in how slices are represented internally: As
rows of a d-column matrix, where in each row d - d_s
elements are set to fixed values and d_s elements are NA. (The
slice dimension d_s can vary between rows.)
The case when d_s = d (no dimensions have fixed values) is called
the identity slice, and represents the whole input space. To specify the
identity slice, x must be provided in matrix form with a row of all
NA values.
The list form of argument x should consist of components named by a
subset of input space dimensions. Each component should be a vector of
values to be used for the corresponding dimension. Values in each
component will be crossed with all values in the other components, in the
style of base::expand.grid. The result will be a matrix with
prod(lengths(x)) rows (slices). Matrix elements for any dimension
not mentioned in x will be set to NA.
Value
A matrix with one row per slice.
Examples
fspec <- fnSpec(inpnames=c("X1", "X2", "X3"))
# Slices specified directly in matrix form:
slices <- sliceMat(rbind(c(4, 3, NA), c(4, NA, NA), c(NA, 3, NA),
c(NA, NA, NA)), spec=fspec)
slices
sliceMat(spec=fspec) # no slices
# Slices specifed in list form:
slices2 <- sliceMat(list(X2=c(3, -1), X1=c(4, 0, 1)), spec=fspec)
slices2 # 3 x 2 = 6 slices
Identify Points/Lines/Segments that Lie in Slices of Input Space
Description
For each slice of input space specified in slices, identify the
points/rays/lines/segments in object y that lie in the slice. This
is an internal utility function, not intended to be called by package
users.
Usage
sliceMatch(slices, y, inptol)
Arguments
slices |
A matrix specifying slices of input space. |
y |
A matrix, or object inheriting from |
inptol |
2-row matrix with tolerance specifications for each input space dimension
(see |
Details
A point in y is considered to lie in a slice s if its
j-th coordinate y[j] is equal to s[j] (to within a
numerical tolerance based on inptol[, j]), for all j for
which s[j] is not NA. (So an NA value for s[j] matches any
value for y[j].)
A ray or line in y is considered to lie in s if its position
0 and position 1.0 points both lie in s.
A line segment in y is considered to lie in s if both
endpoints of the segment lie in s.
Value
List with one component per slice in slices. Each component is an
integer vector indexing the elements of y that lie in that slice.
See Also
Test Whether Slices of Input Space Intersect a Hyper-Rectangle
Description
Test whether slices of input space intersect a hyper-rectangle. This is an internal utility function, not intended to be called by package users.
Usage
slice_in_rect(slices, rect, inptol=inpTol(rect))
Arguments
slices |
Matrix of slice specifications. The identity slice (no dimensions with fixed values) is allowed. |
rect |
|
inptol |
2-row matrix with tolerance specifications for input space coordinates. |
Value
Logical vector with one element per slice. TRUE means the slice
intersects rect, to within the numerical tolerances specified by
inptol.
See Also
Ray-Based Exploration of the Boundary of a Level Set
Description
Identify the boundary of a level set by finding points where a set of rays intersect it. A separate set of rays is used for each of the specified slices of the input space.
Usage
slicedBdryFromRays(x, lsetthresh, slices, rect, scale=NULL,
origins=NULL, currentBdry=NULL, control=list())
Arguments
x |
|
lsetthresh |
Response function value that defines the level set of interest. |
slices |
Matrix specifying one or more slices of input space. See |
rect |
|
scale |
Optional |
origins |
Optional matrix specifying the point to use as the ray origin for each
slice. The number of rows must match the number of slices. Each origin
must belong to |
currentBdry |
Optional object containing existing information about the level set
boundary: either an |
control |
Optional list with parameters to control the search process. See
|
Details
When the rays used in each slice are random and control$seedRays is
not NA (which it is not by default; see ?srchControl), the state of
R's random number generator is reset between slices, to its value for the
first slice. This is done so that results for a given slice do not depend
on the number or order of other slices.
Value
List with one component per slice. Each component is itself a list, with
the same structure as the value returned by bdrySearch(), plus
slice information. All boundary points and origins will lie in their
slices.
Note that the rays used for slice i can be extracted by
inpRays(rslt[[i]]$segs), where rslt is the list returned by
this function.
List names will be taken from rownames(slices).
See Also
sliceMat, bdryFromRays,
srchControl, plotSegsList
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
Ex <- circuitFailure_3dEx # see '?circuitFailure_3dEx'
fobj <- Ex$fobj
thresh <- Ex$thresh
theta_mle <- Ex$theta_mle
theta_vcov <- Ex$theta_vcov
# Initial level set search without slicing.
rect1 <- inpRect(rbind(theta_mle - 3*sqrt(diag(theta_vcov)),
theta_mle + 3*sqrt(diag(theta_vcov))),
spec=fobj)
scl1 <- inpScale(theta_vcov, spec=fobj)
set.seed(1)
rays1 <- randomRays(100, rect=rect1, scale=scl1)
segs1 <- bdryFromRays(fobj, rays=rays1, lsetthresh=thresh)
# The three input dimensions are 'dfrac', 'shape', and 'scale'.
# Consider slices defined by six values of 'scale'.
slices <- sliceMat(list(scale=c(10, 30, 50, 70, 90, 110)), spec=fobj)
# To apply `slicedBdryFromRays()` we need to specify a search region that
# intersects all the slices, such as
rect2 <- boundingRect(rect1, slices, expand=1.1)
# Use 'currentBdry=segs1' as a "warm start" for searching within slices.
slsrch <- slicedBdryFromRays(fobj, lsetthresh=thresh, slices=slices,
rect=rect2, scale=scl1, currentBdry=segs1)
if (use("ggplot2")) {
plt <- plotSegsList(slsrch, dims=c("dfrac", "shape"), rect=rect1)
print(plt + theme(panel.background=element_blank()) +
labs(title="Level set sliced by 'scale'"))
}
lsetPkgOpt(oldopt) # restore previous settings
Ray-Based Exploration of the Boundary of a Level Set
Description
Identify the boundary of a level set by finding pairs of boundary points,
such that the line segment connecting each pair appears to lie entirely in
the level set. The search is carried out separately within specified
slices of the input space. For each slice an adaptive, ray-based search
is carried out, as described for function bdrySearch(). A list is
returned, where each component is the result returned by
bdrySearch() for a single slice.
Usage
slicedBdrySearch(x, lsetthresh, slices, rect, scale=NULL,
initOrigins=NULL, currentBdry=NULL, control=list())
Arguments
x |
An |
lsetthresh |
Response function value that defines the level set of interest. |
slices |
Matrix specifying one or more slices of input space. See |
rect |
|
scale |
Optional |
initOrigins |
Optional matrix specifying the point to use as the initial ray origin for
each slice. The number of rows must match the number of slices. Each
origin must belong to |
currentBdry |
Optional object containing existing information about the level set
boundary: either an |
control |
Optional list with parameters to control the search process. See
|
Details
By default the results for a given slice do not depend on the number or
order of other slices in slices; see ?srchControl.
Value
List with one component per slice. Each component is itself a list, with
the same structure as the value returned by bdrySearch(), plus
slice information. All boundary points and origins will lie in their
slice.
List names will be taken from rownames(slices).
See Also
sliceMat, bdrySearch,
srchControl, plotSegsList
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
Ex <- circuitFailure_3dEx # see '?circuitFailure_3dEx'
fobj <- Ex$fobj
thresh <- Ex$thresh
theta_mle <- Ex$theta_mle
theta_vcov <- Ex$theta_vcov
# Initial level set search without slicing.
rect0 <- inpRect(rbind(theta_mle - 3*sqrt(diag(theta_vcov)),
theta_mle + 3*sqrt(diag(theta_vcov))),
spec=fobj)
scl0 <- inpScale(theta_vcov, spec=fobj)
bsrch <- bdrySearch(fobj, lsetthresh=thresh, rect=rect0, scale=scl0,
initOrigin=theta_mle,
control=list(axisDegree=2, updateScale=2))
# The three input dimensions are 'dfrac', 'shape', and 'scale'.
# Consider slices defined by four values of 'scale'.
slices <- sliceMat(list(scale=c(10, 40, 70, 110)), spec=fobj)
# To apply `slicedBdrySearch()` we need to specify a search region that
# intersects all the slices, such as
rect1 <- boundingRect(bsrch$rect, slices, expand=1.1)
# Use 'currentBdry=bsrch' as a "warm start" for searching within slices.
slsrch <- slicedBdrySearch(fobj, lsetthresh=thresh, slices=slices,
currentBdry=bsrch, rect=rect1, scale=bsrch$scale,
control=list(axisDegree=2, maxSteps=6))
# If desired, plot results, one slice per panel:
#if (use("ggplot2")) {
# plt <- plotSegsList(slsrch, dims=c("dfrac", "shape"), rect=rect1)
# print(plt + theme(panel.background=element_blank()) +
# labs(title="Level set sliced by 'scale'"))
#}
lsetPkgOpt(oldopt) # restore previous settings
Rearrange the Internal Structure of an 'lsetSegs' Object
Description
Rearrange the internal structure of an lsetSegs object. Segments
are sorted first by their line index and then by the smaller of the
positions of their two endpoints on that line. Within a segment the
endpoints are sorted by position. This is an internal utility method, not
intended to be used by package users.
Usage
## S3 method for class 'lsetSegs'
sort(x, decreasing=FALSE, withinSegsOnly=FALSE, ...)
Arguments
x |
|
decreasing |
Argument required by the generic but ignored, with a warning, by this function. |
withinSegsOnly |
Logical scalar. If TRUE, the order of segments in |
... |
Additional arguments required by the generic but ignored, with a warning, by this function. |
Details
Sorting of endpoints within each segment is done just by editing the
corresponding column of the pairIdxs component. This does not
change the respInfo, ptCoord, or respGrad components.
Therefore the within-segment sorting will be apparent when respInfo
or ptCoord are called with most values of which, but not
when which is raw.
*Should consider making sorted endpoints within each segment a requirement
in the specification of lsetSegs objects.*
Value
lsetSegs object containing the same segments as x but
possibly with rearranged rows and columns of internal components.
Default Control Parameters for Boundary Search Functions
Description
Return a list with default settings for various control parameters used by level set boundary search functions.
Usage
srchControl(d)
Arguments
d |
Dimension of the input space, or vector of slice dimensions if slicing is being used. |
Details
Functions bdryFromRays, bdrySearch, and their sliced*
versions each have a control argument that specifies certain
parameters used to control the search for level set boundary points. This
function documents the parameters and their default values. Note that not
all parameters are used by a given function, and default values can be
overridden in the control argument.
The control parameters are categorized into four groups:
Finding boundary points along given rays. (These parameters are used by all search functions.):
- initPosns
Vector of non-negative positions along each ray that will be used as starting points to search for intersections with the level set boundary. Position 0 (the ray origin) will always be included, and at least one other strictly positive value is required. Default:
c(0, 1).- initPosns2
Optional vector of additional positive positions to use as starting points for finding boundary crossings. These additional positions are only tried for rays for which no or only censored boundary crossings are found using
initPosns. The default isc(0.25, 0.5, 2, 4).- bothDirections
Logical scalar. If TRUE (the default), the search for boundary intersections is also done along a reversed version of each ray, and combined with those from the original ray.
Generating rays to search along, given a ray origin. (Used by
bdrySearch(), slicedBdrySearch(),
slicedBdryFromRays().):
- rayType
Character string.
randommeans rays will be generated by functionrandomRays();axismeansaxisRays()will be used. Default isaxisforbdrySearch()andslicedBdrySearch(),randomforslicedBdryFromRays().- nRays
Vector containing the number of rays to generate for each slice when
rayTypeisrandom. Default is 1 if the slice dimension is 1, andpmin(5^d, 1000)for largerd(i.e., 1000 ford > 4).- axisDegree
When
rayTypeisaxis, vector of positive integers less than or equal to slice dimensions ind. For slicei, rays are generated from unit vectors along each free coordinate axis and combinations of those vectors up toaxisDegree[i](see?axisRays). A scalar will be repeated for all slices. Default: 1.- rotateRays
Logical scalar. If TRUE and
rayTypeisaxis, the set of axis-based rays will be randomly rotated after each step (new origin). Default is TRUE.- seedRays
Integer used to initialize the RNG stream for random rays when
rayTypeisrandom, or the random rotations whenrayTypeisaxisandrotateRaysis TRUE. If NA, the current state of R's random number stream will be used, and is never reset. If not NA, the current state of R's RNG will be saved and restored at the end, as if random number generation had not been used. Default: 1.- warnDegenerate
Integer or logical scalar. When a ray origin is on the boundary of a search region (hyper-rectangle), it is possible for certain ray directions to lead to degenerate rays (i.e., positions 0 and 1 are the same point). Degenerate rays are not allowed.
warnDegeneratecontrols whether they are silently dropped (0 or FALSE), dropped with a warning (1 or TRUE), or treated as an error (2). The default is 0.
Generating initial or new ray origins. (Used by bdrySearch(),
slicedBdrySearch(), slicedBdryFromRays().):
- maxSteps
Vector setting the maximum number of steps (ray origins) the search will use to explore the level set boundary for each slice. A scalar value will be repeated for all slices. Default:
pmin(d^2, 100).- originBias
Scalar in [0, 1] used during the generation of new candidate origins. It specifies where along each level set segment the candidate origins are placed relative to the segment's midpoint (0) and endpoints (1). Values close to 1 bias origin selection toward existing level set boundary points, while values close to 0 prefer new origins toward the interior of the level set. Default: 0.6.
- originCrit
Character string specifying how the new origin at each step is selected from among the candidate origins. One of
maximindist,minimaxdist, ormaxproj. The default ismaximindist. See?bdrySearch.- lsetFirst
Logical scalar. If TRUE (the default), candidate origins that belong to the level set are always preferred over those that do not, regardless of their criterion value.
- srchDirection
Vector, 1-row matrix, or 1-element
inpLinesobject specifying a direction in input space. Required iforiginCritismaxprojand ignored otherwise. The boundary search will select the candidate origin with maximum projection onto this vector.- maxCandOrigins
Positive integer. New ray origins are selected from among a potentially large number of candidates generated from previously-found level set segments. Depending on the selection criterion
originCrit, the distance from each candidate to each existing origin or existing boundary point must be calculated, which can result in a large distance matrix. This parameter limits the number of candidates that will be considered. Default is 1000.- maxDistances
Positive integer. Soft limit on the total number of elements allowed for a distance matrix, during the selection of new origins. Default is 1e7.
Initializing or updating the search region (rect) and input scaling
(scale) during a boundary search, based on current information
about the level set. (Used by bdrySearch(),
slicedBdrySearch(), slicedBdryFromRays().):
- updateRect1, updateRect2
Numeric scalars. The first specifies whether the search region
rectwill be updated before each step (new ray origin) to include all previously found boundary points. The update is done bysegBoundingRect()with expansion factors 1.2 for uncensored boundary points and 2.0 for censored points. A value of 0 means no update, > 0 enables updates; the default is 1.updateRect2is the maximum number of times to allowrectto be expanded within each step (fixed origin and ray directions), to try to resolve censored level set segments along its rays. 0 means no expansion; the default is 2 times.- updateScale
Logical or numeric scalar. If FALSE or 0, the same
scaleis used at every step. If TRUE or 1 (the default), scaling factors for input space dimensions are updated at each step to the lengths of the sides of the bounding hyper-rectangle for previously found boundary points. The dimension correlation structure specified by argumentscale, if any, is unchanged. IfupdateScaleis 2, both scaling factors and correlation structure are updated at each step, using previously found boundary points.
Value
List with default values for the control argument of functions
bdryFromRays, bdrySearch, and their sliced* versions.
See Also
bdryFromRays, bdrySearch,
slicedBdrySearch, slicedBdryFromRays,
axisRays, randomRays
Examples
# The default control parameters for input space dimensions of 1, 2, 3:
str(srchControl(1:3))
Default Control Parameters for Boundary Search Functions
Description
Extract the control parameters for a single slice, from the list returned
by srchControl(). This is an internal utility function, not
intended to be called by package users.
Usage
srchControl_1slice(x, i)
Arguments
x |
List returned by |
i |
Index of the slice of interest. |
Details
This function assumes that each component of x either has length 0
or 1 (which is kept unchanged), or a vector with length equal to the
number of slices (from which the i-th element is returned).
Value
List like x, but containing only the control parameters for slice
i.
See Also
Check and Standardize Boundary Search Function Arguments
Description
Check validity and consistency of common arguments to functions searching for level set boundary points, and put them in standardized form. This is an internal utility function, not intended to be called by package users.
Usage
srchsetup_args(fnobj, rect=NULL, scale=NULL, slices=NULL,
initOrigins=NULL, lsetthresh=NULL, currentBdry=NULL, control=list())
Arguments
fnobj |
|
rect |
|
scale |
Optional |
slices |
Optional vector or matrix specifying one or more slices of input space.
If specified all slices must (to within a numerical tolerance) intersect
|
initOrigins |
Optional vector, matrix, or |
lsetthresh |
Numeric scalar, the response function value that defines the level set of interest. Must be finite and not NA. |
currentBdry |
Optional object containing existing information about the level set
boundary: either an |
control |
List with options to control the search process. See |
Details
The returned initOrigins will always be non-empty and valid. If
not user-specified it will be derived from currentBdry if that is
not empty, or from rectRefPt(rect) if it is.
If currentBdry has adequate level set information, and if requested
by control, rect and scales will be updated based on
the level set segments in currentBdry. This will happen before
initOrigins is generated.
Value
List with components derived from the arguments, standardized and made numerically consistent with each other:
spec |
|
slices |
Matrix with one row per slice. If argument |
initOrigins |
Matrix of origin points. The number of rows will match |
rect |
|
scales |
List with one component per slice in |
lsetthresh |
Same as the argument. |
currentBdry |
Standardized version of the argument. List with components |
control |
List, with values checked and standardized, with defaults inserted where needed. |
See Also
bdrySearch, slicedBdrySearch use this function
to process their arguments. Helper functions srchControl,
srchsetup_control, srchsetup_origin.
Check Validity and Consistency of Search 'control' Argument
Description
Check validity and consistency of control argument to functions
searching for level set boundary points. This is an internal utility
function, not intended to be called by package users.
Usage
srchsetup_control(control, d, d_s=d)
Arguments
control |
List, possibly empty. See |
d |
Scalar, the number of input space dimensions. |
d_s |
Vector containing the dimension of each slice of input space. (Just the
input space dimension |
Value
List, with values checked and defaults inserted where needed.
See Also
Initial Origin to Use for a Level Set Boundary Search
Description
Determine an initial origin to use for a level set boundary search. If slices are specified, determine a separate origin belonging to each slice. This is an internal utility function, not intended to be called by package users.
Usage
srchsetup_origin(fnobj, slices, rect, scales, lsetthresh,
currentBdry, control)
Arguments
fnobj |
|
slices |
Matrix with one row per slice. (May include the identity slice that has no dimensions with fixed values.) |
rect |
|
scales |
List with one component per slice. Each component should be an
|
lsetthresh |
Numeric scalar, the response function value that defines the level set of interest. Must be finite and not NA. |
currentBdry |
List containing existing information about the level set boundary (which may be empty). |
control |
List. See |
Details
It is assumed that all arguments have already been processed by
srchsetup_args() so that they are in standard form and mutually
consistent.
If currentBdry is empty, the initial origin is the reference point
of rect, projected to each slice.
If currentBdry is not empty, the initial origin(s) are derived from
it as described in ?bdrySearch.
Value
Matrix with coordinates of initial origin(s), one origin per slice.
All origins will strictly (without a numerical tolerance) belong to
rect, and to their associated slice if any.
See Also
srchsetup_args uses this function.
Coefficients Defining Sums and Differences of Basis Vectors
Description
Create a set of coefficient vectors that can be used to define sums and
differences of a set of basis vectors. The maximum number of basis
vectors included in a given sum or difference (i.e., number of non-zero
entries in a coefficient vector) is degree. This is an internal
utility function, not intended to be called by package users.
Usage
stdCombCoef(d, degree=1, includeFlipped)
Arguments
d |
Scalar, the number of basis vectors to be combined (and thus the length of each coefficient vector). |
degree |
Non-negative integer less than or equal to |
includeFlipped |
Logical scalar. If TRUE, for every coefficient vector its negative will also be included. If FALSE, coefficient vectors will be unique with respect to sign change. |
Details
Consider first the case when includeFlipped is FALSE. Coefficient
vectors of degree 1 will have a single non-zero entry, equal to 1. Thus
when degree=1, the returned matrix will be just the
d-dimensional identity matrix.
When degree=2, two additional coefficient vectors will be generated
for each of the choose(d, 2) pairs of basis vectors. Each
coefficient vector will have two non-zero entries, either (1/sqrt(2),
1/sqrt(2)) or (1/sqrt(2), -1/sqrt(2)). degree=3 adds four
coefficient vectors for each of the choose(d, 3) triples of basis
vectors, with three non-zero coefficients of +/-(1/sqrt(3)), and so on for
higher degree.
When includeFlipped is TRUE, all the above coefficient vectors are
also multiplied by -1 and included in the result.
Value
Matrix with d columns. Each row is a unique coefficient vector
with up to degree non-zero entries, and will be scaled to have unit
length. See DETAILS. The number of rows will be sum((2^(1:degree))
* choose(d, 1:degree)) if includeFlipped is TRUE, and half that if
it is FALSE.
If includeFlipped is TRUE, original and flipped versions of each
vector will be in consecutive rows.
See Also
Used by axisRays.
Put a Single Indexing Vector into a Standard Form
Description
Put a single indexing vector into a standard form, while checking validity. Logical and character vectors are converted to a numeric vector of indexes. This is an internal utility function, not intended to be called by package users.
Usage
std_index_vec(i, nmax, validnms=NULL)
Arguments
i |
Numeric, character, or logical vector intended to index elements of an object. |
nmax |
Number of elements in the object; the maximum allowed numerical index. |
validnms |
Character vector of valid names for elements of the object to be indexed. Default NULL means character indexing is not allowed. |
Value
Numeric vector of integer indices.
'summary' Method for 'lsetSegs' Objects
Description
summary method for lsetSegs objects. Package users should
call the generic summary function.
Usage
## S3 method for class 'lsetSegs'
summary(object, ...)
Arguments
object |
An |
... |
Ignored, with a warning. (Only resent for compatibility with the generic.) |
Details
If object is empty (no level set segments), respRange,
bBox, and bBoxVol will contain only NA values.
There is a print method for the objects returned by this function.
Value
An object with class summary.lsetSegs. This is a list with
components:
fnSpec |
|
nlines |
Number of lines/rays to which segments in |
inpLines |
|
lsetThresh |
Response function value that defines the level set to which segments belong. |
respRange |
Vector with minimum and maximum response function values over all segment
endpoints. (The minimum will be greater than or equal to
|
bBox |
|
bBoxVol |
Volume of the bounding box. |
lineInfo |
Data frame with one row per line/ray in
|
See Also
Examples
oldopt <- lsetPkgOpt(reset=TRUE)
Ex <- dbl_ellipse_X1bnd_2dEx # see '?dbl_ellipse_2dEx'
segs <- Ex$segs_checked
summary(segs) # 75 segments along 50 rays (25 rays have 2 segs each)
# 34 of 150 segment endpoints are on the foundary of the
# feasible region.
lsetPkgOpt(oldopt)
'summary' Method for 'respProfiles' Objects
Description
summary method for respProfiles objects. Package users
should call the generic summary function.
Usage
## S3 method for class 'respProfiles'
summary(object, ...)
Arguments
object |
A |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Value
An object with class summary.respProfiles. This is a list with
components:
fnSpec |
|
nlines |
Number of lines/rays profiled in |
inpLines |
|
lsetThresh |
Response function value that defines a level set for which line intersections with its boundary were searched. May be NA. |
ptCounts |
Matrix with one row per line/ray profile, and columns of point counts for each:
|
respRange |
Matrix with one row per line/ray profile, and two columns containing the
minimum and maximum response function values in the profile for each
line/ray. Values will be NA if |
See Also
Examples
# See the examples in '?respProfiles'.
'summary' Method for 'respPts' Objects
Description
summary method for respPts objects. This is an internal
utility method, not intended to be used by package users.
Usage
## S3 method for class 'respPts'
summary(object, ...)
Arguments
object |
An object inheriting from class |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
If object is empty (no points), coordRange and
respRange will contain only NA values, and no warnings will be
produced. This differs from the base R convention of returning
c(Inf, -Inf) with warnings.
Value
An object with class summary.respPts. This is a list with
components:
fnSpec |
|
lsetThresh |
Response function value that defines a level set of interest. May be NA. |
ptCounts |
Matrix with one row, and columns of point counts:
nlset : Number of points in the level set (NA if |
coordRange |
Two-row matrix with minimum and maximum point coordinates for each input
space dimension. (All NA if |
respRange |
Vector with minimum and maximum response function values over all feasible points. (All NA if there are no feasible points.) |
inclGrad |
Logical scalar. TRUE if |
See Also
Test for Degenerate Point Pairs
Description
Test whether the endpoints of a set of point pairs should be considered (effectively) tied, based on a numerical tolerance for input space coordinates. This is an internal utility function, not intended to be called by package users.
Usage
tied_endpts(x, pairidxs=NULL, x2=NULL, abstol=NULL, inptol)
Arguments
x |
Matrix containing coordinates of points in input space. |
pairidxs |
Two-row matrix. Each column contains the indices in |
x2 |
Alternative to |
abstol |
|
inptol |
An alternative way to specify tolerances: |
Details
If abstol is specified: Points x[i, ] and x2[i, ] are
considered tied if all(abs(x[i, ] - x2[i, ]) <= abstol[i, ]) is
TRUE.
If abstol is not specified: inptol is used to create two
n x d matrices atol1 and atol2, from x and
x2 respectively. Then abstol is defined as
pmax(atol1, atol2), and points are compared as above.
Value
Logical vector with length equal to the number of point pairs. TRUE means the corresponding pair is degenerate, in the sense that the line segment connecting the endpoints has essentially zero length.
See Also
Are Elements in One Vector Tied with any Element in Another?
Description
For each element of numeric vector x, is it tied with any element
of numeric vector y, to within abstol (a scalar or a vector
parallel to x)? This is an internal utility function, not intended
to be called by package users.
Usage
tied_with_any(x, y, abstol)
Arguments
x, y |
Numeric vectors. |
abstol |
Numeric scalar, or vector with the same length as |
Value
Logical vector with the same length as x. Element i is TRUE
if x[i] equals any element in y, to within absolute
tolerance abstol. NA in x will yield NA in the
corresponding element of the return.
If any element of y is NA, the result will be NA for elements of
x for which no tie is found with any of the non-NA elements of
y. (I.e., the return values will be either TRUE or NA, never
FALSE.)
Update Certain Specifications in an 'fnObj' Object
Description
Update certain specifications in an fnObj object. Package users
should call the generic update function.
Usage
## S3 method for class 'fnObj'
update(object, inptol=NULL, resptol=NULL, derivmethod=NULL,
warnNAresp=NULL, warnInfresp=NULL, ...)
Arguments
object |
|
inptol, resptol, derivmethod, warnNAresp, warnInfresp |
New values for specifications in |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
The number and names of input space dimensions, the response function, and its feasible region cannot be updated.
Value
An fnObj object.
See Also
Examples
fnobj <- fnObj(c("X1", "X2"), function(x) { colSums(x) },
inptol=c(1e-6, 1e-8))
inpTol(fnobj)
fnobj2 <- update(fnobj, inptol=c(1e-4, 2e-8))
inpTol(fnobj2)
Rays in Input Space
Description
Update an inpRays object with a new origin and/or hyper-rectangle.
Package users should call the generic update function.
Usage
## S3 method for class 'inpRays'
update(object, origin=NULL, rect=NULL, warnDegenerate=TRUE, ...)
Arguments
object |
|
origin, rect |
Optional values to update the ray origin and/or the hyper-rectangle
associated with the rays. (Rays will be scaled so that position 1.0 on
each ray is its intersection with the boundary of |
warnDegenerate |
Integer or logical scalar. If 1 or TRUE (the default), a warning will be raised if any rays are dropped because their position 1.0 point is (near-)equal to the ray origin. If 0 or FALSE, degenerate rays are dropped silently. If 2, degenerate rays will be treated as an error. |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
Ray directions are preserved. However rays may be dropped during the
update if they become degenerate (their position 1.0 point is equal to the
ray origin, to within a numerical tolerance). This can happen if a new
rect is specified, or with a new origin if object
already has an associated hyper-rectangle.
Value
An object with S3 class inpRays, inheriting from inpLines.
Examples
fspec <- fnSpec(inpnames=c("X1", "X2"))
set.seed(1)
rays <- randomRays(10, spec=fspec) # ray vectors have unit length,
# origin at (0, 0)
rect2 <- inpRect(rbind(c(0, 0), c(1, 1)), spec=fspec) # unit square
rays2 <- update(rays, origin=c(0.3, 0.4), rect=rect2)
plot(rays, eqAxes=TRUE, main="Updating ray origin and rect")
plot(rays2, rect=rect2, add=TRUE, rayPar=list(col="blue"))
Update Method for 'inpRect' Objects
Description
Update an inpRect object with a new reference point or size.
Package users should call the generic update function.
Usage
## S3 method for class 'inpRect'
update(object, refpt=NULL, expand=NULL, ...)
Arguments
object |
|
refpt |
A vector or one-row matrix containing the coordinates of a single point.
The point must belong to the hyper-rectangle, before applying
|
expand |
Positive scalar. The hyper-rectangle will be expanded away from/
contracted toward |
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
Hyper-rectangles represented by inpRect objects must be finite and
have non-zero d-dimensional volume. See ?inpRect for how
the latter condition is defined.
Values of expand less than 1 will contract the hyper-rectangle
toward refpt.
Value
An inpRect object.
Examples
fspec <- fnSpec(inpnames=c("X1", "X2"))
rect <- inpRect(rbind(c(-1, 3), c(2, 5)), refpt=c(0, 4), spec=fspec)
rect2 <- update(rect, refpt=c(1, 3), expand=1.5)
# Size increases from 3 x 2 to 4.5 x 3. Expansion is relative to new
# reference point.
plot(rect2, showRefPt=TRUE, border="red", main=
"Original (blue) and updated (red) 'inpRect' objects")
plot(rect, showRefPt=TRUE, border="blue", add=TRUE)
'update' Method for 'respProfiles' Objects
Description
update method for respProfiles objects. It allows updating
the hyper-rectangle associated with the inpLines component of the
object. This is an internal utility method, not intended to be used by
package users.
Usage
## S3 method for class 'respProfiles'
update(object, rect=NULL, ...)
Arguments
object |
|
rect |
|
... |
Ignored, with a warning. (Only present for compatibility with the generic.) |
Details
The inpLines component of object must actually be an
inpRays object, so that it can have an associated hyper-rectangle.
Also, at present it is an error if the new rect causes any rays to
become degenerate.
In addition to updating inpLines(object), this function updates
some columns of respInfo(object) to reflect the change in position
1.0 for the rays.
Value
Object with the same class(es) as object, but with rays rescaled to
put position 1.0 on the boundary of rect.
See Also
respProfiles. bdrySearch_1origin calls this
function.
Warn/Error About NA and Infinite Response Function Values
Description
Utility function called in fnObj objects to generate warning or
error messages if the response function evaluates to NA or +/-Inf at
feasible input points. The amount of output is controlled by option
warn.showBadRespPts. This is an internal utility function, not
intended to be called by package users.
Usage
warnBadResp(resp, x, type=c("NA", "Inf"), level=1)
Arguments
resp |
Vector of response function values at points in |
x |
Matrix of point coordinates, one point per row. |
type |
Character string indicating which type of response value is being warned about, NA or +/-Inf. |
level |
Type of message: 1 = warning, 2 = error. |
Value
Invisible NULL. This function is used only for its side effect of generating warning or error messages.