Author SHA1 Message Date
Sébastien Albert 920d1735a9 Update Readme - add Installation and Usage 2021-12-15 10:22:42 +01:00
Sébastien Albert b82667ad0c Update README.md 2021-12-08 14:25:46 +01:00
Sébastien Albert ba5e1f7e67 add usd-21-11-win64_py39 2021-12-07 17:43:55 +01:00
15685 changed files with 3069974 additions and 3 deletions

No files matched your search

+17 -3
View File
@@ -1,10 +1,24 @@
# usd_prebuilt_libraries
USD Pre-built Libraries for windows are released :
- **usd-21-05-win64_py37** ( USD 21.05, Python 3.7 ) Compatible with **Blender 2.92**
- **usd-21-11-win64_py39** ( USD 21.11, Python 3.9 ) Compatible with **Blender 3.0**
- [usd-21-11-win64_py39](https://github.com/LoopsCreativeStudio/usd_prebuilt_libraries/releases/tag/usd-21-11-win64_py39) ( USD 21.11, Python 3.9 ) Compatible with **Blender 3.0**
- [usd-21-05-win64_py37](https://github.com/LoopsCreativeStudio/usd_prebuilt_libraries/releases/tag/usd-21-05-win64_py37) ( USD 21.05, Python 3.7 ) Compatible with **Blender 2.92**
# NVIDIA, other versions :
# Installation :
Add *"C:\usd-21-11-win64_py39\lib\python"* in your environment variable **PYTHONPATH**
# Usage :
In Blender 3.0 or Python 3.9, you can test if the python module works with this command:
```python
from pxr import Usd
stage = Usd.Stage.Open('path_to_file.usd')
```
More exemples here : https://developer.nvidia.com/usd/tutorials
# NVIDIA, other prebuilt versions :
- https://developer.nvidia.com/usd
# USD PIXAR :
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
BIN
View File
Binary file not shown.
BIN
View File
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+171
View File
@@ -0,0 +1,171 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2017 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
# This is a wrapper around Usdview's launcher code to allow injection of a
# script for testing purposes. Tests can be supplied in the form of a python
# script which provides a function testUsdviewInputFunction(appController)
# as the entry point. This is passed to testusdview with the (required)
# --testScript argument. Other than this signature requirement, scripts are
# free to do whatever they want with mainwindow for testing.
import pxr.Usdviewq as Usdviewq
from pxr.Usdviewq import AppController
from pxr.Usdviewq.qt import QtWidgets
import sys, os, inspect, argparse
TEST_USD_VIEW_CALLBACK_IDENT = "testUsdviewInputFunction"
class TestUsdView(Usdviewq.Launcher):
def RegisterOptions(self, parser):
super(TestUsdView, self).RegisterOptions(parser)
parser.add_argument('--testScript', action='store', required=True,
help="The test script to run after loading. "
"This script must expect to take a single")
def Run(self):
parser = argparse.ArgumentParser(prog=sys.argv[0],
description=self.GetHelpDescription())
self.RegisterOptions(parser)
super(TestUsdView, self).RegisterPositionals(parser)
arg_parse_result = super(TestUsdView, self).ParseOptions(parser)
# We always set --defaultsettings to ensure a consistent test
# environment for our test scripts.
arg_parse_result.defaultSettings = True
super(TestUsdView, self).ValidateOptions(arg_parse_result)
# Further, we ensure usdview won't try to create any state directory
# to save its state, as that would be bad for running multiple tests
# in parallel
os.environ['PXR_USDVIEW_SUPPRESS_STATE_SAVING'] = "1"
self.__LaunchProcess(arg_parse_result)
def __LaunchProcess(self, arg_parse_result):
callBack = self._ValidateTestFile(arg_parse_result.testScript)
(app, appController) = (
super(TestUsdView, self).LaunchPreamble(arg_parse_result))
# Set a fixed size on the stage view so that any image tests get a
# consistent resolution - but only if we've created a viewer
if appController._stageView:
appController._stageView.setFixedSize(597,540)
# Process initial loading events
app.processEvents()
callBack(appController)
# Process event triggered by the callbacks
app.processEvents()
# Trigger application shutdown.
app.instance().closeAllWindows()
return
# Verify that we have a valid file as input, and it contains
# our expected entry point for testing.
#
# Upon success, this will return the callback to be called after
# launching Usdview and doing the initial load pass
def _ValidateTestFile(self, filePath):
if not os.path.exists(filePath):
sys.stderr.write('Invalid file supplied, does not exist: {}\n'
.format(filePath))
sys.exit(1)
if not os.access(filePath, os.R_OK):
sys.stderr.write('Invalid file supplied, must be readable: {}\n'
.format(filePath))
# Ensure that we are passed a valid python file
_, ext = os.path.splitext(filePath)
if ext != '.py':
sys.stderr.write('Invalid file supplied, must be a python file: '
'{}\n'.format(filePath))
sys.exit(1)
# Grab the function from the input python file
# if it doesn't contain our expected callback fn, bail
localVars = {}
with open(filePath) as inputFile:
code = compile(inputFile.read(), filePath, 'exec')
exec(code, localVars)
callBack = localVars.get(TEST_USD_VIEW_CALLBACK_IDENT)
if not callBack:
sys.stderr.write('Invalid file supplied, must contain a function of '
'the signature' + TEST_USD_VIEW_CALLBACK_IDENT +
'(appController): {}\n'.format(filePath))
sys.exit(1)
errorMsg = ('Invalid function signature, must be of the form: \n ' +
TEST_USD_VIEW_CALLBACK_IDENT + ' (appController)\n'
'File: ' + filePath + '\n'
'Error: %s')
if sys.version_info.major >= 3:
(args, varargs, keywords, defaults, _, _, _) = \
inspect.getfullargspec(callBack)
else:
(args, varargs, keywords, defaults) = inspect.getargspec(callBack)
assert not varargs, errorMsg % 'Varargs are disallowed'
assert not keywords, errorMsg % 'Kwargs are disallowed'
assert not defaults, errorMsg % 'Defaults are disallowed'
assert len(args) == 1, errorMsg % 'Incorrect number of args (1 expected)'
return callBack
# Monkey patch AppController to add helper test interface methods
def _processEvents(self, iterations=10, waitForConvergence=False):
# Qt does not guarantee that a single call to processEvents() will
# process all events in the event queue, and in some builds, on
# some platforms, we sporadically or even repeatably see test failures
# in which the selection does not change, presumably because the
# events were not all getting processed, when we simply called
# processEvents once. So we do it a handful of times whenever we
# generate an event, to increase our odds of success.
for x in range(iterations):
QtWidgets.QApplication.processEvents()
# Need to wait extra for progressive rendering images to converge
if (waitForConvergence):
# Wait until the image is converged
while not self._stageView._renderer.IsConverged():
QtWidgets.QApplication.processEvents()
AppController._processEvents = _processEvents
# Take a shot of the viewport and save it to a file.
def _takeShot(self, fileName, iterations=10, waitForConvergence=False):
self._processEvents(iterations, waitForConvergence)
viewportShot = self.GrabViewportShot()
viewportShot.save(fileName, "PNG")
AppController._takeShot = _takeShot
if __name__ == '__main__':
TestUsdView().Run()
+1
View File
@@ -0,0 +1 @@
@python "%~dp0testusdview" %*
+245
View File
@@ -0,0 +1,245 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
import argparse, sys, os
def _Msg(msg):
sys.stdout.write(msg + '\n')
def _Err(msg):
sys.stderr.write(msg + '\n')
def GetUsdData(filePath):
from pxr import Sdf
return Sdf.Layer.FindOrOpen(filePath)
def GetUsdLayerMetaData(filePath):
"""Return an SdfLayer holding just the layer metadata of the given layer."""
from pxr import Sdf, UsdUtils
srcLayer = Sdf.Layer.OpenAsAnonymous(filePath, metadataOnly=True)
# Not all file format plugins support metadata-only parsing.
# Create a new anonymous layer and copy just the layer metadata.
layer = Sdf.Layer.CreateAnonymous(filePath, Sdf.FileFormat.FindById('usda'))
UsdUtils.CopyLayerMetadata(srcLayer, layer)
return layer
def GetFlattenedUsdData(filePath, populationMaskPaths):
from pxr import Ar, Usd
if hasattr(Ar.Resolver, "ConfigureResolverForAsset"):
Ar.GetResolver().ConfigureResolverForAsset(filePath)
popMask = (None if populationMaskPaths is None
else Usd.StagePopulationMask())
if popMask:
for path in populationMaskPaths:
popMask.Add(path)
return Usd.Stage.OpenMasked(filePath, popMask)
else:
return Usd.Stage.Open(filePath)
def GetFlattenedLayerStack(filePath):
from pxr import Ar, Sdf, Pcp, Usd, UsdUtils
if hasattr(Ar.Resolver, "ConfigureResolverForAsset"):
Ar.GetResolver().ConfigureResolverForAsset(filePath)
stage = Usd.Stage.Open(filePath, Usd.Stage.LoadNone)
return UsdUtils.FlattenLayerStack(stage)
def main():
parser = argparse.ArgumentParser(
description='Write usd file(s) either as text to stdout or to a '
'specified output file.')
parser.add_argument('inputFiles', nargs='+')
parser.add_argument(
'-o', '--out', metavar='file', action='store',
help='Write a single input file to this output file instead of stdout.')
parser.add_argument(
'--usdFormat', metavar='usda|usdc', action='store',
help="Use this underlying file format "
"for output files with the extension 'usd'. For example, passing "
"'-o output.usd --usdFormat usda' will create output.usd as a text "
"file. The USD_DEFAULT_FILE_FORMAT environment variable is another "
"way to achieve this.")
parser.add_argument(
'-l', '--loadOnly', action='store_true',
help="Attempt to load the specified input files and report 'OK' or "
"'ERR' for each one. After all files are processed, this script will "
"exit with a non-zero exit code if any files failed to load.")
parser.add_argument(
'-f', '--flatten', action='store_true', help='Compose stages with the '
'input files as root layers and write their flattened content.')
parser.add_argument(
'--flattenLayerStack', action='store_true',
help='Flatten the layer stack with the given root layer, and write '
'out the result. Unlike --flatten, this does not flatten composition '
'arcs (such as references).')
parser.add_argument(
'--skipSourceFileComment', action='store_true',
help='If --flatten is specified, skip adding a comment regarding the '
'source of the flattened layer in the documentation field of the '
'output layer.')
parser.add_argument('--mask', action='store',
dest='populationMask',
metavar='PRIMPATH[,PRIMPATH...]',
help='Limit stage population to these prims, '
'their descendants and ancestors. To specify '
'multiple paths, either use commas with no spaces '
'or quote the argument and separate paths by '
'commas and/or spaces. Requires --flatten.')
parser.add_argument('--layerMetadata', action='store_true',
help='Load only layer metadata in the USD file. '
'This option cannot be combined with either '
'--flatten or --flattenStack')
args = parser.parse_args()
formatArgsDict = {}
# If --out was specified, it must either not exist or must be writable, the
# extension must correspond to a known Sdf file format, and we must have
# exactly one input file.
if args.out:
if os.path.isfile(args.out) and not os.access(args.out, os.W_OK):
_Err("%s: error: no write permission for existing output file '%s'"
% (parser.prog, args.out))
return 1
if len(args.inputFiles) != 1:
_Err("%s: error: must supply exactly one input file with -o/--out" %
parser.prog)
return 1
ext = os.path.splitext(args.out)[1][1:]
if args.usdFormat:
if ext != 'usd':
_Err("%s: error: use of --usdFormat requires output file end "
"with '.usd' extension" % parser.prog)
return 1
formatArgsDict.update(dict(format=args.usdFormat))
from pxr import Sdf
if Sdf.FileFormat.FindByExtension(ext) is None:
_Err("%s: error: unknown output file extension '.%s'"
% (parser.prog, ext))
return 1
# If --out was not specified, then --usdFormat must be unspecified or must
# be 'usda'.
elif args.usdFormat and args.usdFormat != 'usda':
_Err("%s: error: can only write 'usda' format to stdout; specify an "
"output file with -o/--out to write other formats" % parser.prog)
return 1
# split args.populationMask into paths.
if args.populationMask:
if not args.flatten:
# You can only mask a stage, not a layer.
_Err("%s: error: --mask requires --flatten" % parser.prog)
return 1
args.populationMask = args.populationMask.replace(',', ' ').split()
if args.layerMetadata:
if args.flatten:
# Cannot parse only metadata when flattening.
_Err("%s: error: --layerMetadata cannot be used "
"together with --flatten" % parser.prog)
if args.flattenLayerStack:
# Cannot parse only metadata when flattening.
_Err("%s: error: --layerMetadata cannot be used "
"together with --flattenLayerStack" % parser.prog)
from pxr import Usd
exitCode = 0
for inputFile in args.inputFiles:
# Either open a layer or compose a stage, depending on whether or not
# --flatten was specified. Note that 'usdData' will be either a
# Usd.Stage or an Sdf.Layer.
try:
if args.flatten:
usdData = GetFlattenedUsdData(inputFile, args.populationMask)
elif args.flattenLayerStack:
usdData = GetFlattenedLayerStack(inputFile)
elif args.layerMetadata:
usdData = GetUsdLayerMetaData(inputFile)
else:
usdData = GetUsdData(inputFile)
if not usdData:
raise Exception("Could not open layer")
if args.loadOnly:
_Msg("{:3} {}".format("OK", inputFile))
continue
except Exception as e:
if args.loadOnly:
_Msg("{:3} {}".format("ERR", inputFile))
_Msg("{}".format(e))
else:
_Err("Failed to open '%s' - %s" % (inputFile, e))
exitCode = 1
continue
# Write to either stdout or the specified output file
if args.out:
try:
if args.flatten:
usdData.Export(args.out,
addSourceFileComment=not args.skipSourceFileComment,
args=formatArgsDict)
else:
usdData.Export(args.out, args=formatArgsDict)
except Exception as e:
# Let the user know an error occurred.
_Err("Error exporting '%s' to '%s' - %s" %
(inputFile, args.out, e))
# If the output file exists, let's try to rename it with
# '.quarantine' appended and let the user know. Do this
# after the above error report because os.rename() can
# fail and we don't want to lose the above error.
if os.path.isfile(args.out):
newName = args.out + '.quarantine'
try:
os.rename(args.out, newName)
_Err("Possibly corrupt output file renamed to %s" %
(newName, ))
except Exception as e:
_Err("Failed to rename possibly corrupt output " +
"file from %s to %s" % (args.out, newName))
exitCode = 1
else:
try:
sys.stdout.write(usdData.ExportToString())
except Exception as e:
_Err("Error writing '%s' to stdout; %s" % (inputFile, e))
exitCode = 1
return exitCode
if __name__ == "__main__":
# Restore signal handling defaults to allow output redirection and the like.
import platform
if platform.system() != 'Windows':
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdcat" %*
+148
View File
@@ -0,0 +1,148 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import argparse
import itertools
import sys
from contextlib import contextmanager
from pxr import Ar, Sdf, Usd, UsdGeom, UsdShade, UsdUtils
class TermColors:
WARN = '\033[93m'
FAIL = '\033[91m'
END = '\033[0m'
@contextmanager
def _Stream(path, *args, **kwargs):
if path == '-':
yield sys.stdout
else:
with open(path, *args, **kwargs) as fp:
yield fp
def _Print(stream, msg):
print(msg, file=stream)
def _Err(msg):
sys.stderr.write(TermColors.FAIL + msg + TermColors.END + '\n')
def _Warn(msg):
sys.stderr.write(TermColors.WARN + msg + TermColors.END + '\n')
def main():
parser = argparse.ArgumentParser(description="""Utility for checking the
compliance of a given USD stage or a USDZ package. Only the first sample
of any relevant time-sampled attribute is checked, currently. General
USD checks are always performed, and more restrictive checks targeted at
distributable consumer content are also applied when the "--arkit" option
is specified.""")
parser.add_argument('inputFile', type=str, nargs='?',
help='Name of the input file to inspect.')
parser.add_argument('-s', '--skipVariants', dest='skipVariants',
action='store_true', help='If specified, only the prims'
' that are present in the default (i.e. selected) '
'variants are checked. When this option is not '
'specified, prims in all possible combinations of '
'variant selections are checked.')
parser.add_argument('-p', '--rootPackageOnly', dest='rootPackageOnly',
action="store_true", help='Check only the specified'
'package. Nested packages, dependencies and their '
'contents are not validated.')
parser.add_argument('-o', '--out', dest='outFile', type=str, nargs='?',
default='-', help='The file to which all the failed '
'checks are output. If unspecified, the failed checks '
'are output to stdout.')
parser.add_argument('--noAssetChecks', dest='noAssetChecks',
action='store_true', help='If specified, do NOT perform '
'extra checks to help ensure the stage or '
'package can be easily and safely referenced into '
'aggregate stages.')
parser.add_argument('--arkit', dest='arkit', action='store_true',
help='Check if the given USD stage is compatible with '
'ARKit\'s initial implementation of usdz. These assets '
'operate under greater constraints that usdz files for '
'more general in-house uses, and this option attempts '
'to ensure that these constraints are met.')
parser.add_argument('-d', '--dumpRules', dest='dumpRules',
action='store_true', help='Dump the enumerated set of '
'rules being checked for the given set of options.')
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
help='Enable verbose output mode.')
args = parser.parse_args()
inputFile = args.inputFile
outFile = args.outFile
checker = UsdUtils.ComplianceChecker(arkit=args.arkit,
skipARKitRootLayerCheck=False,
rootPackageOnly=args.rootPackageOnly,
skipVariants=args.skipVariants,
verbose=args.verbose,
assetLevelChecks=not args.noAssetChecks)
if not args.dumpRules and not args.inputFile:
parser.error("Either an inputFile or the --dumpRules option must be"
"specified.")
if args.dumpRules:
checker.DumpRules()
# If there's no input file to check, exit after dumping the rules.
if args.inputFile is None:
return 0
checker.CheckCompliance(inputFile)
warnings = checker.GetWarnings()
errors = checker.GetErrors()
failedChecks = checker.GetFailedChecks()
with _Stream(outFile, 'w') as ofp:
if len(warnings) > 0:
for msg in warnings:
# Add color if we're outputting to a terminal.
if outFile == '-':
msg = TermColors.WARN + msg + TermColors.END
_Print(ofp, msg)
if len(errors)> 0 or len(failedChecks) > 0:
for msg in errors + failedChecks:
# Add color if we're outputting to a terminal.
if outFile == '-':
msg = TermColors.FAIL + msg + TermColors.END
_Print(ofp, msg)
print("Failed!")
return 1
if len(warnings) > 0:
print("Success with warnings...")
else:
print("Success!")
return 0
if __name__ == '__main__':
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdchecker" %*
+375
View File
@@ -0,0 +1,375 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import difflib, os, sys
from subprocess import call
import platform
isWindows = (platform.system() == 'Windows')
NO_DIFF_FOUND_EXIT_CODE = 0
DIFF_FOUND_EXIT_CODE = 1
ERROR_EXIT_CODE = 2
def _exit(msg, exitCode):
if msg is not None:
sys.stderr.write(msg + "\n")
sys.exit(exitCode)
# generates a command list representing a call which will generate
# a temporary ascii file used during diffing.
def _generateCatCommand(usdcatCmd, inPath, outPath, flatten=None, fmt=None):
command = [usdcatCmd, inPath, '--out', outPath]
if flatten:
command.append('--flatten')
if fmt and os.path.splitext(outPath)[1] == '.usd':
command.append('--usdFormat')
command.append(fmt)
return command
def _findExe(name):
from distutils.spawn import find_executable
cmd = find_executable(name)
if cmd:
return cmd
else:
cmd = find_executable(name, path=os.path.abspath(os.path.dirname(sys.argv[0])))
if cmd:
return cmd
if isWindows:
# find_executable under Windows only returns *.EXE files
# so we need to traverse PATH.
for path in os.environ['PATH'].split(os.pathsep):
base = os.path.join(path, name)
# We need to test for name.cmd first because on Windows, the USD
# executables are wrapped due to lack of N*IX style shebang support
# on Windows.
for ext in ['.cmd', '']:
cmd = base + ext
if os.access(cmd, os.X_OK):
return cmd
return None
# looks up a suitable diff tool, and locates usdcat
def _findDiffTools():
usdcatCmd = _findExe("usdcat")
if not usdcatCmd:
_exit("Error: Could not find 'usdcat'. Expected it to be in PATH",
ERROR_EXIT_CODE)
# prefer USD_DIFF, then DIFF, else use the internal unified diff.
diffCmd = (os.environ.get('USD_DIFF') or os.environ.get('DIFF'))
diffCmdArgs = list()
if diffCmd:
diffCmdList = diffCmd.split()
diffCmd = diffCmdList[0]
if diffCmdList[1:]:
diffCmdArgs = diffCmdList[1:]
if diffCmd and not _findExe(diffCmd):
_exit("Error: Failed to find diff tool %s." % (diffCmd, ),
ERROR_EXIT_CODE)
return (usdcatCmd, diffCmd, diffCmdArgs)
def _getFileFormat(path):
from pxr import Sdf, Ar
# Note that python's os.path.splitext retains the '.' portion
# when obtaining an extension, but Sdf's Fileformat API doesn't
# expect one. We also make sure to prune out any version specifiers.
_, ext = os.path.splitext(path)
path = Ar.GetResolver().Resolve(path)
if path is None:
return None
if len(ext) <= 1:
fileFormat = Sdf.FileFormat.FindByExtension('usd')
else:
prunedExtension = ext[1:]
versionSpecifierPos = prunedExtension.rfind('#')
if versionSpecifierPos != -1:
prunedExtension = prunedExtension[:versionSpecifierPos]
fileFormat = Sdf.FileFormat.FindByExtension(prunedExtension)
# Don't check if file exists - this should be handled by resolver (and
# path may not exist / have been fetched yet)
if fileFormat:
return fileFormat.formatId
return None
def _convertTo(inPath, outPath, usdcatCmd, flatten=None, fmt=None):
# Just copy empty files -- we want something to diff against but
# the file isn't valid usd.
try:
if os.stat(inPath).st_size == 0:
import shutil
try:
shutil.copy(inPath, outPath)
return 0
except:
return 1
except (IOError, OSError):
# assume it's because file doesn't exist yet, because it's an unresolved
# path...
pass
return call(_generateCatCommand(usdcatCmd, inPath, outPath, flatten, fmt))
def _tryEdit(fileName, tempFileName, usdcatCmd, fileType, flattened):
if flattened:
_exit('Error: Cannot write out flattened result.', ERROR_EXIT_CODE)
if not os.access(fileName, os.W_OK):
_exit('Error: Cannot write to %s, insufficient permissions' % fileName,
ERROR_EXIT_CODE)
return _convertTo(tempFileName, fileName, usdcatCmd, flatten=None, fmt=fileType)
def _runDiff(baseline, comparison, flatten, noeffect, brief):
from pxr import Tf
diffResult = 0
usdcatCmd, diffCmd, diffCmdArgs = _findDiffTools()
baselineFileType = _getFileFormat(baseline)
comparisonFileType = _getFileFormat(comparison)
pluginError = 'Error: Cannot find supported file format plugin for %s'
if baselineFileType is None:
_exit(pluginError % baseline, ERROR_EXIT_CODE)
if comparisonFileType is None:
_exit(pluginError % comparison, ERROR_EXIT_CODE)
# Generate recognizable suffixes for our files in the temp dir
# location of the form /temp/string__originalFileName.usda
# where originalFileName is the basename(no extension) of the original file.
# This allows users to tell which file is which when diffing.
tempBaselineFileName = ("__" +
os.path.splitext(os.path.basename(baseline))[0] + '.usda')
tempComparisonFileName = ("__" +
os.path.splitext(os.path.basename(comparison))[0] + '.usda')
with Tf.NamedTemporaryFile(suffix=tempBaselineFileName) as tempBaseline, \
Tf.NamedTemporaryFile(suffix=tempComparisonFileName) as tempComparison:
# Dump the contents of our files into the temporaries
convertError = 'Error: failed to convert from %s to %s.'
if _convertTo(baseline, tempBaseline.name, usdcatCmd,
flatten, fmt=None) != 0:
_exit(convertError % (baseline, tempBaseline.name),
ERROR_EXIT_CODE)
if _convertTo(comparison, tempComparison.name, usdcatCmd,
flatten, fmt=None) != 0:
_exit(convertError % (comparison, tempComparison.name),
ERROR_EXIT_CODE)
tempBaselineTimestamp = os.path.getmtime(tempBaseline.name)
tempComparisonTimestamp = os.path.getmtime(tempComparison.name)
if diffCmd:
# Run the external diff tool.
if brief:
diffCmdArgs.append("--brief")
diffResult = call([diffCmd] + diffCmdArgs + [tempBaseline.name, tempComparison.name])
else:
# Read the files.
with open(tempBaseline.name, "r") as f:
baselineData = f.readlines()
with open(tempComparison.name, "r") as f:
comparisonData = f.readlines()
if baselineData != comparisonData:
if brief:
print("Files %s and %s differ" % (baseline, comparison))
else:
# Generate unified diff and output if there are any differences.
diff = list(difflib.unified_diff(
baselineData, comparisonData,
tempBaseline.name, tempComparison.name, n=0))
# Skip the file names.
for line in diff[2:]:
print(line, end='')
diffResult = 1
tempBaselineChanged = (
os.path.getmtime(tempBaseline.name) != tempBaselineTimestamp)
tempComparisonChanged = (
os.path.getmtime(tempComparison.name) != tempComparisonTimestamp)
# If we intend to edit either of the files
if not noeffect:
if tempBaselineChanged:
if _tryEdit(baseline, tempBaseline.name,
usdcatCmd, baselineFileType, flatten) != 0:
_exit(convertError % (baseline, tempBaseline.name),
ERROR_EXIT_CODE)
if tempComparisonChanged:
if _tryEdit(comparison, tempComparison.name,
usdcatCmd, comparisonFileType, flatten) != 0:
_exit(convertError % (comparison, tempComparison.name),
ERROR_EXIT_CODE)
return diffResult
def _findFiles(args):
'''Return a 3-tuple of lists: (baseline-only, matching, comparison-only).
baseline-only and comparison-only are lists of individual files, while
matching is a list of corresponding pairs of files.'''
import os
import stat
from pxr import Ar
join = os.path.join
basename = os.path.basename
exists = os.path.exists
def listFiles(dirpath):
ret = []
for root, _, files in os.walk(dirpath):
ret += [os.path.relpath(join(root, file), dirpath)
for file in files]
return set(ret)
# Must have FILE FILE, DIR DIR, DIR FILES... or FILES... DIR.
err = ValueError("Error: File arguments must be one of: "
"FILE FILE, DIR DIR, DIR FILES..., or FILES... DIR.")
if len(args) < 2:
raise err
# For speed, since filestats can be slow, stat all args once, then reuse that
# to determine isdir/isfile
resolver = Ar.GetResolver()
stats = []
for arg in args:
try:
st = os.stat(arg)
except (OSError, IOError):
if not resolver.Resolve(arg):
raise ValueError("Error: %s does not exist, and cannot be "
"resolved" % arg)
st = None
stats.append(st)
def isdir(st):
return st and stat.S_ISDIR(st.st_mode)
# if any of the directory forms are used, no paths may be unresolved assets
def validateFiles():
for i, st in enumerate(stats):
if st is None:
raise ValueError("Error: %s did not exist on disk, and using a "
"directory comparison form" % args[i])
# DIR FILES...
if isdir(stats[0]) and not any(map(isdir, stats[1:])):
validateFiles()
dirpath = args[0]
files = set(map(os.path.relpath, args[1:]))
dirfiles = listFiles(dirpath)
return ([],
[(join(dirpath, p), p) for p in files & dirfiles],
[p for p in files - dirfiles])
# FILES... DIR
elif not any(map(isdir, stats[:-1])) and isdir(stats[-1]):
validateFiles()
dirpath = args[-1]
files = set(map(os.path.relpath, args[:-1]))
dirfiles = listFiles(dirpath)
return ([p for p in files - dirfiles],
[(p, join(dirpath, p)) for p in files & dirfiles],
[])
# FILE FILE or DIR DIR
elif len(args) == 2:
# DIR DIR
if all(map(isdir, stats)):
ldir, rdir = args[0], args[1]
lhs, rhs = map(listFiles, args)
return (
# baseline only
sorted([join(ldir, p) for p in lhs - rhs]),
# corresponding
sorted([(join(ldir, p), join(rdir, p)) for p in lhs & rhs]),
# comparison only
sorted([join(rdir, p) for p in rhs - lhs]))
# FILE FILE
elif not any(map(isdir, stats)):
return ([], [(args[0], args[1])], [])
raise err
def main():
import argparse
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
description="Compares two usd-readable files using a selected"
" diff program. This is chosen by looking at the"
" $USD_DIFF environment variable. If this is unset,"
" it will consult the $DIFF environment variable. "
" Lastly, if neither of these is set, it will try"
" to use the canonical unix program, diff."
" This will relay the exit code of the selected"
" diff program.")
parser.add_argument('files', nargs='+',
help='The files to compare. These must be of the form '
'DIR DIR, FILE... DIR, DIR FILE... or FILE FILE. ')
parser.add_argument('-n', '--noeffect', action='store_true',
help='Do not edit either file.')
parser.add_argument('-f', '--flatten', action='store_true',
help='Fully compose both layers as Usd Stages and '
'flatten into single layers.')
parser.add_argument('-q', '--brief', action='store_true',
help='Do not return full results of diffs. Passes --brief to the diff command.')
results = parser.parse_args()
diffResult = NO_DIFF_FOUND_EXIT_CODE
try:
baselineOnly, common, comparisonOnly = _findFiles(results.files)
for (baseline, comparison) in common:
if _runDiff(baseline, comparison,
results.flatten, results.noeffect, results.brief):
diffResult = DIFF_FOUND_EXIT_CODE
mismatchMsg = 'No corresponding file found for %s, skipping.'
for b in baselineOnly:
print(mismatchMsg % b)
for c in comparisonOnly:
print(mismatchMsg % c)
except ValueError as err:
_exit(str(err), ERROR_EXIT_CODE)
_exit(None, diffResult)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usddiff" %*
+77
View File
@@ -0,0 +1,77 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import argparse, sys, os
from pxr import Sdf, Usd
def Err(msg):
print('Error: ' + msg, file=sys.stderr)
def PrintReport(fname, info, summaryOnly):
print('@%s@' % fname, 'file version', info.GetFileVersion())
ss = info.GetSummaryStats()
print (' %s specs, %s paths, %s tokens, %s strings, '
'%s fields, %s field sets' %
(ss.numSpecs, ss.numUniquePaths, ss.numUniqueTokens,
ss.numUniqueStrings, ss.numUniqueFields, ss.numUniqueFieldSets))
if summaryOnly:
return
print(' Structural Sections:')
for sec in info.GetSections():
print(' %16s %16d bytes at offset 0x%X' % (
sec.name, sec.size, sec.start))
print()
def main():
parser = argparse.ArgumentParser(
prog=os.path.basename(sys.argv[0]),
description='Write information about a usd crate (usdc) file to stdout')
parser.add_argument('inputFiles', nargs='+')
parser.add_argument('-s', '--summary', action='store_true',
help='report only a short summary')
args = parser.parse_args()
print('Usd crate software version', Usd.CrateInfo().GetSoftwareVersion())
for fname in args.inputFiles:
try:
info = Usd.CrateInfo.Open(fname)
if not info:
Err('Failed to read %s' % fname)
continue
except Exception as e:
Err('Failed to read %s\n %s' % (fname,e))
continue
PrintReport(fname, info, args.summary)
if __name__ == "__main__":
# Restore signal handling defaults to allow output redirection and the like.
import platform
if platform.system() != 'Windows':
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
main()
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usddumpcrate" %*
+231
View File
@@ -0,0 +1,231 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import os, sys
import platform
isWindows = (platform.system() == 'Windows')
def _findExe(name):
from distutils.spawn import find_executable
cmd = find_executable(name)
if cmd:
return cmd
else:
cmd = find_executable(name, path=os.path.abspath(os.path.dirname(sys.argv[0])))
if cmd:
return cmd
if isWindows:
# find_executable under Windows only returns *.EXE files
# so we need to traverse PATH.
for path in os.environ['PATH'].split(os.pathsep):
base = os.path.join(path, name)
# We need to test for name.cmd first because on Windows, the USD
# executables are wrapped due to lack of N*IX style shebang support
# on Windows.
for ext in ['.cmd', '']:
cmd = base + ext
if os.access(cmd, os.X_OK):
return cmd
return None
# lookup usdcat and a suitable text editor. if none are available,
# this will cause the program to abort with a suitable error message.
def _findEditorTools(usdFileName, readOnly):
# Ensure the usdcat executable has been installed
usdcatCmd = _findExe("usdcat")
if not usdcatCmd:
sys.exit("Error: Couldn't find 'usdcat'. Expected it to be in PATH.")
# Ensure we have a suitable editor available
editorCmd = (os.getenv("USD_EDITOR") or
os.getenv("EDITOR") or
_findExe("emacs") or
_findExe("vim") or
_findExe("notepad"))
if not editorCmd:
sys.exit("Error: Couldn't find a suitable text editor to use. Expected "
"$USD_EDITOR or $EDITOR to be set, or emacs/vim/notepad to "
"be installed and available in PATH.")
# special handling for emacs users
if 'emacs' in editorCmd:
title = '"usdedit %s%s"' % ("--noeffect " if readOnly else "",
usdFileName)
editorCmd += " -name %s" % title
return (usdcatCmd, editorCmd)
# this generates a temporary usd file which the user will edit.
def _generateTemporaryFile(usdcatCmd, usdFileName, readOnly, prefix):
# gets the base name of the USD file opened
usdFileNameBasename = os.path.splitext(os.path.basename(usdFileName))[0]
fullPrefix = prefix or usdFileNameBasename + "_tmp"
import tempfile
(usdaFile, usdaFileName) = tempfile.mkstemp(
prefix=fullPrefix, suffix='.usda', dir=os.getcwd())
# No need for an open file descriptor, as it locks the file in Windows.
os.close(usdaFile)
os.system(usdcatCmd + ' ' + usdFileName + '> ' + usdaFileName)
if readOnly:
os.chmod(usdaFileName, 0o444)
# Thrown if failed to open temp file Could be caused by
# failure to read USD file
if os.stat(usdaFileName).st_size == 0:
sys.exit("Error: Failed to open file %s, exiting." % usdFileName)
return usdaFileName
# allow the user to edit the temporary file, and return whether or
# not they made any changes.
def _editTemporaryFile(editorCmd, usdaFileName):
# check the timestamp before updating a file's mtime
initialTimeStamp = os.path.getmtime(usdaFileName)
os.system(editorCmd + ' ' + usdaFileName)
newTimeStamp = os.path.getmtime(usdaFileName)
# indicate whether the file was changed
return initialTimeStamp != newTimeStamp
# attempt to write out our changes to the actual usd file
def _writeOutChanges(temporaryFileName, permanentFileName):
from pxr import Sdf, Tf
try:
temporaryLayer = Sdf.Layer.FindOrOpen(temporaryFileName)
except Tf.ErrorException as err:
sys.exit("Error: Failed to open temporary layer %s, and therefore cannot save your edits back to original file %s"
". An error occurred trying to parse the file: %s" % (temporaryFileName, permanentFileName, str(err)))
# Note that we attempt to overwrite the permanent file's contents
# rather than explicitly creating a new layer. This avoids aligning
# file format paremeters from the original to the new.
outLayer = Sdf.Layer.FindOrOpen(permanentFileName)
if not outLayer:
sys.exit("Error: Unable to save edits back to the original file %s"
". Your edits can be found in %s." \
%(permanentFileName, temporaryFileName))
outLayer.TransferContent(temporaryLayer)
return outLayer.Save()
def main():
import argparse
parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]),
description= 'Convert a usd-readable file to the usd ascii format in \n'
'a temporary location and invoke an editor on it. After \n'
'saving and quitting the editor, the edited file will be \n'
'converted back to the original format and OVERWRITE the \n'
'original file, unless you supply the "-n" (--noeffect) flag, \n'
'in which case no changes will be saved back to the original '
'file. \n'
'The editor to use will be looked up as follows: \n'
' - USD_EDITOR environment variable \n'
' - EDITOR environment variable \n'
' - emacs in PATH \n'
' - vim in PATH \n'
' - notepad in PATH \n'
'\n\n')
parser.add_argument('-n', '--noeffect',
dest='readOnly', action='store_true',
help='Do not edit the file.')
parser.add_argument('-f', '--forcewrite',
dest='forceWrite', action='store_true',
help='Override file permissions to allow writing.')
parser.add_argument('-p', '--prefix',
dest='prefix', action='store', type=str, default=None,
help='Provide a prefix for the temporary file name.')
parser.add_argument('usdFileName', help='The usd file to edit.')
results = parser.parse_args()
# pull args from result map so we don't need to write result. for each
readOnly, forceWrite, usdFileName, prefix = (
results.readOnly,
results.forceWrite,
results.usdFileName,
results.prefix)
# verify our usd file exists, and permissions args are sane
if readOnly and forceWrite:
sys.exit("Error: Cannot set read only(-n) and force "
" write(-f) together.")
from pxr import Ar
resolvedPath = Ar.GetResolver().Resolve(usdFileName)
if not resolvedPath:
sys.exit("Error: Cannot find file %s" % usdFileName)
# Layers in packages cannot be written using the Sdf API.
from pxr import Ar, Sdf
(package, packaged) = Ar.SplitPackageRelativePathOuter(resolvedPath)
extension = Sdf.FileFormat.GetFileExtension(package)
fileFormat = Sdf.FileFormat.FindByExtension(extension)
if not fileFormat:
sys.exit("Error: Unknown file format")
if fileFormat.IsPackage():
print("Warning: Edits cannot be saved to layers in %s files. "
"Starting in no-effect mode." % extension)
readOnly = True
forceWrite = False
writable = os.path.isfile(usdFileName) and os.access(usdFileName, os.W_OK)
if not (writable or readOnly or forceWrite):
sys.exit("Error: File isn't writable, and "
"readOnly(-n)/forceWrite(-f) haven't been marked.")
# ensure we have both a text editor and usdcat available
usdcatCmd, editorCmd = _findEditorTools(usdFileName, readOnly)
# generate our temporary file with proper permissions and edit.
usdaFileName = _generateTemporaryFile(usdcatCmd, usdFileName,
readOnly, prefix)
tempFileChanged = _editTemporaryFile(editorCmd, usdaFileName)
if (not readOnly or forceWrite) and tempFileChanged:
# note that we need not overwrite usdFileName's write permissions
# because we will be creating a new layer at that path.
if not _writeOutChanges(temporaryFileName=usdaFileName,
permanentFileName=usdFileName):
sys.exit("Error: Unable to save edits back to the original file %s"
". Your edits can be found in %s. " \
%(usdFileName, usdaFileName))
if readOnly:
os.chmod(usdaFileName, 0o644)
os.remove(usdaFileName)
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdedit" %*
+172
View File
@@ -0,0 +1,172 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2019 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from pxr import Usd
from pxr import UsdAppUtils
from pxr import Tf
import argparse
import os
import sys
def _Msg(msg):
sys.stdout.write(msg + '\n')
def _Err(msg):
sys.stderr.write(msg + '\n')
def _SetupOpenGLContext(width=100, height=100):
try:
from PySide2 import QtOpenGL
from PySide2.QtWidgets import QApplication
except ImportError:
from PySide import QtOpenGL
from PySide.QtGui import QApplication
application = QApplication(sys.argv)
glFormat = QtOpenGL.QGLFormat()
glFormat.setSampleBuffers(True)
glFormat.setSamples(4)
glWidget = QtOpenGL.QGLWidget(glFormat)
glWidget.setFixedSize(width, height)
# note that we need to bind the gl context here, instead of explicitly
# showing the glWidget. Binding the gl context will make sure framebuffer is
# ready for gl operations.
glWidget.makeCurrent()
return glWidget
def main():
programName = os.path.basename(sys.argv[0])
parser = argparse.ArgumentParser(prog=programName,
description='Generates images from a USD file')
# Positional (required) arguments.
parser.add_argument('usdFilePath', action='store', type=str,
help='USD file to record')
parser.add_argument('outputImagePath', action='store', type=str,
help=(
'Output image path. For frame ranges, the path must contain '
'exactly one frame number placeholder of the form "###" or '
'"###.###". Note that the number of hash marks is variable in '
'each group.'))
# Optional arguments.
parser.add_argument('--mask', action='store', type=str,
dest='populationMask', metavar='PRIMPATH[,PRIMPATH...]',
help=(
'Limit stage population to these prims, their descendants and '
'ancestors. To specify multiple paths, either use commas with no '
'spaces or quote the argument and separate paths by commas and/or '
'spaces.'))
parser.add_argument('--purposes', action='store', type=str,
dest='purposes', metavar='PURPOSE[,PURPOSE...]', default='proxy',
help=(
'Specify which UsdGeomImageable purposes should be included '
'in the renders. The "default" purpose is automatically included, '
'so you need specify only the *additional* purposes. If you want '
'more than one extra purpose, either use commas with no spaces or '
'quote the argument and separate purposes by commas and/or spaces.'))
UsdAppUtils.cameraArgs.AddCmdlineArgs(parser)
UsdAppUtils.framesArgs.AddCmdlineArgs(parser)
UsdAppUtils.complexityArgs.AddCmdlineArgs(parser)
UsdAppUtils.colorArgs.AddCmdlineArgs(parser)
UsdAppUtils.rendererArgs.AddCmdlineArgs(parser)
parser.add_argument('--imageWidth', '-w', action='store', type=int,
default=960,
help=(
'Width of the output image. The height will be computed from this '
'value and the camera\'s aspect ratio (default=%(default)s)'))
args = parser.parse_args()
UsdAppUtils.framesArgs.ValidateCmdlineArgs(parser, args,
frameFormatArgName='outputImagePath')
args.imageWidth = max(args.imageWidth, 1)
purposes = args.purposes.replace(',', ' ').split()
# Open the USD stage, using a population mask if paths were given.
if args.populationMask:
populationMaskPaths = args.populationMask.replace(',', ' ').split()
populationMask = Usd.StagePopulationMask()
for maskPath in populationMaskPaths:
populationMask.Add(maskPath)
usdStage = Usd.Stage.OpenMasked(args.usdFilePath, populationMask)
else:
usdStage = Usd.Stage.Open(args.usdFilePath)
if not usdStage:
_Err('Could not open USD stage: %s' % args.usdFilePath)
return 1
# Get the camera at the given path (or with the given name).
usdCamera = UsdAppUtils.GetCameraAtPath(usdStage, args.camera)
# Frame-independent initialization.
# Note that the size of the widget doesn't actually affect the size of the
# output image. We just pass it along for cleanliness.
glWidget = _SetupOpenGLContext(args.imageWidth, args.imageWidth)
frameRecorder = UsdAppUtils.FrameRecorder()
if args.rendererPlugin:
frameRecorder.SetRendererPlugin(
UsdAppUtils.rendererArgs.GetPluginIdFromArgument(
args.rendererPlugin))
frameRecorder.SetImageWidth(args.imageWidth)
frameRecorder.SetComplexity(args.complexity.value)
frameRecorder.SetColorCorrectionMode(args.colorCorrectionMode)
frameRecorder.SetIncludedPurposes(purposes)
_Msg('Camera: %s' % usdCamera.GetPath().pathString)
_Msg('Renderer plugin: %s' % frameRecorder.GetCurrentRendererId())
for timeCode in args.frames:
_Msg('Recording time code: %s' % timeCode)
outputImagePath = args.outputImagePath.format(frame=timeCode.GetValue())
try:
frameRecorder.Record(usdStage, usdCamera, timeCode, outputImagePath)
except Tf.ErrorException as e:
_Err("Recording aborted due to the following failure at time code "
"{0}: {1}".format(timeCode, str(e)))
break
# Release our reference to the frame recorder so it can be deleted before
# the Qt stuff.
frameRecorder = None
if __name__ == '__main__':
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdrecord" %*
+141
View File
@@ -0,0 +1,141 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import argparse, sys, os
from pxr import Ar
def _HasCreateIdentifier():
return hasattr(Ar.Resolver, "CreateIdentifier")
def _HasConfigureResolverForAsset():
return hasattr(Ar.Resolver, "ConfigureResolverForAsset")
def _Msg(msg):
sys.stdout.write(msg + '\n')
def _Err(msg):
sys.stderr.write(msg + '\n')
def _ConfigureAssetResolver(args, resolver):
if _HasConfigureResolverForAsset():
configurePath = args.configureAssetPath or args.inputPath
resolver.ConfigureResolverForAsset(configurePath)
else:
if args.createContextForAsset:
return resolver.CreateDefaultContextForAsset(
args.createContextForAsset)
elif args.createContextFromString:
configStrs = []
for s in args.createContextFromString:
try:
uriScheme, config = s.split(":", 1)
configStrs.append((uriScheme, config))
except ValueError:
configStrs.append(("", s))
return resolver.CreateContextFromStrings(configStrs)
return resolver.CreateDefaultContextForAsset(args.inputPath)
def _AnchorRelativePath(args, resolver):
if args.anchorPath:
if _HasCreateIdentifier():
return resolver.CreateIdentifier(
args.inputPath, Ar.ResolvedPath(args.anchorPath))
elif resolver.IsRelativePath(args.inputPath):
return resolver.AnchorRelativePath(args.anchorPath, args.inputPath)
return args.inputPath
def main():
parser = argparse.ArgumentParser(
description='Resolves an asset path using a fully configured USD Asset Resolver.')
parser.add_argument('inputPath',
help="An asset path to be resolved by the USD Asset Resolver.")
if _HasConfigureResolverForAsset():
parser.add_argument(
'--configureAssetPath',
help="Run ConfigureResolverForAsset on the given asset path.")
else:
subparser = parser.add_mutually_exclusive_group()
subparser.add_argument(
'--createContextForAsset',
help=("Run CreateDefaultContextForAsset with the given asset path "
"to create the context used for resolution."))
subparser.add_argument(
'--createContextFromString', action='append',
help=("Run CreateContextFromString with the given string to create "
"the context used for resolution. This accepts strings like "
"[<URI Scheme>:]<Configuration String> and may be specified "
"multiple times.\n\n"
"ex: usdresolve --createContextFromString 'config_primary' "
"--createContextFromString 'my_uri_scheme:config_uri'"))
if _HasCreateIdentifier():
parser.add_argument(
'--anchorPath',
help=("Run CreateIdentifier with the input path and this anchor "
"asset path and resolve the result.\n\n"
"ex: usdresolve --anchorPath /asset/asset.usd sublayer.usd"))
else:
parser.add_argument(
'--anchorPath',
help="Run AnchorRelativePath on the given asset path.")
args = parser.parse_args()
exitCode = 0
resolver = Ar.GetResolver()
try:
resolverContext = _ConfigureAssetResolver(args, resolver)
with Ar.ResolverContextBinder(resolverContext):
inputPath = _AnchorRelativePath(args, resolver)
resolved = resolver.Resolve(inputPath)
except Exception as e:
_Err("Failed to resolve '%s' - %s" % (args.inputPath, e))
exitCode = 1
if not resolved:
_Err("Failed to resolve '%s'" % args.inputPath)
exitCode = 1
else:
print(resolved)
return exitCode
if __name__ == "__main__":
# Restore signal handling defaults to allow output redirection and the like.
import platform
if platform.system() != 'Windows':
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdresolve" %*
+76
View File
@@ -0,0 +1,76 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import argparse, os, sys
from pxr import UsdUtils, Sdf, Tf
parser = argparse.ArgumentParser( \
prog=sys.argv[0],
description='Stitch multiple usd file(s) together '
'into one. Opinion strength is determined by '
'the order in which the file is given, with the '
'first file getting the highest strength. '
'The exception to this general behavior is in '
'time samples, which are merged together as a '
'union across the input layers. It is consistent '
'in that, if two time sample keys conflict, the '
'strong layer takes precedence.')
parser.add_argument('usdFiles', nargs='+')
parser.add_argument('-o', '--out', action='store',
help='specify a file to write out to')
results = parser.parse_args()
assert results.out != None, "must specify output file"
if os.path.isfile(results.out):
print("Warning: overwriting pre-existing file")
# fold over the files, left file takes precedence on op. strength
outLayer = Sdf.Layer.CreateNew(results.out)
# open up all of the files into memory before stitching.
# if one is missing, this will allow us to fail without doing
#
# try opening all files
openedFiles = [Sdf.Layer.FindOrOpen(fname) for fname in results.usdFiles]
# grab the index of all, if any, files which failed to open
unopened = [i for i, unopened in enumerate(openedFiles) if unopened == None ]
# grab the filenames of the failed files for error messaging
erroredFiles = ' '.join([results.usdFiles[i] for i in unopened])
# if we failed to open any files, error out
assert len(unopened) == 0, 'unable to open file(s) %s' %erroredFiles
# the extra computation and fail more gracefully
try:
for usdFile in openedFiles:
UsdUtils.StitchLayers(outLayer, usdFile)
outLayer.Save()
# if something in the authoring fails, remove the output file
except Exception as e:
print('Failed to complete stitching, removing output file %s' % results.out)
print(e)
os.remove(results.out)
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdstitch" %*
+167
View File
@@ -0,0 +1,167 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import argparse, os, sys
from pxr import UsdUtils, Sdf, Tf
parser = argparse.ArgumentParser( \
prog=os.path.basename(sys.argv[0]),
description='Stitch multiple usd file(s) together '
'into one using value clips.\n'
'An example command is:\n\n'
'usdstitchclips --out result.usd --clipPath '
'/World/fx/Particles_Splash clip1.usd clip2.usd '
'\n\n'
'This will produce two files, a result.topology.usd '
'and a result.usd.',
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('usdFiles', nargs='+')
parser.add_argument('-o', '--out', action='store',
help='specify the filename for the top-level result file, which also serves as base-name for the topology and manifest files.')
parser.add_argument('-c', '--clipPath', action='store',
help='specify a prim path at which to begin stitching clip data.')
parser.add_argument('-s', '--startTimeCode', action='store',
help='specify the time at which the clips will become active')
parser.add_argument('-r', '--stride', action='store',
help='specify a stride for the numeric component of filenames for template metadata')
parser.add_argument('-e', '--endTimeCode', action='store',
help='specify the time at which the clips will cease being active')
parser.add_argument('-t', '--templateMetadata', action='store_true',
help='author template clip metadata in the root layer.')
parser.add_argument('-p', '--templatePath', action='store',
help='specify a template asset path to author')
parser.add_argument('--clipSet', action='store',
help='specify a named clipSet in which to author clip metadata, so that multiple sets of clips can be applied on the same prim.')
parser.add_argument('--activeOffset', action='store', required=False,
help='specify an offset for template-based clips, offsetting the frame number of each clip file.')
parser.add_argument('--interpolateMissingClipValues', action='store_true',
help=('specify whether values for clips without authored '
'samples are interpolated from surrounding clips '
'if no default value is authored in any clip.'))
# useful for debugging with diffs
parser.add_argument('-n', '--noComment', action='store_true',
help='do not write a comment specifying how the usd file was generated')
results = parser.parse_args()
# verify the integrity of the inputs
assert results.out is not None, "must specify output file(--out)"
assert results.clipPath is not None, "must specify a clip path(--clipPath)"
assert results.usdFiles is not None, "must specify clip files"
if os.path.isfile(results.out):
print("Warning: merging with current result layer")
outLayerGenerated = False
topologyLayerGenerated = False
topologyLayerName = ""
try:
outLayer = Sdf.Layer.FindOrOpen(results.out)
if not outLayer:
outLayerGenerated = True
outLayer = Sdf.Layer.CreateNew(results.out)
topologyLayerName = UsdUtils.GenerateClipTopologyName(results.out)
topologyLayer = Sdf.Layer.FindOrOpen(topologyLayerName)
if not topologyLayer:
topologyLayerGenerated = True
topologyLayer = Sdf.Layer.CreateNew(topologyLayerName)
manifestLayerName = UsdUtils.GenerateClipManifestName(results.out)
manifestLayer = Sdf.Layer.FindOrOpen(manifestLayerName)
if not manifestLayer:
manifestLayerGenerated = True
manifestLayer = Sdf.Layer.CreateNew(manifestLayerName)
if results.startTimeCode:
results.startTimeCode = float(results.startTimeCode)
if results.endTimeCode:
results.endTimeCode = float(results.endTimeCode)
if results.stride:
results.stride = float(results.stride)
if results.activeOffset:
results.activeOffset = float(results.activeOffset)
if results.templateMetadata:
def _checkMissingTemplateArg(argName, argValue):
if not argValue:
raise Tf.ErrorException('Error: %s must be specified '
'when --templateMetadata is' % argName)
_checkMissingTemplateArg('templatePath', results.templatePath)
_checkMissingTemplateArg('endTimeCode', results.endTimeCode)
_checkMissingTemplateArg('startTimeCode', results.startTimeCode)
_checkMissingTemplateArg('stride', results.stride)
UsdUtils.StitchClipsTopology(topologyLayer, results.usdFiles)
UsdUtils.StitchClipsManifest(manifestLayer, topologyLayer,
results.usdFiles, results.clipPath)
UsdUtils.StitchClipsTemplate(outLayer,
topologyLayer,
manifestLayer,
results.clipPath,
results.templatePath,
results.startTimeCode,
results.endTimeCode,
results.stride,
results.activeOffset,
results.interpolateMissingClipValues,
results.clipSet)
else:
if results.templatePath:
raise Tf.ErrorException('Error: templatePath cannot be specified '
'without --templateMetadata')
if results.activeOffset:
raise Tf.ErrorException('Error: activeOffset cannot be specified '
'without --templateMetadata')
if results.stride:
raise Tf.ErrorException('Error: stride cannot be specified '
'without --templateMetadata')
UsdUtils.StitchClips(outLayer, results.usdFiles, results.clipPath,
results.startTimeCode, results.endTimeCode,
results.interpolateMissingClipValues,
results.clipSet)
if not results.noComment:
outLayer.comment = 'Generated with ' + ' '.join(sys.argv)
outLayer.Save()
except Tf.ErrorException as e:
# if something in the authoring fails, remove the output file
if outLayerGenerated and os.path.isfile(results.out):
os.remove(results.out)
if topologyLayerGenerated and os.path.isfile(topologyLayerName):
os.remove(topologyLayerName)
if manifestLayerGenerated and os.path.isfile(manifestLayerName):
os.remove(manifestLayerName)
sys.exit(e)
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdstitchclips" %*
+313
View File
@@ -0,0 +1,313 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
import argparse
import os
import sys
from pxr import Usd
METADATA_KEYS_TO_SKIP = ('typeName', 'specifier', 'kind', 'active')
def _Msg(msg):
sys.stdout.write(msg + '\n')
def _Err(msg):
sys.stderr.write(msg + '\n')
class USDAccessor(object):
@staticmethod
def GetChildren(prim):
return prim.GetAllChildren()
@staticmethod
def GetProperties(prim):
return prim.GetAuthoredProperties()
@staticmethod
def GetPropertyName(prop):
return prop.GetName()
@staticmethod
def GetMetadata(prim):
return prim.GetAllAuthoredMetadata().keys()
@staticmethod
def GetName(prim):
return prim.GetName()
@staticmethod
def GetTypeName(prim):
return prim.GetTypeName()
@staticmethod
def GetSpecifier(prim):
return prim.GetSpecifier()
@staticmethod
def GetKind(prim):
return Usd.ModelAPI(prim).GetKind()
@staticmethod
def HasAuthoredActive(prim):
return prim.HasAuthoredActive()
@staticmethod
def IsActive(prim):
return prim.IsActive()
class SdfAccessor(object):
@staticmethod
def GetChildren(prim):
return prim.nameChildren
@staticmethod
def GetProperties(prim):
return prim.properties
@staticmethod
def GetPropertyName(prop):
return prop.name
@staticmethod
def GetMetadata(prim):
return prim.ListInfoKeys()
@staticmethod
def GetName(prim):
return prim.name
@staticmethod
def GetTypeName(prim):
return prim.typeName
@staticmethod
def GetSpecifier(prim):
return prim.specifier
@staticmethod
def GetKind(prim):
return prim.kind
@staticmethod
def HasAuthoredActive(prim):
return 'active' in prim.ListInfoKeys()
@staticmethod
def IsActive(prim):
return prim.active
def GetPrimLabel(acc, prim):
spec = acc.GetSpecifier(prim).displayName.lower()
typeName = acc.GetTypeName(prim)
if typeName:
definition = '{} {}'.format(spec, typeName)
else:
definition = spec
label = '{} [{}]'.format(acc.GetName(prim), definition)
shortMetadata = []
if not acc.IsActive(prim):
shortMetadata.append('active = false')
elif acc.HasAuthoredActive(prim):
shortMetadata.append('active = true')
kind = acc.GetKind(prim)
if kind:
shortMetadata.append('kind = {}'.format(kind))
if shortMetadata:
label += ' ({})'.format(', '.join(shortMetadata))
return label
def PrintPrim(args, acc, prim, prefix, isLast):
if not isLast:
lastStep = ' |--'
if acc.GetChildren(prim):
attrStep = ' | |'
else:
attrStep = ' | '
else:
lastStep = ' `--'
if acc.GetChildren(prim):
attrStep = ' |'
else:
attrStep = ' '
if args.simple:
label = acc.GetName(prim)
else:
label = GetPrimLabel(acc, prim)
_Msg('{}{}{}'.format(prefix, lastStep, label))
attrs = []
if args.metadata:
mdKeys = filter(lambda x: x not in METADATA_KEYS_TO_SKIP, sorted(acc.GetMetadata(prim)))
attrs.extend('({})'.format(md) for md in mdKeys)
if args.attributes:
attrs.extend('.{}'.format(acc.GetPropertyName(prop)) for prop in acc.GetProperties(prim))
numAttrs = len(attrs)
for i, attr in enumerate(attrs):
if i < numAttrs - 1:
_Msg('{}{} :--{}'.format(prefix, attrStep, attr))
else:
_Msg('{}{} `--{}'.format(prefix, attrStep, attr))
def PrintChildren(args, acc, prim, prefix):
children = acc.GetChildren(prim)
numChildren = len(children)
for i, child in enumerate(children):
if i < numChildren - 1:
PrintPrim(args, acc, child, prefix, isLast=False)
PrintChildren(args, acc, child, prefix + ' | ')
else:
PrintPrim(args, acc, child, prefix, isLast=True)
PrintChildren(args, acc, child, prefix + ' ')
def PrintStage(args, stage):
_Msg('/')
PrintChildren(args, USDAccessor, stage.GetPseudoRoot(), '')
def PrintLayer(args, layer):
_Msg('/')
PrintChildren(args, SdfAccessor, layer.pseudoRoot, '')
def PrintTree(args, path):
if args.flatten:
popMask = (None if args.populationMask is None else Usd.StagePopulationMask())
if popMask:
for mask in args.populationMask:
popMask.Add(mask)
if popMask:
if args.unloaded:
stage = Usd.Stage.OpenMasked(path, popMask, Usd.Stage.LoadNone)
else:
stage = Usd.Stage.OpenMasked(path, popMask)
else:
if args.unloaded:
stage = Usd.Stage.Open(path, Usd.Stage.LoadNone)
else:
stage = Usd.Stage.Open(path)
PrintStage(args, stage)
elif args.flattenLayerStack:
from pxr import UsdUtils
stage = Usd.Stage.Open(path, Usd.Stage.LoadNone)
layer = UsdUtils.FlattenLayerStack(stage)
PrintLayer(args, layer)
else:
from pxr import Sdf
layer = Sdf.Layer.FindOrOpen(path)
PrintLayer(args, layer)
def main():
parser = argparse.ArgumentParser(
description='''Writes the tree structure of a USD file. The default is to inspect a single USD file.
Use the --flatten argument to see the flattened (or composed) Stage tree.
Special metadata "kind" and "active" are always shown if authored unless --simple is provided.''')
parser.add_argument('inputPath')
parser.add_argument(
'--unloaded', action='store_true',
dest='unloaded',
help='Do not load payloads')
parser.add_argument(
'--attributes', '-a', action='store_true',
dest='attributes',
help='Display authored attributes')
parser.add_argument(
'--metadata', '-m', action='store_true',
dest='metadata',
help='Display authored metadata (active and kind are part of the label and not shown as individual items)')
parser.add_argument(
'--simple', '-s', action='store_true',
dest='simple',
help='Only display prim names: no specifier, kind or active state.')
parser.add_argument(
'--flatten', '-f', action='store_true', help='Compose the stage with the '
'input file as root layer and write the flattened content.')
parser.add_argument(
'--flattenLayerStack', action='store_true',
help='Flatten the layer stack with the given root layer. '
'Unlike --flatten, this does not flatten composition arcs (such as references).')
parser.add_argument('--mask', action='store',
dest='populationMask',
metavar='PRIMPATH[,PRIMPATH...]',
help='Limit stage population to these prims, '
'their descendants and ancestors. To specify '
'multiple paths, either use commas with no spaces '
'or quote the argument and separate paths by '
'commas and/or spaces. Requires --flatten.')
args = parser.parse_args()
# split args.populationMask into paths.
if args.populationMask:
if not args.flatten:
# You can only mask a stage, not a layer.
_Err("%s: error: --mask requires --flatten" % parser.prog)
return 1
args.populationMask = args.populationMask.replace(',', ' ').split()
from pxr import Ar
resolver = Ar.GetResolver()
try:
if hasattr(Ar.Resolver, "ConfigureResolverForAsset"):
resolver.ConfigureResolverForAsset(args.inputPath)
resolverContext = resolver.CreateDefaultContextForAsset(args.inputPath)
with Ar.ResolverContextBinder(resolverContext):
resolved = resolver.Resolve(args.inputPath)
if not resolved:
_Err('Cannot resolve inputPath %r'%resolved)
return 1
PrintTree(args, resolved)
except Exception as e:
_Err("Failed to process '%s' - %s" % (args.inputPath, e))
return 1
return 0
if __name__ == "__main__":
# Restore signal handling defaults to allow output redirection and the like.
import platform
if platform.system() != 'Windows':
import signal
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdtree" %*
+38
View File
@@ -0,0 +1,38 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import sys
import pxr.Usdviewq as Usdviewq
if __name__ == '__main__':
# Let Ctrl-C kill the app.
import signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
try:
Usdviewq.Launcher().Run()
except Usdviewq.InvalidUsdviewOption as e:
print("ERROR: " + e.message, file=sys.stderr)
sys.exit(1)
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdview" %*
+295
View File
@@ -0,0 +1,295 @@
#!C:/Users/sebastien/AppData/Local/Programs/Python/Python39/python.exe
#
# Copyright 2018 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
# 6. Trademarks. This License does not grant permission to use the trade
# names, trademarks, service marks, or product names of the Licensor
# and its affiliates, except as required to comply with Section 4(c) of
# the License and to reproduce the content of the NOTICE file.
#
# You may obtain a copy of the Apache License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the Apache License with the above modification is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the Apache License for the specific
# language governing permissions and limitations under the Apache License.
#
from __future__ import print_function
import argparse
import glob
import os
import sys
from pxr import Ar, Sdf, Tf, Usd, UsdUtils
from contextlib import contextmanager
@contextmanager
def _Stream(path, *args, **kwargs):
if path == '-':
yield sys.stdout
else:
with open(path, *args, **kwargs) as fp:
yield fp
def _Print(stream, msg):
print(msg, file=stream)
def _Err(msg):
sys.stderr.write(msg + '\n')
def _CheckCompliance(rootLayer, arkit=False):
checker = UsdUtils.ComplianceChecker(arkit=arkit,
# We're going to flatten the USD stage and convert the root layer to
# crate file format before packaging, if necessary. Hence, skip these
# checks.
skipARKitRootLayerCheck=True)
checker.CheckCompliance(rootLayer)
errors = checker.GetErrors()
failedChecks = checker.GetFailedChecks()
warnings = checker.GetWarnings()
for msg in errors + failedChecks:
_Err(msg)
if len(warnings) > 0:
_Err("*********************************************\n"
"Possible correctness problems to investigate:\n"
"*********************************************\n")
for msg in warnings:
_Err(msg)
return len(errors) == 0 and len(failedChecks) == 0
def _CreateUsdzPackage(usdzFile, filesToAdd, recurse, checkCompliance, verbose):
with Usd.ZipFileWriter.CreateNew(usdzFile) as usdzWriter:
fileList = []
while filesToAdd:
# Pop front (first file) from the list of files to add.
f = filesToAdd[0]
filesToAdd = filesToAdd[1:]
if os.path.isdir(f):
# If a directory is specified, add all files in the directory.
filesInDir = glob.glob(os.path.join(f, '*'))
# If the recurse flag is not specified, remove sub-directories.
if not recurse:
filesInDir = [f for f in filesInDir if not os.path.isdir(f)]
# glob.glob returns files in arbitrary order. Hence, sort them
# here to get consistent ordering of files in the package.
filesInDir.sort()
filesToAdd += filesInDir
else:
if verbose:
print('.. adding: %s' % f)
if os.path.getsize(f) > 0:
fileList.append(f)
else:
_Err("Skipping empty file '%s'." % f)
if checkCompliance and len(fileList) > 0:
rootLayer = fileList[0]
if not _CheckCompliance(rootLayer):
return False
for f in fileList:
try:
usdzWriter.AddFile(f)
except Tf.ErrorException as e:
_Err('Failed to add file \'%s\' to package. Discarding '
'package.' % f)
# When the "with" block exits, Discard() will be called on
# usdzWriter automatically if an exception occurs.
raise
return True
def _DumpContents(dumpLocation, zipFile):
with _Stream(dumpLocation, "w") as ofp:
_Print(ofp, " Offset\t Comp\t Uncomp\tName")
_Print(ofp, " ------\t ----\t ------\t----")
fileNames = zipFile.GetFileNames()
for fileName in fileNames:
fileInfo = zipFile.GetFileInfo(fileName)
_Print(ofp, "%10d\t%10d\t%10d\t%s" %
(fileInfo.dataOffset, fileInfo.size,
fileInfo.uncompressedSize, fileName))
_Print(ofp, "----------")
_Print(ofp, "%d files total" % len(fileNames))
def _ListContents(listLocation, zipFile):
with _Stream(listLocation, "w") as ofp:
for fileName in zipFile.GetFileNames():
_Print(ofp, fileName)
def main():
parser = argparse.ArgumentParser(description='Utility for creating a .usdz '
'file containing USD assets and for inspecting existing .usdz files.')
parser.add_argument('usdzFile', type=str, nargs='?',
help='Name of the .usdz file to create or to inspect '
'the contents of.')
parser.add_argument('inputFiles', type=str, nargs='*',
help='Files to include in the .usdz file.')
parser.add_argument('-r', '--recurse', dest='recurse', action='store_true',
help='If specified, files in sub-directories are '
'recursively added to the package.')
parser.add_argument('-a', '--asset', dest='asset', type=str,
help='Resolvable asset path pointing to the root layer '
'of the asset to be isolated and copied into the '
'package.')
parser.add_argument("--arkitAsset", dest="arkitAsset", type=str,
help="Similar to the --asset option, the --arkitAsset "
"option packages all of the dependencies of the named "
"scene file. Assets targeted at the initial usdz "
"implementation in ARKit operate under greater "
"constraints than usdz files for more general 'in "
"house' uses, and this option attempts to ensure that "
"these constraints are honored; this may involve more "
"transformations to the data, which may cause loss of "
"features such as VariantSets.")
parser.add_argument('-c', '--checkCompliance', dest='checkCompliance',
action='store_true', help='Perform compliance checking '
'of the input files. If the input asset or \"root\" '
'layer fails any of the compliance checks, the package '
'is not created and the program fails.')
parser.add_argument('-l', '--list', dest='listTarget', type=str,
nargs='?', default=None, const='-',
help='List contents of the specified usdz file. If '
'a file-path argument is provided, the list is output '
'to a file at the given path. If no argument is '
'provided or if \'-\' is specified as the argument, the'
' list is output to stdout.')
parser.add_argument('-d', '--dump', dest='dumpTarget', type=str,
nargs='?', default=None, const='-',
help='Dump contents of the specified usdz file. If '
'a file-path argument is provided, the contents are '
'output to a file at the given path. If no argument is '
'provided or if \'-\' is specified as the argument, the'
' contents are output to stdout.')
parser.add_argument('-v', '--verbose', dest='verbose', action='store_true',
help='Enable verbose mode, which causes messages '
'regarding files being added to the package to be '
'output to stdout.')
args = parser.parse_args()
usdzFile = args.usdzFile
inputFiles = args.inputFiles
if args.asset and args.arkitAsset:
parser.error("Specify either --asset or --arkitAsset, not both.")
elif (args.arkitAsset or args.asset) and len(inputFiles)>0:
parser.error("Specify either inputFiles or an asset (via --asset or "
"--arkitAsset, not both.")
# If usdzFile is not specified directly as an argument, check if it has been
# specified as an argument to the --list or --dump options. In these cases,
# output the list or the contents to stdout.
if not usdzFile:
if args.listTarget and args.listTarget != '-' and \
args.listTarget.endswith('.usdz') and \
os.path.exists(args.listTarget):
usdzFile = args.listTarget
args.listTarget = '-'
elif args.dumpTarget and args.dumpTarget != '-' and \
args.dumpTarget.endswith('.usdz') and \
os.path.exists(args.dumpTarget):
usdzFile = args.dumpTarget
args.dumpTarget = '-'
else:
parser.error("No usdz file specified!")
# Check if we're in package creation mode and verbose mode is enabled,
# print some useful information.
if (args.asset or args.arkitAsset or len(inputFiles)>0):
# Ensure that the usdz file has the right extension.
if not usdzFile.endswith('.usdz'):
usdzFile += '.usdz'
if args.verbose:
if os.path.exists(usdzFile):
print("File at path '%s' already exists. Overwriting file." %
usdzFile)
if args.inputFiles:
print('Creating package \'%s\' with files %s.' %
(usdzFile, inputFiles))
if args.asset or args.arkitAsset:
Tf.Debug.SetDebugSymbolsByName("USDUTILS_CREATE_USDZ_PACKAGE", 1)
if not args.recurse:
print('Not recursing into sub-directories.')
else:
if args.checkCompliance:
parser.error("--checkCompliance should only be specified when "
"creating a usdz package. Please use 'usdchecker' to check "
"compliance of an existing .usdz file.")
success = True
if len(inputFiles) > 0:
success = _CreateUsdzPackage(usdzFile, inputFiles, args.recurse,
args.checkCompliance, args.verbose) and success
elif args.asset:
r = Ar.GetResolver()
resolvedAsset = r.Resolve(args.asset)
if args.checkCompliance:
success = _CheckCompliance(resolvedAsset, arkit=False) and success
context = r.CreateDefaultContextForAsset(resolvedAsset)
with Ar.ResolverContextBinder(context):
# Create the package only if the compliance check was passed.
success = success and UsdUtils.CreateNewUsdzPackage(
Sdf.AssetPath(args.asset), usdzFile)
elif args.arkitAsset:
r = Ar.GetResolver()
resolvedAsset = r.Resolve(args.arkitAsset)
if args.checkCompliance:
success = _CheckCompliance(resolvedAsset, arkit=True) and success
context = r.CreateDefaultContextForAsset(resolvedAsset)
with Ar.ResolverContextBinder(context):
# Create the package only if the compliance check was passed.
success = success and UsdUtils.CreateNewARKitUsdzPackage(
Sdf.AssetPath(args.arkitAsset), usdzFile)
if args.listTarget or args.dumpTarget:
if os.path.exists(usdzFile):
zipFile = Usd.ZipFile.Open(usdzFile)
if zipFile:
if args.dumpTarget:
if args.dumpTarget == usdzFile:
_Err("The file into which to dump the contents of the "
"usdz file '%s' must be different from the file "
"itself." % usdzFile)
return 1
_DumpContents(args.dumpTarget, zipFile)
if args.listTarget:
if args.listTarget == usdzFile:
_Err("The file into which to list the contents of the "
"usdz file '%s' must be different from the file "
"itself." % usdzFile)
return 1
_ListContents(args.listTarget, zipFile)
else:
_Err("Failed to open usdz file at path '%s'." % usdzFile)
else:
_Err("Can't find usdz file at path '%s'." % usdzFile)
return 0 if success else 1
if __name__ == '__main__':
sys.exit(main())
+1
View File
@@ -0,0 +1 @@
@python "%~dp0usdzip" %*
BIN
View File
Binary file not shown.
+469
View File
@@ -0,0 +1,469 @@
#----------------------------------------------------------------
# Generated CMake target import file for configuration "Release".
#----------------------------------------------------------------
# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)
# Import target "arch" for configuration "Release"
set_property(TARGET arch APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(arch PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_arch.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_arch.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS arch )
list(APPEND _IMPORT_CHECK_FILES_FOR_arch "${_IMPORT_PREFIX}/lib/usd_arch.lib" "${_IMPORT_PREFIX}/lib/usd_arch.dll" )
# Import target "tf" for configuration "Release"
set_property(TARGET tf APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(tf PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_tf.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_tf.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS tf )
list(APPEND _IMPORT_CHECK_FILES_FOR_tf "${_IMPORT_PREFIX}/lib/usd_tf.lib" "${_IMPORT_PREFIX}/lib/usd_tf.dll" )
# Import target "gf" for configuration "Release"
set_property(TARGET gf APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(gf PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_gf.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_gf.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS gf )
list(APPEND _IMPORT_CHECK_FILES_FOR_gf "${_IMPORT_PREFIX}/lib/usd_gf.lib" "${_IMPORT_PREFIX}/lib/usd_gf.dll" )
# Import target "js" for configuration "Release"
set_property(TARGET js APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(js PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_js.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_js.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS js )
list(APPEND _IMPORT_CHECK_FILES_FOR_js "${_IMPORT_PREFIX}/lib/usd_js.lib" "${_IMPORT_PREFIX}/lib/usd_js.dll" )
# Import target "trace" for configuration "Release"
set_property(TARGET trace APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(trace PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_trace.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_trace.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS trace )
list(APPEND _IMPORT_CHECK_FILES_FOR_trace "${_IMPORT_PREFIX}/lib/usd_trace.lib" "${_IMPORT_PREFIX}/lib/usd_trace.dll" )
# Import target "work" for configuration "Release"
set_property(TARGET work APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(work PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_work.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_work.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS work )
list(APPEND _IMPORT_CHECK_FILES_FOR_work "${_IMPORT_PREFIX}/lib/usd_work.lib" "${_IMPORT_PREFIX}/lib/usd_work.dll" )
# Import target "plug" for configuration "Release"
set_property(TARGET plug APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(plug PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_plug.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_plug.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS plug )
list(APPEND _IMPORT_CHECK_FILES_FOR_plug "${_IMPORT_PREFIX}/lib/usd_plug.lib" "${_IMPORT_PREFIX}/lib/usd_plug.dll" )
# Import target "vt" for configuration "Release"
set_property(TARGET vt APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(vt PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_vt.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_vt.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS vt )
list(APPEND _IMPORT_CHECK_FILES_FOR_vt "${_IMPORT_PREFIX}/lib/usd_vt.lib" "${_IMPORT_PREFIX}/lib/usd_vt.dll" )
# Import target "ar" for configuration "Release"
set_property(TARGET ar APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(ar PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_ar.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_ar.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS ar )
list(APPEND _IMPORT_CHECK_FILES_FOR_ar "${_IMPORT_PREFIX}/lib/usd_ar.lib" "${_IMPORT_PREFIX}/lib/usd_ar.dll" )
# Import target "kind" for configuration "Release"
set_property(TARGET kind APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(kind PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_kind.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_kind.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS kind )
list(APPEND _IMPORT_CHECK_FILES_FOR_kind "${_IMPORT_PREFIX}/lib/usd_kind.lib" "${_IMPORT_PREFIX}/lib/usd_kind.dll" )
# Import target "sdf" for configuration "Release"
set_property(TARGET sdf APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(sdf PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_sdf.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_sdf.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS sdf )
list(APPEND _IMPORT_CHECK_FILES_FOR_sdf "${_IMPORT_PREFIX}/lib/usd_sdf.lib" "${_IMPORT_PREFIX}/lib/usd_sdf.dll" )
# Import target "ndr" for configuration "Release"
set_property(TARGET ndr APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(ndr PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_ndr.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_ndr.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS ndr )
list(APPEND _IMPORT_CHECK_FILES_FOR_ndr "${_IMPORT_PREFIX}/lib/usd_ndr.lib" "${_IMPORT_PREFIX}/lib/usd_ndr.dll" )
# Import target "sdr" for configuration "Release"
set_property(TARGET sdr APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(sdr PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_sdr.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_sdr.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS sdr )
list(APPEND _IMPORT_CHECK_FILES_FOR_sdr "${_IMPORT_PREFIX}/lib/usd_sdr.lib" "${_IMPORT_PREFIX}/lib/usd_sdr.dll" )
# Import target "pcp" for configuration "Release"
set_property(TARGET pcp APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(pcp PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_pcp.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_pcp.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS pcp )
list(APPEND _IMPORT_CHECK_FILES_FOR_pcp "${_IMPORT_PREFIX}/lib/usd_pcp.lib" "${_IMPORT_PREFIX}/lib/usd_pcp.dll" )
# Import target "usd" for configuration "Release"
set_property(TARGET usd APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usd PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usd.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usd.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usd )
list(APPEND _IMPORT_CHECK_FILES_FOR_usd "${_IMPORT_PREFIX}/lib/usd_usd.lib" "${_IMPORT_PREFIX}/lib/usd_usd.dll" )
# Import target "usdGeom" for configuration "Release"
set_property(TARGET usdGeom APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdGeom PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdGeom.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdGeom.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdGeom )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdGeom "${_IMPORT_PREFIX}/lib/usd_usdGeom.lib" "${_IMPORT_PREFIX}/lib/usd_usdGeom.dll" )
# Import target "usdVol" for configuration "Release"
set_property(TARGET usdVol APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdVol PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdVol.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdVol.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdVol )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdVol "${_IMPORT_PREFIX}/lib/usd_usdVol.lib" "${_IMPORT_PREFIX}/lib/usd_usdVol.dll" )
# Import target "usdMedia" for configuration "Release"
set_property(TARGET usdMedia APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdMedia PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdMedia.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdMedia.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdMedia )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdMedia "${_IMPORT_PREFIX}/lib/usd_usdMedia.lib" "${_IMPORT_PREFIX}/lib/usd_usdMedia.dll" )
# Import target "usdShade" for configuration "Release"
set_property(TARGET usdShade APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdShade PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdShade.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdShade.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdShade )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdShade "${_IMPORT_PREFIX}/lib/usd_usdShade.lib" "${_IMPORT_PREFIX}/lib/usd_usdShade.dll" )
# Import target "usdLux" for configuration "Release"
set_property(TARGET usdLux APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdLux PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdLux.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdLux.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdLux )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdLux "${_IMPORT_PREFIX}/lib/usd_usdLux.lib" "${_IMPORT_PREFIX}/lib/usd_usdLux.dll" )
# Import target "usdRender" for configuration "Release"
set_property(TARGET usdRender APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdRender PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdRender.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdRender.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdRender )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdRender "${_IMPORT_PREFIX}/lib/usd_usdRender.lib" "${_IMPORT_PREFIX}/lib/usd_usdRender.dll" )
# Import target "usdHydra" for configuration "Release"
set_property(TARGET usdHydra APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdHydra PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdHydra.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdHydra.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdHydra )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdHydra "${_IMPORT_PREFIX}/lib/usd_usdHydra.lib" "${_IMPORT_PREFIX}/lib/usd_usdHydra.dll" )
# Import target "usdRi" for configuration "Release"
set_property(TARGET usdRi APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdRi PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdRi.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdRi.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdRi )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdRi "${_IMPORT_PREFIX}/lib/usd_usdRi.lib" "${_IMPORT_PREFIX}/lib/usd_usdRi.dll" )
# Import target "usdSkel" for configuration "Release"
set_property(TARGET usdSkel APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdSkel PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdSkel.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdSkel.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdSkel )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdSkel "${_IMPORT_PREFIX}/lib/usd_usdSkel.lib" "${_IMPORT_PREFIX}/lib/usd_usdSkel.dll" )
# Import target "usdUI" for configuration "Release"
set_property(TARGET usdUI APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdUI PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdUI.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdUI.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdUI )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdUI "${_IMPORT_PREFIX}/lib/usd_usdUI.lib" "${_IMPORT_PREFIX}/lib/usd_usdUI.dll" )
# Import target "usdUtils" for configuration "Release"
set_property(TARGET usdUtils APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdUtils PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdUtils.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdUtils.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdUtils )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdUtils "${_IMPORT_PREFIX}/lib/usd_usdUtils.lib" "${_IMPORT_PREFIX}/lib/usd_usdUtils.dll" )
# Import target "usdPhysics" for configuration "Release"
set_property(TARGET usdPhysics APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdPhysics PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdPhysics.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdPhysics.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdPhysics )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdPhysics "${_IMPORT_PREFIX}/lib/usd_usdPhysics.lib" "${_IMPORT_PREFIX}/lib/usd_usdPhysics.dll" )
# Import target "garch" for configuration "Release"
set_property(TARGET garch APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(garch PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_garch.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_garch.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS garch )
list(APPEND _IMPORT_CHECK_FILES_FOR_garch "${_IMPORT_PREFIX}/lib/usd_garch.lib" "${_IMPORT_PREFIX}/lib/usd_garch.dll" )
# Import target "hf" for configuration "Release"
set_property(TARGET hf APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(hf PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_hf.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_hf.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS hf )
list(APPEND _IMPORT_CHECK_FILES_FOR_hf "${_IMPORT_PREFIX}/lib/usd_hf.lib" "${_IMPORT_PREFIX}/lib/usd_hf.dll" )
# Import target "hio" for configuration "Release"
set_property(TARGET hio APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(hio PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_hio.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_hio.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS hio )
list(APPEND _IMPORT_CHECK_FILES_FOR_hio "${_IMPORT_PREFIX}/lib/usd_hio.lib" "${_IMPORT_PREFIX}/lib/usd_hio.dll" )
# Import target "cameraUtil" for configuration "Release"
set_property(TARGET cameraUtil APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(cameraUtil PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_cameraUtil.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_cameraUtil.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS cameraUtil )
list(APPEND _IMPORT_CHECK_FILES_FOR_cameraUtil "${_IMPORT_PREFIX}/lib/usd_cameraUtil.lib" "${_IMPORT_PREFIX}/lib/usd_cameraUtil.dll" )
# Import target "pxOsd" for configuration "Release"
set_property(TARGET pxOsd APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(pxOsd PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_pxOsd.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_pxOsd.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS pxOsd )
list(APPEND _IMPORT_CHECK_FILES_FOR_pxOsd "${_IMPORT_PREFIX}/lib/usd_pxOsd.lib" "${_IMPORT_PREFIX}/lib/usd_pxOsd.dll" )
# Import target "glf" for configuration "Release"
set_property(TARGET glf APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(glf PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_glf.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_glf.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS glf )
list(APPEND _IMPORT_CHECK_FILES_FOR_glf "${_IMPORT_PREFIX}/lib/usd_glf.lib" "${_IMPORT_PREFIX}/lib/usd_glf.dll" )
# Import target "hgi" for configuration "Release"
set_property(TARGET hgi APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(hgi PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_hgi.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_hgi.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS hgi )
list(APPEND _IMPORT_CHECK_FILES_FOR_hgi "${_IMPORT_PREFIX}/lib/usd_hgi.lib" "${_IMPORT_PREFIX}/lib/usd_hgi.dll" )
# Import target "hgiGL" for configuration "Release"
set_property(TARGET hgiGL APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(hgiGL PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_hgiGL.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_hgiGL.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS hgiGL )
list(APPEND _IMPORT_CHECK_FILES_FOR_hgiGL "${_IMPORT_PREFIX}/lib/usd_hgiGL.lib" "${_IMPORT_PREFIX}/lib/usd_hgiGL.dll" )
# Import target "hgiInterop" for configuration "Release"
set_property(TARGET hgiInterop APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(hgiInterop PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_hgiInterop.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_hgiInterop.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS hgiInterop )
list(APPEND _IMPORT_CHECK_FILES_FOR_hgiInterop "${_IMPORT_PREFIX}/lib/usd_hgiInterop.lib" "${_IMPORT_PREFIX}/lib/usd_hgiInterop.dll" )
# Import target "hd" for configuration "Release"
set_property(TARGET hd APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(hd PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_hd.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_hd.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS hd )
list(APPEND _IMPORT_CHECK_FILES_FOR_hd "${_IMPORT_PREFIX}/lib/usd_hd.lib" "${_IMPORT_PREFIX}/lib/usd_hd.dll" )
# Import target "hdSt" for configuration "Release"
set_property(TARGET hdSt APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(hdSt PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_hdSt.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_hdSt.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS hdSt )
list(APPEND _IMPORT_CHECK_FILES_FOR_hdSt "${_IMPORT_PREFIX}/lib/usd_hdSt.lib" "${_IMPORT_PREFIX}/lib/usd_hdSt.dll" )
# Import target "hdx" for configuration "Release"
set_property(TARGET hdx APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(hdx PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_hdx.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_hdx.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS hdx )
list(APPEND _IMPORT_CHECK_FILES_FOR_hdx "${_IMPORT_PREFIX}/lib/usd_hdx.lib" "${_IMPORT_PREFIX}/lib/usd_hdx.dll" )
# Import target "usdImaging" for configuration "Release"
set_property(TARGET usdImaging APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdImaging PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdImaging.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdImaging.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdImaging )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdImaging "${_IMPORT_PREFIX}/lib/usd_usdImaging.lib" "${_IMPORT_PREFIX}/lib/usd_usdImaging.dll" )
# Import target "usdImagingGL" for configuration "Release"
set_property(TARGET usdImagingGL APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdImagingGL PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdImagingGL.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdImagingGL.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdImagingGL )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdImagingGL "${_IMPORT_PREFIX}/lib/usd_usdImagingGL.lib" "${_IMPORT_PREFIX}/lib/usd_usdImagingGL.dll" )
# Import target "usdRiImaging" for configuration "Release"
set_property(TARGET usdRiImaging APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdRiImaging PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdRiImaging.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdRiImaging.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdRiImaging )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdRiImaging "${_IMPORT_PREFIX}/lib/usd_usdRiImaging.lib" "${_IMPORT_PREFIX}/lib/usd_usdRiImaging.dll" )
# Import target "usdSkelImaging" for configuration "Release"
set_property(TARGET usdSkelImaging APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdSkelImaging PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdSkelImaging.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdSkelImaging.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdSkelImaging )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdSkelImaging "${_IMPORT_PREFIX}/lib/usd_usdSkelImaging.lib" "${_IMPORT_PREFIX}/lib/usd_usdSkelImaging.dll" )
# Import target "usdVolImaging" for configuration "Release"
set_property(TARGET usdVolImaging APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdVolImaging PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdVolImaging.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdVolImaging.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdVolImaging )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdVolImaging "${_IMPORT_PREFIX}/lib/usd_usdVolImaging.lib" "${_IMPORT_PREFIX}/lib/usd_usdVolImaging.dll" )
# Import target "usdAppUtils" for configuration "Release"
set_property(TARGET usdAppUtils APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdAppUtils PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdAppUtils.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdAppUtils.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdAppUtils )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdAppUtils "${_IMPORT_PREFIX}/lib/usd_usdAppUtils.lib" "${_IMPORT_PREFIX}/lib/usd_usdAppUtils.dll" )
# Import target "usdviewq" for configuration "Release"
set_property(TARGET usdviewq APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE)
set_target_properties(usdviewq PROPERTIES
IMPORTED_IMPLIB_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdviewq.lib"
IMPORTED_LOCATION_RELEASE "${_IMPORT_PREFIX}/lib/usd_usdviewq.dll"
)
list(APPEND _IMPORT_CHECK_TARGETS usdviewq )
list(APPEND _IMPORT_CHECK_FILES_FOR_usdviewq "${_IMPORT_PREFIX}/lib/usd_usdviewq.lib" "${_IMPORT_PREFIX}/lib/usd_usdviewq.dll" )
# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)
+531
View File
@@ -0,0 +1,531 @@
# Generated by CMake
if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.5)
message(FATAL_ERROR "CMake >= 2.6.0 required")
endif()
cmake_policy(PUSH)
cmake_policy(VERSION 2.6...3.19)
#----------------------------------------------------------------
# Generated CMake target import file.
#----------------------------------------------------------------
# Commands may need to know the format version.
set(CMAKE_IMPORT_FILE_VERSION 1)
# Protect against multiple inclusion, which would fail when already imported targets are added once more.
set(_targetsDefined)
set(_targetsNotDefined)
set(_expectedTargets)
foreach(_expectedTarget arch tf gf js trace work plug vt ar kind sdf ndr sdr pcp usd usdGeom usdVol usdMedia usdShade usdLux usdRender usdHydra usdRi usdSkel usdUI usdUtils usdPhysics garch hf hio cameraUtil pxOsd glf hgi hgiGL hgiInterop hd hdSt hdx usdImaging usdImagingGL usdRiImaging usdSkelImaging usdVolImaging usdAppUtils usdviewq)
list(APPEND _expectedTargets ${_expectedTarget})
if(NOT TARGET ${_expectedTarget})
list(APPEND _targetsNotDefined ${_expectedTarget})
endif()
if(TARGET ${_expectedTarget})
list(APPEND _targetsDefined ${_expectedTarget})
endif()
endforeach()
if("${_targetsDefined}" STREQUAL "${_expectedTargets}")
unset(_targetsDefined)
unset(_targetsNotDefined)
unset(_expectedTargets)
set(CMAKE_IMPORT_FILE_VERSION)
cmake_policy(POP)
return()
endif()
if(NOT "${_targetsDefined}" STREQUAL "")
message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_targetsDefined}\nTargets not yet defined: ${_targetsNotDefined}\n")
endif()
unset(_targetsDefined)
unset(_targetsNotDefined)
unset(_expectedTargets)
# Compute the installation prefix relative to this file.
get_filename_component(_IMPORT_PREFIX "${CMAKE_CURRENT_LIST_FILE}" PATH)
get_filename_component(_IMPORT_PREFIX "${_IMPORT_PREFIX}" PATH)
if(_IMPORT_PREFIX STREQUAL "/")
set(_IMPORT_PREFIX "")
endif()
# Create imported target arch
add_library(arch SHARED IMPORTED)
set_target_properties(arch PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "Ws2_32.lib;Dbghelp.lib"
)
# Create imported target tf
add_library(tf SHARED IMPORTED)
set_target_properties(tf PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/Users/sebastien/AppData/Local/Programs/Python/Python39/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "arch;Shlwapi.lib;C:/Users/sebastien/AppData/Local/Programs/Python/Python39/libs/python39.lib;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/Users/sebastien/AppData/Local/Programs/Python/Python39/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target gf
add_library(gf SHARED IMPORTED)
set_target_properties(gf PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "arch;tf"
)
# Create imported target js
add_library(js SHARED IMPORTED)
set_target_properties(js PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "tf"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target trace
add_library(trace SHARED IMPORTED)
set_target_properties(trace PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "arch;js;tf;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target work
add_library(work SHARED IMPORTED)
set_target_properties(work PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "tf;trace;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include"
)
# Create imported target plug
add_library(plug SHARED IMPORTED)
set_target_properties(plug PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "arch;tf;js;trace;work;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target vt
add_library(vt SHARED IMPORTED)
set_target_properties(vt PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "arch;tf;gf;trace;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target ar
add_library(ar SHARED IMPORTED)
set_target_properties(ar PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "arch;tf;plug;vt;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target kind
add_library(kind SHARED IMPORTED)
set_target_properties(kind PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "tf;plug"
)
# Create imported target sdf
add_library(sdf SHARED IMPORTED)
set_target_properties(sdf PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "arch;tf;gf;trace;vt;work;ar;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target ndr
add_library(ndr SHARED IMPORTED)
set_target_properties(ndr PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "tf;plug;vt;work;ar;sdf;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target sdr
add_library(sdr SHARED IMPORTED)
set_target_properties(sdr PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "tf;vt;ar;ndr;sdf;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target pcp
add_library(pcp SHARED IMPORTED)
set_target_properties(pcp PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "tf;trace;vt;sdf;work;ar;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target usd
add_library(usd SHARED IMPORTED)
set_target_properties(usd PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "arch;kind;pcp;sdf;ar;plug;tf;trace;vt;work;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target usdGeom
add_library(usdGeom SHARED IMPORTED)
set_target_properties(usdGeom PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "js;tf;plug;vt;sdf;trace;usd;work;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target usdVol
add_library(usdVol SHARED IMPORTED)
set_target_properties(usdVol PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "tf;usd;usdGeom"
)
# Create imported target usdMedia
add_library(usdMedia SHARED IMPORTED)
set_target_properties(usdMedia PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "tf;vt;sdf;usd;usdGeom"
)
# Create imported target usdShade
add_library(usdShade SHARED IMPORTED)
set_target_properties(usdShade PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "tf;vt;sdf;ndr;sdr;usd;usdGeom"
)
# Create imported target usdLux
add_library(usdLux SHARED IMPORTED)
set_target_properties(usdLux PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "tf;vt;ndr;sdf;usd;usdGeom;usdShade"
)
# Create imported target usdRender
add_library(usdRender SHARED IMPORTED)
set_target_properties(usdRender PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "gf;tf;usd;usdGeom"
)
# Create imported target usdHydra
add_library(usdHydra SHARED IMPORTED)
set_target_properties(usdHydra PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "tf;usd;usdShade"
)
# Create imported target usdRi
add_library(usdRi SHARED IMPORTED)
set_target_properties(usdRi PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "tf;vt;sdf;usd;usdShade;usdGeom;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target usdSkel
add_library(usdSkel SHARED IMPORTED)
set_target_properties(usdSkel PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "arch;gf;tf;trace;vt;work;sdf;usd;usdGeom;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target usdUI
add_library(usdUI SHARED IMPORTED)
set_target_properties(usdUI PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "tf;vt;sdf;usd"
)
# Create imported target usdUtils
add_library(usdUtils SHARED IMPORTED)
set_target_properties(usdUtils PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "arch;tf;gf;sdf;usd;usdGeom;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target usdPhysics
add_library(usdPhysics SHARED IMPORTED)
set_target_properties(usdPhysics PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "js;tf;plug;vt;sdf;trace;usd;usdGeom;work;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70;C:/dev/USD/include"
)
# Create imported target garch
add_library(garch SHARED IMPORTED)
set_target_properties(garch PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "arch;tf;opengl32"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target hf
add_library(hf SHARED IMPORTED)
set_target_properties(hf PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "plug;tf;trace"
)
# Create imported target hio
add_library(hio SHARED IMPORTED)
set_target_properties(hio PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "arch;js;plug;tf;vt;trace;ar;hf"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target cameraUtil
add_library(cameraUtil SHARED IMPORTED)
set_target_properties(cameraUtil PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "tf;gf"
)
# Create imported target pxOsd
add_library(pxOsd SHARED IMPORTED)
set_target_properties(pxOsd PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "tf;gf;vt;C:/dev/USD/lib/osdCPU.lib;C:/dev/USD/lib/osdGPU.lib;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include"
)
# Create imported target glf
add_library(glf SHARED IMPORTED)
set_target_properties(glf PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "ar;arch;garch;gf;hf;hio;js;plug;tf;trace;sdf;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;opengl32"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target hgi
add_library(hgi SHARED IMPORTED)
set_target_properties(hgi PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "gf;plug;tf"
)
# Create imported target hgiGL
add_library(hgiGL SHARED IMPORTED)
set_target_properties(hgiGL PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "arch;garch;hgi;tf;trace"
)
# Create imported target hgiInterop
add_library(hgiInterop SHARED IMPORTED)
set_target_properties(hgiInterop PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "gf;tf;hgi;vt;garch"
)
# Create imported target hd
add_library(hd SHARED IMPORTED)
set_target_properties(hd PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "plug;tf;trace;vt;work;sdf;cameraUtil;hf;pxOsd;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include"
)
# Create imported target hdSt
add_library(hdSt SHARED IMPORTED)
set_target_properties(hdSt PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "hio;garch;glf;hd;hgiGL;sdr;tf;trace;C:/dev/USD/lib/osdCPU.lib;C:/dev/USD/lib/osdGPU.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include"
)
# Create imported target hdx
add_library(hdx SHARED IMPORTED)
set_target_properties(hdx PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "plug;tf;vt;gf;work;garch;glf;pxOsd;hd;hdSt;hgi;hgiInterop;cameraUtil;sdf"
)
# Create imported target usdImaging
add_library(usdImaging SHARED IMPORTED)
set_target_properties(usdImaging PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "gf;tf;plug;trace;vt;work;hd;pxOsd;sdf;usd;usdGeom;usdLux;usdShade;usdVol;ar;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include"
)
# Create imported target usdImagingGL
add_library(usdImagingGL SHARED IMPORTED)
set_target_properties(usdImagingGL PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/Users/sebastien/AppData/Local/Programs/Python/Python39/include;C:/Users/sebastien/AppData/Local/Programs/Python/Python39/include;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "gf;tf;plug;trace;vt;work;hio;garch;glf;hd;hdx;pxOsd;sdf;sdr;usd;usdGeom;usdHydra;usdShade;usdImaging;ar;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib;C:/Users/sebastien/AppData/Local/Programs/Python/Python39/libs/python39.lib;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/Users/sebastien/AppData/Local/Programs/Python/Python39/include;C:/Users/sebastien/AppData/Local/Programs/Python/Python39/include;C:/dev/USD/include"
)
# Create imported target usdRiImaging
add_library(usdRiImaging SHARED IMPORTED)
set_target_properties(usdRiImaging PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include"
INTERFACE_LINK_LIBRARIES "gf;tf;plug;trace;vt;work;hd;pxOsd;sdf;usd;usdGeom;usdLux;usdShade;usdImaging;usdVol;ar;C:/dev/USD/lib/tbb.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include"
)
# Create imported target usdSkelImaging
add_library(usdSkelImaging SHARED IMPORTED)
set_target_properties(usdSkelImaging PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "hio;hd;usdImaging;usdSkel"
)
# Create imported target usdVolImaging
add_library(usdVolImaging SHARED IMPORTED)
set_target_properties(usdVolImaging PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include"
INTERFACE_LINK_LIBRARIES "usdImaging"
)
# Create imported target usdAppUtils
add_library(usdAppUtils SHARED IMPORTED)
set_target_properties(usdAppUtils PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "garch;gf;hio;sdf;tf;usd;usdGeom;usdImagingGL;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
# Create imported target usdviewq
add_library(usdviewq SHARED IMPORTED)
set_target_properties(usdviewq PROPERTIES
INTERFACE_COMPILE_DEFINITIONS "PXR_PYTHON_ENABLED=1"
INTERFACE_INCLUDE_DIRECTORIES "${_IMPORT_PREFIX}/include;C:/dev/USD/include/boost-1_70"
INTERFACE_LINK_LIBRARIES "tf;usd;usdGeom;C:/dev/USD/lib/boost_python39-vc142-mt-x64-1_70.lib"
INTERFACE_SYSTEM_INCLUDE_DIRECTORIES "C:/dev/USD/include/boost-1_70"
)
if(CMAKE_VERSION VERSION_LESS 2.8.12)
message(FATAL_ERROR "This file relies on consumers using CMake 2.8.12 or greater.")
endif()
# Load information for each installed configuration.
get_filename_component(_DIR "${CMAKE_CURRENT_LIST_FILE}" PATH)
file(GLOB CONFIG_FILES "${_DIR}/pxrTargets-*.cmake")
foreach(f ${CONFIG_FILES})
include(${f})
endforeach()
# Cleanup temporary variables.
set(_IMPORT_PREFIX)
# Loop over all imported files and verify that they actually exist
foreach(target ${_IMPORT_CHECK_TARGETS} )
foreach(file ${_IMPORT_CHECK_FILES_FOR_${target}} )
if(NOT EXISTS "${file}" )
message(FATAL_ERROR "The imported target \"${target}\" references the file
\"${file}\"
but this file does not exist. Possible reasons include:
* The file was deleted, renamed, or moved to another location.
* An install or uninstall procedure did not complete successfully.
* The installation package was faulty and contained
\"${CMAKE_CURRENT_LIST_FILE}\"
but not all the files it references.
")
endif()
endforeach()
unset(_IMPORT_CHECK_FILES_FOR_${target})
endforeach()
unset(_IMPORT_CHECK_TARGETS)
# This file does not depend on other imported targets which have
# been exported from the same project but in a separate export set.
# Commands beyond this point should not need to know the version.
set(CMAKE_IMPORT_FILE_VERSION)
cmake_policy(POP)
@@ -0,0 +1,27 @@
///////////////////////////////////////////////////////////////////////////////
/// \file accumulators.hpp
/// Includes all of the Accumulators Framework
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_ACCUMULATORS_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_ACCUMULATORS_HPP_EAN_28_10_2005
#include <boost/accumulators/framework/accumulator_set.hpp>
#include <boost/accumulators/framework/accumulator_concept.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/external.hpp>
#include <boost/accumulators/framework/features.hpp>
#include <boost/accumulators/framework/parameters/accumulator.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/parameters/weight.hpp>
#include <boost/accumulators/framework/parameters/weights.hpp>
#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>
#include <boost/accumulators/framework/accumulators/droppable_accumulator.hpp>
#include <boost/accumulators/framework/accumulators/reference_accumulator.hpp>
#include <boost/accumulators/framework/accumulators/value_accumulator.hpp>
#endif
@@ -0,0 +1,230 @@
///////////////////////////////////////////////////////////////////////////////
// accumulators_fwd.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_ACCUMULATORS_FWD_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_ACCUMULATORS_FWD_HPP_EAN_28_10_2005
#include <boost/config.hpp>
#include <boost/mpl/apply_fwd.hpp> // for mpl::na
#include <boost/mpl/limits/vector.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/repetition/enum_params_with_a_default.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/accumulators/numeric/functional_fwd.hpp>
#ifndef BOOST_ACCUMULATORS_MAX_FEATURES
/// The maximum number of accumulators that may be put in an accumulator_set.
/// Defaults to BOOST_MPL_LIMIT_VECTOR_SIZE (which defaults to 20).
# define BOOST_ACCUMULATORS_MAX_FEATURES BOOST_MPL_LIMIT_VECTOR_SIZE
#endif
#if BOOST_ACCUMULATORS_MAX_FEATURES > BOOST_MPL_LIMIT_VECTOR_SIZE
# error BOOST_ACCUMULATORS_MAX_FEATURES cannot be larger than BOOST_MPL_LIMIT_VECTOR_SIZE
#endif
#ifndef BOOST_ACCUMULATORS_MAX_ARGS
/// The maximum number of arguments that may be specified to an accumulator_set's
/// accumulation function. Defaults to 15.
# define BOOST_ACCUMULATORS_MAX_ARGS 15
#endif
#if BOOST_WORKAROUND(__GNUC__, == 3) \
|| BOOST_WORKAROUND(__EDG_VERSION__, BOOST_TESTED_AT(306))
# define BOOST_ACCUMULATORS_BROKEN_CONST_OVERLOADS
#endif
#ifdef BOOST_ACCUMULATORS_BROKEN_CONST_OVERLOADS
# include <boost/utility/enable_if.hpp>
# include <boost/type_traits/is_const.hpp>
# define BOOST_ACCUMULATORS_PROTO_DISABLE_IF_IS_CONST(T)\
, typename boost::disable_if<boost::is_const<T> >::type * = 0
#else
# define BOOST_ACCUMULATORS_PROTO_DISABLE_IF_IS_CONST(T)
#endif
#define BOOST_ACCUMULATORS_GCC_VERSION \
(__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
namespace boost { namespace accumulators
{
///////////////////////////////////////////////////////////////////////////////
// Named parameters tags
//
namespace tag
{
struct sample;
struct weight;
struct accumulator;
struct weights;
}
///////////////////////////////////////////////////////////////////////////////
// User-level features
//
namespace tag
{
template<typename ValueType, typename Tag>
struct value;
template<typename Tag>
struct value_tag;
template<typename Referent, typename Tag>
struct reference;
template<typename Tag>
struct reference_tag;
template<typename Type, typename Tag = void, typename AccumulatorSet = void>
struct external;
template<typename Feature>
struct droppable;
}
template<typename Accumulator>
struct droppable_accumulator_base;
template<typename Accumulator>
struct droppable_accumulator;
template<typename Accumulator>
struct with_cached_result;
template<typename Sample, typename Features, typename Weight = void>
struct accumulator_set;
template<typename Feature>
struct extractor;
template<typename Feature>
struct feature_of;
template<typename Feature>
struct as_feature;
template<typename Feature>
struct as_weighted_feature;
template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(BOOST_ACCUMULATORS_MAX_FEATURES, typename Feature, mpl::na)>
struct depends_on;
template<BOOST_PP_ENUM_PARAMS_WITH_A_DEFAULT(BOOST_ACCUMULATORS_MAX_FEATURES, typename Feature, mpl::na)>
struct features;
template<typename Feature, typename AccumulatorSet>
typename mpl::apply<AccumulatorSet, Feature>::type const &
find_accumulator(AccumulatorSet const &acc);
template<typename Feature, typename AccumulatorSet>
typename mpl::apply<AccumulatorSet, Feature>::type::result_type
extract_result(AccumulatorSet const &acc);
template<typename Feature, typename AccumulatorSet, typename A1>
typename mpl::apply<AccumulatorSet, Feature>::type::result_type
extract_result(AccumulatorSet const &acc, A1 const &a1);
// ... other overloads generated by Boost.Preprocessor:
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_EXTRACT_RESULT_FWD(z, n, _) \
template< \
typename Feature \
, typename AccumulatorSet \
BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A) \
> \
typename mpl::apply<AccumulatorSet, Feature>::type::result_type \
extract_result( \
AccumulatorSet const &acc \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a) \
);
/// INTERNAL ONLY
///
BOOST_PP_REPEAT_FROM_TO(
2
, BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
, BOOST_ACCUMULATORS_EXTRACT_RESULT_FWD
, _
)
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
template<typename Feature, typename AccumulatorSet, typename A1, typename A2 ...>
typename mpl::apply<AccumulatorSet, Feature>::type::result_type
extract_result(AccumulatorSet const &acc, A1 const &a1, A2 const &a2 ...);
#endif
namespace impl
{
using namespace numeric::operators;
template<typename Accumulator, typename Tag>
struct external_impl;
}
namespace detail
{
template<typename Accumulator>
struct feature_tag;
template<typename Feature, typename Sample, typename Weight>
struct to_accumulator;
struct accumulator_set_base;
template<typename T>
struct is_accumulator_set;
inline void ignore_variable(void const *) {}
#define BOOST_ACCUMULATORS_IGNORE_GLOBAL(X) \
namespace detail \
{ \
struct BOOST_PP_CAT(ignore_, X) \
{ \
void ignore() \
{ \
boost::accumulators::detail::ignore_variable(&X); \
} \
}; \
} \
/**/
}
}} // namespace boost::accumulators
// For defining boost::parameter keywords that can be inherited from to
// get a nested, class-scoped keyword with the requested alias
#define BOOST_PARAMETER_NESTED_KEYWORD(tag_namespace, name, alias) \
namespace tag_namespace \
{ \
template<int Dummy = 0> \
struct name ## _ \
{ \
static char const* keyword_name() \
{ \
return #name; \
} \
static ::boost::parameter::keyword<name ## _<Dummy> > &alias; \
}; \
template<int Dummy> \
::boost::parameter::keyword<name ## _<Dummy> > &name ## _<Dummy>::alias = \
::boost::parameter::keyword<name ## _<Dummy> >::get(); \
typedef name ## _ <> name; \
} \
namespace \
{ \
::boost::parameter::keyword<tag_namespace::name> &name = \
::boost::parameter::keyword<tag_namespace::name>::get(); \
}
#endif
@@ -0,0 +1,65 @@
///////////////////////////////////////////////////////////////////////////////
// accumulator_base.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_BASE_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_BASE_HPP_EAN_28_10_2005
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/joint_view.hpp>
#include <boost/mpl/single_view.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/contains.hpp>
#include <boost/mpl/empty_sequence.hpp>
#include <boost/accumulators/framework/accumulator_concept.hpp>
namespace boost { namespace accumulators
{
namespace detail
{
typedef void void_;
}
///////////////////////////////////////////////////////////////////////////////
// dont_care
//
struct dont_care
{
template<typename Args>
dont_care(Args const &)
{
}
};
///////////////////////////////////////////////////////////////////////////////
// accumulator_base
//
struct accumulator_base
{
// hidden if defined in derived classes
detail::void_ operator ()(dont_care)
{
}
typedef mpl::false_ is_droppable;
detail::void_ add_ref(dont_care)
{
}
detail::void_ drop(dont_care)
{
}
detail::void_ on_drop(dont_care)
{
}
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,29 @@
///////////////////////////////////////////////////////////////////////////////
// accumulator_concept.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATOR_CONCEPT_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATOR_CONCEPT_HPP_EAN_28_10_2005
#include <boost/concept_check.hpp>
namespace boost { namespace accumulators
{
template<typename Stat>
struct accumulator_concept
{
void constraints()
{
// TODO: define the stat concept
}
Stat stat;
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,401 @@
///////////////////////////////////////////////////////////////////////////////
// accumulator_set.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATOR_SET_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATOR_SET_HPP_EAN_28_10_2005
#include <boost/version.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/protect.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/is_sequence.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/parameter/parameters.hpp>
#include <boost/preprocessor/repetition/repeat_from_to.hpp>
#include <boost/preprocessor/repetition/enum_binary_params.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/framework/accumulator_concept.hpp>
#include <boost/accumulators/framework/parameters/accumulator.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>
#include <boost/accumulators/framework/accumulators/droppable_accumulator.hpp>
#include <boost/fusion/include/any.hpp>
#include <boost/fusion/include/find_if.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <boost/fusion/include/filter_view.hpp>
namespace boost { namespace accumulators
{
namespace detail
{
///////////////////////////////////////////////////////////////////////////////
// accumulator_visitor
// wrap a boost::parameter argument pack in a Fusion extractor object
template<typename Args>
struct accumulator_visitor
{
explicit accumulator_visitor(Args const &a)
: args(a)
{
}
template<typename Accumulator>
void operator ()(Accumulator &accumulator) const
{
accumulator(this->args);
}
private:
accumulator_visitor &operator =(accumulator_visitor const &);
Args const &args;
};
template<typename Args>
inline accumulator_visitor<Args> const make_accumulator_visitor(Args const &args)
{
return accumulator_visitor<Args>(args);
}
typedef
parameter::parameters<
parameter::required<tag::accumulator>
, parameter::optional<tag::sample>
// ... and others which are not specified here...
>
accumulator_params;
///////////////////////////////////////////////////////////////////////////////
// accumulator_set_base
struct accumulator_set_base
{
};
///////////////////////////////////////////////////////////////////////////////
// is_accumulator_set
template<typename T>
struct is_accumulator_set
: is_base_and_derived<accumulator_set_base, T>
{
};
} // namespace detail
#ifdef _MSC_VER
#pragma warning(push)
#pragma warning(disable: 4355) // warning C4355: 'this' : used in base member initializer list
#endif
///////////////////////////////////////////////////////////////////////////////
/// \brief A set of accumulators.
///
/// accumulator_set resolves the dependencies between features and ensures that
/// the accumulators in the set are updated in the proper order.
///
/// acccumulator_set provides a general mechanism to visit the accumulators
/// in the set in order, with or without a filter. You can also fetch a reference
/// to an accumulator that corresponds to a feature.
///
template<typename Sample, typename Features, typename Weight>
struct accumulator_set
: detail::accumulator_set_base
{
typedef Sample sample_type; ///< The type of the samples that will be accumulated
typedef Features features_type; ///< An MPL sequence of the features that should be accumulated.
typedef Weight weight_type; ///< The type of the weight parameter. Must be a scalar. Defaults to void.
/// INTERNAL ONLY
///
typedef
typename detail::make_accumulator_tuple<
Features
, Sample
, Weight
>::type
accumulators_mpl_vector;
// generate a fusion::list of accumulators
/// INTERNAL ONLY
///
typedef
typename detail::meta::make_acc_list<
accumulators_mpl_vector
>::type
accumulators_type;
/// INTERNAL ONLY
///
//BOOST_MPL_ASSERT((mpl::is_sequence<accumulators_type>));
///////////////////////////////////////////////////////////////////////////////
/// default-construct all contained accumulators
accumulator_set()
: accumulators(
detail::make_acc_list(
accumulators_mpl_vector()
, detail::accumulator_params()(*this)
)
)
{
// Add-ref the Features that the user has specified
this->template visit_if<detail::contains_feature_of_<Features> >(
detail::make_add_ref_visitor(detail::accumulator_params()(*this))
);
}
/// \overload
///
/// \param a1 Optional named parameter to be passed to all the accumulators
template<typename A1>
explicit accumulator_set(A1 const &a1)
: accumulators(
detail::make_acc_list(
accumulators_mpl_vector()
, detail::accumulator_params()(*this, a1)
)
)
{
// Add-ref the Features that the user has specified
this->template visit_if<detail::contains_feature_of_<Features> >(
detail::make_add_ref_visitor(detail::accumulator_params()(*this))
);
}
// ... other overloads generated by Boost.Preprocessor:
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_ACCUMULATOR_SET_CTOR(z, n, _) \
template<BOOST_PP_ENUM_PARAMS_Z(z, n, typename A)> \
accumulator_set(BOOST_PP_ENUM_BINARY_PARAMS_Z(z, n, A, const &a)) \
: accumulators( \
detail::make_acc_list( \
accumulators_mpl_vector() \
, detail::accumulator_params()( \
*this BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a) \
) \
) \
) \
{ \
/* Add-ref the Features that the user has specified */ \
this->template visit_if<detail::contains_feature_of_<Features> >( \
detail::make_add_ref_visitor(detail::accumulator_params()(*this)) \
); \
}
/// INTERNAL ONLY
///
BOOST_PP_REPEAT_FROM_TO(
2
, BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
, BOOST_ACCUMULATORS_ACCUMULATOR_SET_CTOR
, _
)
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
/// \overload
///
template<typename A1, typename A2, ...>
accumulator_set(A1 const &a1, A2 const &a2, ...);
#endif
// ... other overloads generated by Boost.Preprocessor below ...
///////////////////////////////////////////////////////////////////////////////
/// Visitation
/// \param func UnaryFunction which is invoked with each accumulator in turn.
template<typename UnaryFunction>
void visit(UnaryFunction const &func)
{
fusion::for_each(this->accumulators, func);
}
///////////////////////////////////////////////////////////////////////////////
/// Conditional visitation
/// \param func UnaryFunction which is invoked with each accumulator in turn,
/// provided the accumulator satisfies the MPL predicate FilterPred.
template<typename FilterPred, typename UnaryFunction>
void visit_if(UnaryFunction const &func)
{
fusion::filter_view<accumulators_type, FilterPred> filtered_accs(this->accumulators);
fusion::for_each(filtered_accs, func);
}
///////////////////////////////////////////////////////////////////////////////
/// The return type of the operator() overloads is void.
typedef void result_type;
///////////////////////////////////////////////////////////////////////////////
/// Accumulation
/// \param a1 Optional named parameter to be passed to all the accumulators
void operator ()()
{
this->visit(
detail::make_accumulator_visitor(
detail::accumulator_params()(*this)
)
);
}
template<typename A1>
void operator ()(A1 const &a1)
{
this->visit(
detail::make_accumulator_visitor(
detail::accumulator_params()(*this, a1)
)
);
}
// ... other overloads generated by Boost.Preprocessor:
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_ACCUMULATOR_SET_FUN_OP(z, n, _) \
template<BOOST_PP_ENUM_PARAMS_Z(z, n, typename A)> \
void operator ()(BOOST_PP_ENUM_BINARY_PARAMS_Z(z, n, A, const &a)) \
{ \
this->visit( \
detail::make_accumulator_visitor( \
detail::accumulator_params()( \
*this BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a) \
) \
) \
); \
}
/// INTERNAL ONLY
///
BOOST_PP_REPEAT_FROM_TO(
2
, BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
, BOOST_ACCUMULATORS_ACCUMULATOR_SET_FUN_OP
, _
)
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
/// \overload
///
template<typename A1, typename A2, ...>
void operator ()(A1 const &a1, A2 const &a2, ...);
#endif
///////////////////////////////////////////////////////////////////////////////
/// Extraction
template<typename Feature>
struct apply
: fusion::result_of::value_of<
typename fusion::result_of::find_if<
accumulators_type
, detail::matches_feature<Feature>
>::type
>
{
};
///////////////////////////////////////////////////////////////////////////////
/// Extraction
template<typename Feature>
typename apply<Feature>::type &extract()
{
return *fusion::find_if<detail::matches_feature<Feature> >(this->accumulators);
}
/// \overload
template<typename Feature>
typename apply<Feature>::type const &extract() const
{
return *fusion::find_if<detail::matches_feature<Feature> >(this->accumulators);
}
///////////////////////////////////////////////////////////////////////////////
/// Drop
template<typename Feature>
void drop()
{
// You can only drop the features that you have specified explicitly
typedef typename apply<Feature>::type the_accumulator;
BOOST_MPL_ASSERT((detail::contains_feature_of<Features, the_accumulator>));
typedef
typename feature_of<typename as_feature<Feature>::type>::type
the_feature;
(*fusion::find_if<detail::matches_feature<Feature> >(this->accumulators))
.drop(detail::accumulator_params()(*this));
// Also drop accumulators that this feature depends on
typedef typename the_feature::dependencies dependencies;
this->template visit_if<detail::contains_feature_of_<dependencies> >(
detail::make_drop_visitor(detail::accumulator_params()(*this))
);
}
private:
accumulators_type accumulators;
};
#ifdef _MSC_VER
#pragma warning(pop)
#endif
///////////////////////////////////////////////////////////////////////////////
// find_accumulator
// find an accumulator in an accumulator_set corresponding to a feature
template<typename Feature, typename AccumulatorSet>
typename mpl::apply<AccumulatorSet, Feature>::type &
find_accumulator(AccumulatorSet &acc BOOST_ACCUMULATORS_PROTO_DISABLE_IF_IS_CONST(AccumulatorSet))
{
return acc.template extract<Feature>();
}
/// \overload
template<typename Feature, typename AccumulatorSet>
typename mpl::apply<AccumulatorSet, Feature>::type const &
find_accumulator(AccumulatorSet const &acc)
{
return acc.template extract<Feature>();
}
///////////////////////////////////////////////////////////////////////////////
// extract_result
// extract a result from an accumulator set
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_EXTRACT_RESULT_FUN(z, n, _) \
template< \
typename Feature \
, typename AccumulatorSet \
BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A) \
> \
typename mpl::apply<AccumulatorSet, Feature>::type::result_type \
extract_result( \
AccumulatorSet const &acc \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a) \
) \
{ \
return find_accumulator<Feature>(acc).result( \
detail::accumulator_params()( \
acc \
BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a) \
) \
); \
}
BOOST_PP_REPEAT(
BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
, BOOST_ACCUMULATORS_EXTRACT_RESULT_FUN
, _
)
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,328 @@
///////////////////////////////////////////////////////////////////////////////
// droppable_accumulator.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_DROPPABLE_ACCUMULATOR_HPP_EAN_13_12_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_DROPPABLE_ACCUMULATOR_HPP_EAN_13_12_2005
#include <new>
#include <boost/assert.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/aligned_storage.hpp>
#include <boost/accumulators/framework/depends_on.hpp> // for feature_of
#include <boost/accumulators/framework/parameters/accumulator.hpp> // for accumulator
namespace boost { namespace accumulators
{
template<typename Accumulator>
struct droppable_accumulator;
namespace detail
{
///////////////////////////////////////////////////////////////////////////////
// add_ref_visitor
// a fusion function object for add_ref'ing accumulators
template<typename Args>
struct add_ref_visitor
{
explicit add_ref_visitor(Args const &args)
: args_(args)
{
}
template<typename Accumulator>
void operator ()(Accumulator &acc) const
{
typedef typename Accumulator::feature_tag::dependencies dependencies;
acc.add_ref(this->args_);
// Also add_ref accumulators that this feature depends on
this->args_[accumulator].template
visit_if<detail::contains_feature_of_<dependencies> >(
*this
);
}
private:
add_ref_visitor &operator =(add_ref_visitor const &);
Args const &args_;
};
template<typename Args>
add_ref_visitor<Args> make_add_ref_visitor(Args const &args)
{
return add_ref_visitor<Args>(args);
}
///////////////////////////////////////////////////////////////////////////////
// drop_visitor
// a fusion function object for dropping accumulators
template<typename Args>
struct drop_visitor
{
explicit drop_visitor(Args const &args)
: args_(args)
{
}
template<typename Accumulator>
void operator ()(Accumulator &acc) const
{
if(typename Accumulator::is_droppable())
{
typedef typename Accumulator::feature_tag::dependencies dependencies;
acc.drop(this->args_);
// Also drop accumulators that this feature depends on
this->args_[accumulator].template
visit_if<detail::contains_feature_of_<dependencies> >(
*this
);
}
}
private:
drop_visitor &operator =(drop_visitor const &);
Args const &args_;
};
template<typename Args>
drop_visitor<Args> make_drop_visitor(Args const &args)
{
return drop_visitor<Args>(args);
}
}
//////////////////////////////////////////////////////////////////////////
// droppable_accumulator_base
template<typename Accumulator>
struct droppable_accumulator_base
: Accumulator
{
typedef droppable_accumulator_base base;
typedef mpl::true_ is_droppable;
typedef typename Accumulator::result_type result_type;
template<typename Args>
droppable_accumulator_base(Args const &args)
: Accumulator(args)
, ref_count_(0)
{
}
droppable_accumulator_base(droppable_accumulator_base const &that)
: Accumulator(*static_cast<Accumulator const *>(&that))
, ref_count_(that.ref_count_)
{
}
template<typename Args>
void operator ()(Args const &args)
{
if(!this->is_dropped())
{
this->Accumulator::operator ()(args);
}
}
template<typename Args>
void add_ref(Args const &)
{
++this->ref_count_;
}
template<typename Args>
void drop(Args const &args)
{
BOOST_ASSERT(0 < this->ref_count_);
if(1 == this->ref_count_)
{
static_cast<droppable_accumulator<Accumulator> *>(this)->on_drop(args);
}
--this->ref_count_;
}
bool is_dropped() const
{
return 0 == this->ref_count_;
}
private:
int ref_count_;
};
//////////////////////////////////////////////////////////////////////////
// droppable_accumulator
// this can be specialized for any type that needs special handling
template<typename Accumulator>
struct droppable_accumulator
: droppable_accumulator_base<Accumulator>
{
template<typename Args>
droppable_accumulator(Args const &args)
: droppable_accumulator::base(args)
{
}
droppable_accumulator(droppable_accumulator const &that)
: droppable_accumulator::base(*static_cast<typename droppable_accumulator::base const *>(&that))
{
}
};
//////////////////////////////////////////////////////////////////////////
// with_cached_result
template<typename Accumulator>
struct with_cached_result
: Accumulator
{
typedef typename Accumulator::result_type result_type;
template<typename Args>
with_cached_result(Args const &args)
: Accumulator(args)
, cache()
{
}
with_cached_result(with_cached_result const &that)
: Accumulator(*static_cast<Accumulator const *>(&that))
, cache()
{
if(that.has_result())
{
this->set(that.get());
}
}
~with_cached_result()
{
// Since this is a base class of droppable_accumulator_base,
// this destructor is called before any of droppable_accumulator_base's
// members get cleaned up, including is_dropped, so the following
// call to has_result() is valid.
if(this->has_result())
{
this->get().~result_type();
}
}
template<typename Args>
void on_drop(Args const &args)
{
// cache the result at the point this calculation was dropped
BOOST_ASSERT(!this->has_result());
this->set(this->Accumulator::result(args));
}
template<typename Args>
result_type result(Args const &args) const
{
return this->has_result() ? this->get() : this->Accumulator::result(args);
}
private:
with_cached_result &operator =(with_cached_result const &);
void set(result_type const &r)
{
::new(this->cache.address()) result_type(r);
}
result_type const &get() const
{
return *static_cast<result_type const *>(this->cache.address());
}
bool has_result() const
{
typedef with_cached_result<Accumulator> this_type;
typedef droppable_accumulator_base<this_type> derived_type;
return static_cast<derived_type const *>(this)->is_dropped();
}
aligned_storage<sizeof(result_type)> cache;
};
namespace tag
{
template<typename Feature>
struct as_droppable
{
typedef droppable<Feature> type;
};
template<typename Feature>
struct as_droppable<droppable<Feature> >
{
typedef droppable<Feature> type;
};
//////////////////////////////////////////////////////////////////////////
// droppable
template<typename Feature>
struct droppable
: as_feature<Feature>::type
{
typedef typename as_feature<Feature>::type feature_type;
typedef typename feature_type::dependencies tmp_dependencies_;
typedef
typename mpl::transform<
typename feature_type::dependencies
, as_droppable<mpl::_1>
>::type
dependencies;
struct impl
{
template<typename Sample, typename Weight>
struct apply
{
typedef
droppable_accumulator<
typename mpl::apply2<typename feature_type::impl, Sample, Weight>::type
>
type;
};
};
};
}
// make droppable<tag::feature(modifier)> work
template<typename Feature>
struct as_feature<tag::droppable<Feature> >
{
typedef tag::droppable<typename as_feature<Feature>::type> type;
};
// make droppable<tag::mean> work with non-void weights (should become
// droppable<tag::weighted_mean>
template<typename Feature>
struct as_weighted_feature<tag::droppable<Feature> >
{
typedef tag::droppable<typename as_weighted_feature<Feature>::type> type;
};
// for the purposes of feature-based dependency resolution,
// droppable<Foo> provides the same feature as Foo
template<typename Feature>
struct feature_of<tag::droppable<Feature> >
: feature_of<Feature>
{
};
// Note: Usually, the extractor is pulled into the accumulators namespace with
// a using directive, not the tag. But the droppable<> feature doesn't have an
// extractor, so we can put the droppable tag in the accumulators namespace
// without fear of a name conflict.
using tag::droppable;
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,108 @@
///////////////////////////////////////////////////////////////////////////////
// external_accumulator.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_EXTERNAL_ACCUMULATOR_HPP_EAN_01_12_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_EXTERNAL_ACCUMULATOR_HPP_EAN_01_12_2005
#include <boost/mpl/placeholders.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/depends_on.hpp> // for feature_tag
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/accumulators/reference_accumulator.hpp>
namespace boost { namespace accumulators { namespace impl
{
//////////////////////////////////////////////////////////////////////////
// external_impl
/// INTERNAL ONLY
///
template<typename Accumulator, typename Tag>
struct external_impl
: accumulator_base
{
typedef typename Accumulator::result_type result_type;
typedef typename detail::feature_tag<Accumulator>::type feature_tag;
external_impl(dont_care) {}
template<typename Args>
result_type result(Args const &args) const
{
return this->extract_(args, args[parameter::keyword<Tag>::get() | 0]);
}
private:
template<typename Args>
static result_type extract_(Args const &args, int)
{
// No named parameter passed to the extractor. Maybe the external
// feature is held by reference<>.
extractor<feature_tag> extract;
return extract(accumulators::reference_tag<Tag>(args));
}
template<typename Args, typename AccumulatorSet>
static result_type extract_(Args const &, AccumulatorSet const &acc)
{
// OK, a named parameter for this external feature was passed to the
// extractor, so use that.
extractor<feature_tag> extract;
return extract(acc);
}
};
} // namespace impl
namespace tag
{
//////////////////////////////////////////////////////////////////////////
// external
template<typename Feature, typename Tag, typename AccumulatorSet>
struct external
: depends_on<reference<AccumulatorSet, Tag> >
{
typedef
accumulators::impl::external_impl<
detail::to_accumulator<Feature, mpl::_1, mpl::_2>
, Tag
>
impl;
};
template<typename Feature, typename Tag>
struct external<Feature, Tag, void>
: depends_on<>
{
typedef
accumulators::impl::external_impl<
detail::to_accumulator<Feature, mpl::_1, mpl::_2>
, Tag
>
impl;
};
}
// for the purposes of feature-based dependency resolution,
// external_accumulator<Feature, Tag> provides the same feature as Feature
template<typename Feature, typename Tag, typename AccumulatorSet>
struct feature_of<tag::external<Feature, Tag, AccumulatorSet> >
: feature_of<Feature>
{
};
// Note: Usually, the extractor is pulled into the accumulators namespace with
// a using directive, not the tag. But the external<> feature doesn't have an
// extractor, so we can put the external tag in the accumulators namespace
// without fear of a name conflict.
using tag::external;
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,89 @@
///////////////////////////////////////////////////////////////////////////////
// reference_accumulator.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_REFERENCE_ACCUMULATOR_HPP_EAN_03_23_2006
#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_REFERENCE_ACCUMULATOR_HPP_EAN_03_23_2006
#include <boost/ref.hpp>
#include <boost/mpl/always.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/framework/depends_on.hpp> // for feature_tag
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
//////////////////////////////////////////////////////////////////////////
// reference_accumulator_impl
//
template<typename Referent, typename Tag>
struct reference_accumulator_impl
: accumulator_base
{
typedef Referent &result_type;
template<typename Args>
reference_accumulator_impl(Args const &args)
: ref(args[parameter::keyword<Tag>::get()])
{
}
result_type result(dont_care) const
{
return this->ref;
}
private:
reference_wrapper<Referent> ref;
};
} // namespace impl
namespace tag
{
//////////////////////////////////////////////////////////////////////////
// reference_tag
template<typename Tag>
struct reference_tag
{
};
//////////////////////////////////////////////////////////////////////////
// reference
template<typename Referent, typename Tag>
struct reference
: depends_on<>
{
/// INTERNAL ONLY
///
typedef mpl::always<accumulators::impl::reference_accumulator_impl<Referent, Tag> > impl;
};
}
namespace extract
{
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, reference, (typename)(typename))
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, reference_tag, (typename))
}
using extract::reference;
using extract::reference_tag;
// Map all reference<V,T> features to reference_tag<T> so
// that references can be extracted using reference_tag<T>
// without specifying the referent type.
template<typename ValueType, typename Tag>
struct feature_of<tag::reference<ValueType, Tag> >
: feature_of<tag::reference_tag<Tag> >
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,89 @@
///////////////////////////////////////////////////////////////////////////////
// value_accumulator.hpp
//
// Copyright 2005 Eric Niebler, Daniel Egloff. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_VALUE_ACCUMULATOR_HPP_EAN_03_23_2006
#define BOOST_ACCUMULATORS_FRAMEWORK_ACCUMULATORS_VALUE_ACCUMULATOR_HPP_EAN_03_23_2006
#include <boost/mpl/always.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/framework/depends_on.hpp> // for feature_tag
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
//////////////////////////////////////////////////////////////////////////
// value_accumulator_impl
template<typename ValueType, typename Tag>
struct value_accumulator_impl
: accumulator_base
{
typedef ValueType result_type;
template<typename Args>
value_accumulator_impl(Args const &args)
: val(args[parameter::keyword<Tag>::get()])
{
}
result_type result(dont_care) const
{
return this->val;
}
private:
ValueType val;
};
} // namespace impl
namespace tag
{
//////////////////////////////////////////////////////////////////////////
// value_tag
template<typename Tag>
struct value_tag
{
};
//////////////////////////////////////////////////////////////////////////
// value
template<typename ValueType, typename Tag>
struct value
: depends_on<>
{
/// INTERNAL ONLY
///
typedef mpl::always<accumulators::impl::value_accumulator_impl<ValueType, Tag> > impl;
};
}
namespace extract
{
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, value, (typename)(typename))
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, value_tag, (typename))
}
using extract::value;
using extract::value_tag;
// Map all value<V,T> features to value_tag<T> so
// that values can be extracted using value_tag<T>
// without specifying the value type.
template<typename ValueType, typename Tag>
struct feature_of<tag::value<ValueType, Tag> >
: feature_of<tag::value_tag<Tag> >
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,448 @@
///////////////////////////////////////////////////////////////////////////////
// depends_on.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_DEPENDS_ON_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_DEPENDS_ON_HPP_EAN_28_10_2005
#include <boost/version.hpp>
#include <boost/mpl/end.hpp>
#include <boost/mpl/map.hpp>
#include <boost/mpl/set.hpp>
#include <boost/mpl/copy.hpp>
#include <boost/mpl/fold.hpp>
#include <boost/mpl/size.hpp>
#include <boost/mpl/sort.hpp>
#include <boost/mpl/insert.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/remove.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/inherit.hpp>
#include <boost/mpl/identity.hpp>
#include <boost/mpl/equal_to.hpp>
#include <boost/mpl/contains.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/is_sequence.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/mpl/insert_range.hpp>
#include <boost/mpl/back_inserter.hpp>
#include <boost/mpl/transform_view.hpp>
#include <boost/mpl/inherit_linearly.hpp>
#include <boost/type_traits/is_base_and_derived.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/facilities/intercept.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
#include <boost/fusion/include/next.hpp>
#include <boost/fusion/include/equal_to.hpp>
#include <boost/fusion/include/value_of.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/fusion/include/end.hpp>
#include <boost/fusion/include/begin.hpp>
#include <boost/fusion/include/cons.hpp>
namespace boost { namespace accumulators
{
///////////////////////////////////////////////////////////////////////////
// as_feature
template<typename Feature>
struct as_feature
{
typedef Feature type;
};
///////////////////////////////////////////////////////////////////////////
// weighted_feature
template<typename Feature>
struct as_weighted_feature
{
typedef Feature type;
};
///////////////////////////////////////////////////////////////////////////
// feature_of
template<typename Feature>
struct feature_of
{
typedef Feature type;
};
namespace detail
{
///////////////////////////////////////////////////////////////////////////
// feature_tag
template<typename Accumulator>
struct feature_tag
{
typedef typename Accumulator::feature_tag type;
};
template<typename Feature>
struct undroppable
{
typedef Feature type;
};
template<typename Feature>
struct undroppable<tag::droppable<Feature> >
{
typedef Feature type;
};
// For the purpose of determining whether one feature depends on another,
// disregard whether the feature is droppable or not.
template<typename A, typename B>
struct is_dependent_on
: is_base_and_derived<
typename feature_of<typename undroppable<B>::type>::type
, typename undroppable<A>::type
>
{};
template<typename Feature>
struct dependencies_of
{
typedef typename Feature::dependencies type;
};
// Should use mpl::insert_range, but doesn't seem to work with mpl sets
template<typename Set, typename Range>
struct set_insert_range
: mpl::fold<
Range
, Set
, mpl::insert<mpl::_1, mpl::_2>
>
{};
template<typename Features>
struct collect_abstract_features
: mpl::fold<
Features
, mpl::set0<>
, set_insert_range<
mpl::insert<mpl::_1, feature_of<mpl::_2> >
, collect_abstract_features<dependencies_of<mpl::_2> >
>
>
{};
template<typename Features>
struct depends_on_base
: mpl::inherit_linearly<
typename mpl::sort<
typename mpl::copy<
typename collect_abstract_features<Features>::type
, mpl::back_inserter<mpl::vector0<> >
>::type
, is_dependent_on<mpl::_1, mpl::_2>
>::type
// Don't inherit multiply from a feature
, mpl::if_<
is_dependent_on<mpl::_1, mpl::_2>
, mpl::_1
, mpl::inherit<mpl::_1, mpl::_2>
>
>::type
{
};
}
///////////////////////////////////////////////////////////////////////////
/// depends_on
template<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, typename Feature)>
struct depends_on
: detail::depends_on_base<
typename mpl::transform<
mpl::vector<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, Feature)>
, as_feature<mpl::_1>
>::type
>
{
typedef mpl::false_ is_weight_accumulator;
typedef
typename mpl::transform<
mpl::vector<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, Feature)>
, as_feature<mpl::_1>
>::type
dependencies;
};
namespace detail
{
template<typename Feature>
struct matches_feature
{
template<typename Accumulator>
struct apply
: is_same<
typename feature_of<typename as_feature<Feature>::type>::type
, typename feature_of<typename as_feature<typename feature_tag<Accumulator>::type>::type>::type
>
{};
};
template<typename Features, typename Accumulator>
struct contains_feature_of
{
typedef
mpl::transform_view<Features, feature_of<as_feature<mpl::_> > >
features_list;
typedef
typename feature_of<typename feature_tag<Accumulator>::type>::type
the_feature;
typedef
typename mpl::contains<features_list, the_feature>::type
type;
};
// This is to work around a bug in early versions of Fusion which caused
// a compile error if contains_feature_of<List, mpl::_> is used as a
// predicate to fusion::find_if
template<typename Features>
struct contains_feature_of_
{
template<typename Accumulator>
struct apply
: contains_feature_of<Features, Accumulator>
{};
};
template<
typename First
, typename Last
, bool is_empty = fusion::result_of::equal_to<First, Last>::value
>
struct build_acc_list;
template<typename First, typename Last>
struct build_acc_list<First, Last, true>
{
typedef fusion::nil_ type;
template<typename Args>
static fusion::nil_
call(Args const &, First const&, Last const&)
{
return fusion::nil_();
}
};
template<typename First, typename Last>
struct build_acc_list<First, Last, false>
{
typedef
build_acc_list<typename fusion::result_of::next<First>::type, Last>
next_build_acc_list;
typedef fusion::cons<
typename fusion::result_of::value_of<First>::type
, typename next_build_acc_list::type>
type;
template<typename Args>
static type
call(Args const &args, First const& f, Last const& l)
{
return type(args, next_build_acc_list::call(args, fusion::next(f), l));
}
};
namespace meta
{
template<typename Sequence>
struct make_acc_list
: build_acc_list<
typename fusion::result_of::begin<Sequence>::type
, typename fusion::result_of::end<Sequence>::type
>
{};
}
template<typename Sequence, typename Args>
typename meta::make_acc_list<Sequence>::type
make_acc_list(Sequence const &seq, Args const &args)
{
return meta::make_acc_list<Sequence>::call(args, fusion::begin(seq), fusion::end(seq));
}
///////////////////////////////////////////////////////////////////////////
// checked_as_weighted_feature
template<typename Feature>
struct checked_as_weighted_feature
{
typedef typename as_feature<Feature>::type feature_type;
typedef typename as_weighted_feature<feature_type>::type type;
// weighted and non-weighted flavors should provide the same feature.
BOOST_MPL_ASSERT((
is_same<
typename feature_of<feature_type>::type
, typename feature_of<type>::type
>
));
};
///////////////////////////////////////////////////////////////////////////
// as_feature_list
template<typename Features, typename Weight>
struct as_feature_list
: mpl::transform_view<Features, checked_as_weighted_feature<mpl::_1> >
{
};
template<typename Features>
struct as_feature_list<Features, void>
: mpl::transform_view<Features, as_feature<mpl::_1> >
{
};
///////////////////////////////////////////////////////////////////////////
// accumulator_wrapper
template<typename Accumulator, typename Feature>
struct accumulator_wrapper
: Accumulator
{
typedef Feature feature_tag;
accumulator_wrapper(accumulator_wrapper const &that)
: Accumulator(*static_cast<Accumulator const *>(&that))
{
}
template<typename Args>
accumulator_wrapper(Args const &args)
: Accumulator(args)
{
}
};
///////////////////////////////////////////////////////////////////////////
// to_accumulator
template<typename Feature, typename Sample, typename Weight>
struct to_accumulator
{
typedef
accumulator_wrapper<
typename mpl::apply2<typename Feature::impl, Sample, Weight>::type
, Feature
>
type;
};
template<typename Feature, typename Sample, typename Weight, typename Tag, typename AccumulatorSet>
struct to_accumulator<Feature, Sample, tag::external<Weight, Tag, AccumulatorSet> >
{
BOOST_MPL_ASSERT((is_same<Tag, void>));
BOOST_MPL_ASSERT((is_same<AccumulatorSet, void>));
typedef
accumulator_wrapper<
typename mpl::apply2<typename Feature::impl, Sample, Weight>::type
, Feature
>
accumulator_type;
typedef
typename mpl::if_<
typename Feature::is_weight_accumulator
, accumulator_wrapper<impl::external_impl<accumulator_type, tag::weights>, Feature>
, accumulator_type
>::type
type;
};
// BUGBUG work around an MPL bug wrt map insertion
template<typename FeatureMap, typename Feature>
struct insert_feature
: mpl::eval_if<
mpl::has_key<FeatureMap, typename feature_of<Feature>::type>
, mpl::identity<FeatureMap>
, mpl::insert<FeatureMap, mpl::pair<typename feature_of<Feature>::type, Feature> >
>
{
};
template<typename FeatureMap, typename Feature, typename Weight>
struct insert_dependencies
: mpl::fold<
as_feature_list<typename Feature::dependencies, Weight>
, FeatureMap
, insert_dependencies<
insert_feature<mpl::_1, mpl::_2>
, mpl::_2
, Weight
>
>
{
};
template<typename FeatureMap, typename Features, typename Weight>
struct insert_sequence
: mpl::fold< // BUGBUG should use insert_range, but doesn't seem to work for maps
as_feature_list<Features, Weight>
, FeatureMap
, insert_feature<mpl::_1, mpl::_2>
>
{
};
template<typename Features, typename Sample, typename Weight>
struct make_accumulator_tuple
{
typedef
typename mpl::fold<
as_feature_list<Features, Weight>
, mpl::map0<>
, mpl::if_<
mpl::is_sequence<mpl::_2>
, insert_sequence<mpl::_1, mpl::_2, Weight>
, insert_feature<mpl::_1, mpl::_2>
>
>::type
feature_map;
// for each element in the map, add its dependencies also
typedef
typename mpl::fold<
feature_map
, feature_map
, insert_dependencies<mpl::_1, mpl::second<mpl::_2>, Weight>
>::type
feature_map_with_dependencies;
// turn the map into a vector so we can sort it
typedef
typename mpl::insert_range<
mpl::vector<>
, mpl::end<mpl::vector<> >::type
, mpl::transform_view<feature_map_with_dependencies, mpl::second<mpl::_1> >
>::type
feature_vector_with_dependencies;
// sort the features according to which is derived from which
typedef
typename mpl::sort<
feature_vector_with_dependencies
, is_dependent_on<mpl::_2, mpl::_1>
>::type
sorted_feature_vector;
// From the vector of features, construct a vector of accumulators
typedef
typename mpl::transform<
sorted_feature_vector
, to_accumulator<mpl::_1, Sample, Weight>
>::type
type;
};
} // namespace detail
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,27 @@
///////////////////////////////////////////////////////////////////////////////
// external.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_EXTERNAL_HPP_EAN_01_12_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_EXTERNAL_HPP_EAN_01_12_2005
#include <boost/mpl/apply.hpp>
#include <boost/accumulators/framework/accumulators/external_accumulator.hpp>
//namespace boost { namespace accumulators
//{
//
/////////////////////////////////////////////////////////////////////////////////
//// external
////
//template<typename Type>
//struct external
//{
//};
//
//}} // namespace boost::accumulators
#endif
@@ -0,0 +1,229 @@
///////////////////////////////////////////////////////////////////////////////
// extractor.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_EXTRACTOR_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_EXTRACTOR_HPP_EAN_28_10_2005
#include <boost/preprocessor/tuple/rem.hpp>
#include <boost/preprocessor/array/size.hpp>
#include <boost/preprocessor/array/data.hpp>
#include <boost/preprocessor/array/elem.hpp>
#include <boost/preprocessor/seq/to_array.hpp>
#include <boost/preprocessor/seq/transform.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp>
#include <boost/parameter/binding.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/mpl/eval_if.hpp>
#include <boost/type_traits/remove_reference.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
#include <boost/accumulators/framework/parameters/accumulator.hpp>
namespace boost { namespace accumulators
{
namespace detail
{
template<typename AccumulatorSet, typename Feature>
struct accumulator_set_result
{
typedef typename as_feature<Feature>::type feature_type;
typedef typename mpl::apply<AccumulatorSet, feature_type>::type::result_type type;
};
template<typename Args, typename Feature>
struct argument_pack_result
: accumulator_set_result<
typename remove_reference<
typename parameter::binding<Args, tag::accumulator>::type
>::type
, Feature
>
{
};
template<typename A, typename Feature>
struct extractor_result
: mpl::eval_if<
detail::is_accumulator_set<A>
, accumulator_set_result<A, Feature>
, argument_pack_result<A, Feature>
>
{
};
template<typename Feature, typename AccumulatorSet>
typename extractor_result<AccumulatorSet, Feature>::type
do_extract(AccumulatorSet const &acc, mpl::true_)
{
typedef typename as_feature<Feature>::type feature_type;
return extract_result<feature_type>(acc);
}
template<typename Feature, typename Args>
typename extractor_result<Args, Feature>::type
do_extract(Args const &args, mpl::false_)
{
typedef typename as_feature<Feature>::type feature_type;
return find_accumulator<feature_type>(args[accumulator]).result(args);
}
} // namespace detail
///////////////////////////////////////////////////////////////////////////////
/// Extracts the result associated with Feature from the specified accumulator_set.
template<typename Feature>
struct extractor
{
typedef extractor<Feature> this_type;
/// The result meta-function for determining the return type of the extractor
template<typename F>
struct result;
template<typename A1>
struct result<this_type(A1)>
: detail::extractor_result<A1, Feature>
{
};
/// Extract the result associated with Feature from the accumulator set
/// \param acc The accumulator set object from which to extract the result
template<typename Arg1>
typename detail::extractor_result<Arg1, Feature>::type
operator ()(Arg1 const &arg1) const
{
// Arg1 could be an accumulator_set or an argument pack containing
// an accumulator_set. Dispatch accordingly.
return detail::do_extract<Feature>(arg1, detail::is_accumulator_set<Arg1>());
}
/// \overload
///
/// \param a1 Optional named parameter to be passed to the accumulator's result() function.
template<typename AccumulatorSet, typename A1>
typename detail::extractor_result<AccumulatorSet, Feature>::type
operator ()(AccumulatorSet const &acc, A1 const &a1) const
{
BOOST_MPL_ASSERT((detail::is_accumulator_set<AccumulatorSet>));
typedef typename as_feature<Feature>::type feature_type;
return extract_result<feature_type>(acc, a1);
}
// ... other overloads generated by Boost.Preprocessor:
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_EXTRACTOR_FUN_OP(z, n, _) \
template<BOOST_PP_ENUM_PARAMS_Z(z, n, typename A)> \
struct result<this_type(BOOST_PP_ENUM_PARAMS_Z(z, n, A))> \
: detail::extractor_result<A1, Feature> \
{}; \
template< \
typename AccumulatorSet \
BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A) \
> \
typename detail::extractor_result<AccumulatorSet, Feature>::type \
operator ()( \
AccumulatorSet const &acc \
BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a) \
) const \
{ \
BOOST_MPL_ASSERT((detail::is_accumulator_set<AccumulatorSet>)); \
typedef typename as_feature<Feature>::type feature_type; \
return extract_result<feature_type>(acc BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a));\
}
BOOST_PP_REPEAT_FROM_TO(
2
, BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS)
, BOOST_ACCUMULATORS_EXTRACTOR_FUN_OP
, _
)
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
/// \overload
///
template<typename AccumulatorSet, typename A1, typename A2, ...>
typename detail::extractor_result<AccumulatorSet, Feature>::type
operator ()(AccumulatorSet const &acc, A1 const &a1, A2 const &a2, ...);
#endif
};
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_ARRAY_REM(Array) \
BOOST_PP_TUPLE_REM_CTOR(BOOST_PP_ARRAY_SIZE(Array), BOOST_PP_ARRAY_DATA(Array))
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_SEQ_REM(Seq) \
BOOST_ACCUMULATORS_ARRAY_REM(BOOST_PP_SEQ_TO_ARRAY(Seq))
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_ARGS_OP(s, data, elem) \
T ## s
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_PARAMS_OP(s, data, elem) \
elem T ## s
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_MAKE_FEATURE(Tag, Feature, ParamsSeq) \
Tag::Feature< \
BOOST_ACCUMULATORS_SEQ_REM( \
BOOST_PP_SEQ_TRANSFORM(BOOST_ACCUMULATORS_ARGS_OP, ~, ParamsSeq) \
) \
>
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_DEFINE_EXTRACTOR_FUN_IMPL(z, n, Tag, Feature, ParamsSeq) \
template< \
BOOST_ACCUMULATORS_SEQ_REM( \
BOOST_PP_SEQ_TRANSFORM(BOOST_ACCUMULATORS_PARAMS_OP, ~, ParamsSeq) \
) \
, typename Arg1 \
BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, typename A) \
> \
typename boost::accumulators::detail::extractor_result< \
Arg1 \
, BOOST_ACCUMULATORS_MAKE_FEATURE(Tag, Feature, ParamsSeq) \
>::type \
Feature(Arg1 const &arg1 BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(z, n, A, const &a) ) \
{ \
typedef BOOST_ACCUMULATORS_MAKE_FEATURE(Tag, Feature, ParamsSeq) feature_type; \
return boost::accumulators::extractor<feature_type>()( \
arg1 BOOST_PP_ENUM_TRAILING_PARAMS_Z(z, n, a)); \
}
/// INTERNAL ONLY
///
#define BOOST_ACCUMULATORS_DEFINE_EXTRACTOR_FUN(z, n, _) \
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR_FUN_IMPL( \
z \
, n \
, BOOST_PP_ARRAY_ELEM(0, _) \
, BOOST_PP_ARRAY_ELEM(1, _) \
, BOOST_PP_ARRAY_ELEM(2, _) \
)
#define BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(Tag, Feature, ParamSeq) \
BOOST_PP_REPEAT( \
BOOST_PP_INC(BOOST_ACCUMULATORS_MAX_ARGS) \
, BOOST_ACCUMULATORS_DEFINE_EXTRACTOR_FUN \
, (3, (Tag, Feature, ParamSeq)) \
)
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,29 @@
///////////////////////////////////////////////////////////////////////////////
// features.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_STATS_HPP_EAN_08_12_2005
#define BOOST_ACCUMULATORS_STATISTICS_STATS_HPP_EAN_08_12_2005
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
namespace boost { namespace accumulators
{
///////////////////////////////////////////////////////////////////////////////
// features
//
template<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, typename Feature)>
struct features
: mpl::vector<BOOST_PP_ENUM_PARAMS(BOOST_ACCUMULATORS_MAX_FEATURES, Feature)>
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,22 @@
///////////////////////////////////////////////////////////////////////////////
// accumulator.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_ACCUMULATOR_HPP_EAN_31_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_ACCUMULATOR_HPP_EAN_31_10_2005
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
namespace boost { namespace accumulators
{
BOOST_PARAMETER_KEYWORD(tag, accumulator)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(accumulator)
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,22 @@
///////////////////////////////////////////////////////////////////////////////
// sample.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_SAMPLE_HPP_EAN_31_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_SAMPLE_HPP_EAN_31_10_2005
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
namespace boost { namespace accumulators
{
BOOST_PARAMETER_KEYWORD(tag, sample)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(sample)
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,23 @@
///////////////////////////////////////////////////////////////////////////////
// weight.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_WEIGHT_HPP_EAN_31_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_WEIGHT_HPP_EAN_31_10_2005
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
namespace boost { namespace accumulators
{
// The weight of a single sample
BOOST_PARAMETER_KEYWORD(tag, weight)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(weight)
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,23 @@
///////////////////////////////////////////////////////////////////////////////
// weights.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_WEIGHTS_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_FRAMEWORK_PARAMETERS_WEIGHTS_HPP_EAN_28_10_2005
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
namespace boost { namespace accumulators
{
// The weight accumulator
BOOST_PARAMETER_KEYWORD(tag, weights)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(weights)
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,75 @@
// Copyright David Abrahams 2006. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_DETAIL_FUNCTION1_DWA200655_HPP
# define BOOST_DETAIL_FUNCTION1_DWA200655_HPP
# include <boost/concept_check.hpp>
# include <boost/type_traits/remove_reference.hpp>
# include <boost/type_traits/add_const.hpp>
# include <boost/mpl/apply.hpp>
namespace boost { namespace detail {
// A utility for creating unary function objects that play nicely with
// boost::result_of and that handle the forwarding problem.
//
// mpl::apply<F, A0>::type is expected to be a stateless function
// object that accepts an argument of type A0&. It is also expected
// to have a nested ::result_type identical to its return type.
template<typename F>
struct function1
{
template<typename Signature>
struct result
{};
template<typename This, typename A0>
struct result<This(A0)>
{
// How adding const to arguments handles rvalues.
//
// if A0 is arg0 is represents actual argument
// -------- ------- --------------------------
// T const & T const const T lvalue
// T & T non-const T lvalue
// T const T const const T rvalue
// T T const non-const T rvalue
typedef typename remove_reference<
typename add_const< A0 >::type
>::type arg0;
typedef typename mpl::apply1<F, arg0>::type impl;
typedef typename impl::result_type type;
};
// Handles mutable lvalues
template<typename A0>
typename result<function1(A0 &)>::type
operator ()(A0 &a0) const
{
typedef typename result<function1(A0 &)>::impl impl;
typedef typename result<function1(A0 &)>::type type;
typedef A0 &arg0;
BOOST_CONCEPT_ASSERT((UnaryFunction<impl, type, arg0>));
//boost::function_requires<UnaryFunctionConcept<impl, type, arg0> >();
return impl()(a0);
}
// Handles const lvalues and all rvalues
template<typename A0>
typename result<function1(A0 const &)>::type
operator ()(A0 const &a0) const
{
typedef typename result<function1(A0 const &)>::impl impl;
typedef typename result<function1(A0 const &)>::type type;
typedef A0 const &arg0;
BOOST_CONCEPT_ASSERT((UnaryFunction<impl, type, arg0>));
//boost::function_requires<UnaryFunctionConcept<impl, type, arg0> >();
return impl()(a0);
}
};
}} // namespace boost::detail
#endif // BOOST_DETAIL_FUNCTION1_DWA200655_HPP
@@ -0,0 +1,10 @@
// Copyright David Abrahams 2006. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_DETAIL_FUNCTION2_DWA200655_HPP
# define BOOST_DETAIL_FUNCTION2_DWA200655_HPP
# define args (2)
# include <boost/accumulators/numeric/detail/function_n.hpp>
#endif // BOOST_DETAIL_FUNCTION2_DWA200655_HPP
@@ -0,0 +1,10 @@
// Copyright David Abrahams 2006. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_DETAIL_FUNCTION3_DWA2006514_HPP
# define BOOST_DETAIL_FUNCTION3_DWA2006514_HPP
# define args (3)
# include <boost/accumulators/numeric/detail/function_n.hpp>
#endif // BOOST_DETAIL_FUNCTION3_DWA2006514_HPP
@@ -0,0 +1,10 @@
// Copyright David Abrahams 2006. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_DETAIL_FUNCTION4_DWA2006514_HPP
# define BOOST_DETAIL_FUNCTION4_DWA2006514_HPP
# define args (4)
# include <boost/accumulators/numeric/detail/function_n.hpp>
#endif // BOOST_DETAIL_FUNCTION4_DWA2006514_HPP
@@ -0,0 +1,148 @@
// Copyright David Abrahams 2006. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// #include guards intentionally disabled.
// #ifndef BOOST_DETAIL_FUNCTION_N_DWA2006514_HPP
// # define BOOST_DETAIL_FUNCTION_N_DWA2006514_HPP
#include <boost/mpl/void.hpp>
#include <boost/mpl/apply.hpp>
#include <boost/preprocessor/control/if.hpp>
#include <boost/preprocessor/cat.hpp>
#include <boost/preprocessor/punctuation/comma_if.hpp>
#include <boost/preprocessor/repetition/enum_params.hpp>
#include <boost/preprocessor/repetition/enum_trailing_params.hpp>
#include <boost/preprocessor/repetition/repeat.hpp>
#include <boost/preprocessor/seq/fold_left.hpp>
#include <boost/preprocessor/seq/seq.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <boost/preprocessor/seq/for_each_i.hpp>
#include <boost/preprocessor/seq/for_each_product.hpp>
#include <boost/preprocessor/seq/size.hpp>
#include <boost/type_traits/add_const.hpp>
#include <boost/type_traits/remove_reference.hpp>
namespace boost { namespace detail {
# define BOOST_DETAIL_default_arg(z, n, _) \
typedef mpl::void_ BOOST_PP_CAT(arg, n);
# define BOOST_DETAIL_function_arg(z, n, _) \
typedef typename remove_reference< \
typename add_const< BOOST_PP_CAT(A, n) >::type \
>::type BOOST_PP_CAT(arg, n);
#define BOOST_DETAIL_cat_arg_counts(s, state, n) \
BOOST_PP_IF( \
n \
, BOOST_PP_CAT(state, BOOST_PP_CAT(_, n)) \
, state \
) \
/**/
#define function_name \
BOOST_PP_SEQ_FOLD_LEFT( \
BOOST_DETAIL_cat_arg_counts \
, BOOST_PP_CAT(function, BOOST_PP_SEQ_HEAD(args)) \
, BOOST_PP_SEQ_TAIL(args)(0) \
) \
/**/
template<typename F>
struct function_name
{
BOOST_PP_REPEAT(
BOOST_MPL_LIMIT_METAFUNCTION_ARITY
, BOOST_DETAIL_default_arg
, ~
)
template<typename Signature>
struct result {};
#define BOOST_DETAIL_function_result(r, _, n) \
template<typename This BOOST_PP_ENUM_TRAILING_PARAMS(n, typename A)> \
struct result<This(BOOST_PP_ENUM_PARAMS(n, A))> \
{ \
BOOST_PP_REPEAT(n, BOOST_DETAIL_function_arg, ~) \
typedef \
typename BOOST_PP_CAT(mpl::apply, BOOST_MPL_LIMIT_METAFUNCTION_ARITY)<\
F \
BOOST_PP_ENUM_TRAILING_PARAMS( \
BOOST_MPL_LIMIT_METAFUNCTION_ARITY \
, arg \
) \
>::type \
impl; \
typedef typename impl::result_type type; \
}; \
/**/
BOOST_PP_SEQ_FOR_EACH(BOOST_DETAIL_function_result, _, args)
# define arg_type(r, _, i, is_const) \
BOOST_PP_COMMA_IF(i) BOOST_PP_CAT(A, i) BOOST_PP_CAT(const_if, is_const) &
# define result_(r, n, constness) \
typename result< \
function_name( \
BOOST_PP_SEQ_FOR_EACH_I_R(r, arg_type, ~, constness) \
) \
> \
/**/
# define param(r, _, i, is_const) BOOST_PP_COMMA_IF(i) \
BOOST_PP_CAT(A, i) BOOST_PP_CAT(const_if, is_const) & BOOST_PP_CAT(x, i)
# define param_list(r, n, constness) \
BOOST_PP_SEQ_FOR_EACH_I_R(r, param, ~, constness)
# define call_operator(r, constness) \
template<BOOST_PP_ENUM_PARAMS(BOOST_PP_SEQ_SIZE(constness), typename A)> \
result_(r, BOOST_PP_SEQ_SIZE(constness), constness)::type \
operator ()( param_list(r, BOOST_PP_SEQ_SIZE(constness), constness) ) const \
{ \
typedef result_(r, BOOST_PP_SEQ_SIZE(constness), constness)::impl impl; \
return impl()(BOOST_PP_ENUM_PARAMS(BOOST_PP_SEQ_SIZE(constness), x)); \
} \
/**/
# define const_if0
# define const_if1 const
# define bits(z, n, _) ((0)(1))
# define gen_operator(r, _, n) \
BOOST_PP_SEQ_FOR_EACH_PRODUCT_R( \
r \
, call_operator \
, BOOST_PP_REPEAT(n, bits, ~) \
) \
/**/
BOOST_PP_SEQ_FOR_EACH(
gen_operator
, ~
, args
)
# undef bits
# undef const_if1
# undef const_if0
# undef call_operator
# undef param_list
# undef param
# undef result_
# undef default_
# undef arg_type
# undef gen_operator
# undef function_name
# undef args
};
}} // namespace boost::detail
//#endif // BOOST_DETAIL_FUNCTION_N_DWA2006514_HPP
@@ -0,0 +1,20 @@
// Copyright David Abrahams 2006. Distributed under the Boost
// Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_DETAIL_POD_SINGLETON_DWA200655_HPP
# define BOOST_DETAIL_POD_SINGLETON_DWA200655_HPP
namespace boost { namespace detail {
template<typename T>
struct pod_singleton
{
static T instance;
};
template<typename T>
T pod_singleton<T>::instance;
}} // namespace boost::detail
#endif // BOOST_DETAIL_POD_SINGLETON_DWA200655_HPP
@@ -0,0 +1,537 @@
///////////////////////////////////////////////////////////////////////////////
/// \file functional.hpp
///
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMERIC_FUNCTIONAL_HPP_EAN_08_12_2005
#define BOOST_NUMERIC_FUNCTIONAL_HPP_EAN_08_12_2005
#include <limits>
#include <functional>
#include <boost/static_assert.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/and.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/type_traits/add_reference.hpp>
#include <boost/type_traits/is_empty.hpp>
#include <boost/type_traits/is_integral.hpp>
#include <boost/type_traits/is_floating_point.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/typeof/typeof.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
#include <boost/accumulators/numeric/functional_fwd.hpp>
#include <boost/accumulators/numeric/detail/function1.hpp>
#include <boost/accumulators/numeric/detail/function2.hpp>
#include <boost/accumulators/numeric/detail/pod_singleton.hpp>
#ifdef BOOST_NUMERIC_FUNCTIONAL_STD_VECTOR_SUPPORT
# include <boost/accumulators/numeric/functional/vector.hpp>
#endif
#ifdef BOOST_NUMERIC_FUNCTIONAL_STD_VALARRAY_SUPPORT
# include <boost/accumulators/numeric/functional/valarray.hpp>
#endif
#ifdef BOOST_NUMERIC_FUNCTIONAL_STD_COMPLEX_SUPPORT
# include <boost/accumulators/numeric/functional/complex.hpp>
#endif
/// INTERNAL ONLY
///
#define BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
#ifdef BOOST_NUMERIC_FUNCTIONAL_DOXYGEN_INVOKED
// Hack to make Doxygen show the inheritance relationships
/// INTERNAL ONLY
///
namespace std
{
/// INTERNAL ONLY
///
template<class Arg, class Ret> struct unary_function {};
/// INTERNAL ONLY
///
template<class Left, class Right, class Ret> struct binary_function {};
}
#endif
namespace boost { namespace numeric
{
namespace functional
{
/// INTERNAL ONLY
///
template<typename A0, typename A1>
struct are_integral
: mpl::and_<is_integral<A0>, is_integral<A1> >
{};
template<typename Left, typename Right>
struct left_ref
{
typedef Left &type;
};
namespace detail
{
template<typename T>
T &lvalue_of();
}
}
// TODO: handle complex weight, valarray, MTL vectors
/// INTERNAL ONLY
///
#define BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(Name, Op) \
namespace functional \
{ \
template<typename Arg> \
struct result_of_ ## Name \
{ \
BOOST_TYPEOF_NESTED_TYPEDEF_TPL( \
nested \
, Op boost::numeric::functional::detail::lvalue_of<Arg>() \
) \
typedef typename nested::type type; \
}; \
template<typename Arg, typename EnableIf> \
struct Name ## _base \
{ \
typedef typename remove_const<Arg>::type argument_type; \
typedef typename result_of_ ## Name<Arg>::type result_type; \
typename result_of_ ## Name<Arg>::type operator ()(Arg &arg) const \
{ \
return Op arg; \
} \
}; \
template<typename Arg, typename ArgTag> \
struct Name \
: Name ## _base<Arg, void> \
{}; \
} \
namespace op \
{ \
struct Name \
: boost::detail::function1<functional::Name<_, functional::tag<_> > > \
{}; \
} \
namespace \
{ \
op::Name const &Name = boost::detail::pod_singleton<op::Name>::instance; \
} \
/**/
/// INTERNAL ONLY
///
#define BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(Name, Op, RetType) \
namespace functional \
{ \
template<typename Left, typename Right, typename EnableIf> \
struct result_of_ ## Name \
{ \
RetType(Left, Op, Right) \
}; \
template<typename Left, typename Right, typename EnableIf> \
struct Name ## _base \
{ \
typedef typename remove_const<Left>::type first_argument_type; \
typedef typename remove_const<Right>::type second_argument_type; \
typedef typename result_of_ ## Name<Left, Right>::type result_type; \
typename result_of_ ## Name<Left, Right>::type \
operator ()(Left &left, Right &right) const \
{ \
return left Op right; \
} \
}; \
template<typename Left, typename Right, typename LeftTag, typename RightTag> \
struct Name \
: Name ## _base<Left, Right, void> \
{}; \
} \
namespace op \
{ \
struct Name \
: boost::detail::function2< \
functional::Name<_1, _2, functional::tag<_1>, functional::tag<_2> > \
> \
{}; \
} \
namespace \
{ \
op::Name const &Name = boost::detail::pod_singleton<op::Name>::instance; \
} \
BOOST_ACCUMULATORS_IGNORE_GLOBAL(Name) \
/**/
/// INTERNAL ONLY
///
#define BOOST_NUMERIC_FUNCTIONAL_DEDUCED(Left, Op, Right) \
BOOST_TYPEOF_NESTED_TYPEDEF_TPL( \
nested \
, boost::numeric::functional::detail::lvalue_of<Left>() Op \
boost::numeric::functional::detail::lvalue_of<Right>() \
) \
typedef typename nested::type type; \
/**/
/// INTERNAL ONLY
///
#define BOOST_NUMERIC_FUNCTIONAL_LEFT(Left, Op, Right) \
typedef Left &type; \
/**/
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(plus, +, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(minus, -, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(multiplies, *, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(divides, /, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(modulus, %, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(greater, >, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(greater_equal, >=, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(less, <, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(less_equal, <=, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(equal_to, ==, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(not_equal_to, !=, BOOST_NUMERIC_FUNCTIONAL_DEDUCED)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(assign, =, BOOST_NUMERIC_FUNCTIONAL_LEFT)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(plus_assign, +=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(minus_assign, -=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(multiplies_assign, *=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(divides_assign, /=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP(modulus_assign, %=, BOOST_NUMERIC_FUNCTIONAL_LEFT)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(unary_plus, +)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(unary_minus, -)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(complement, ~)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP(logical_not, !)
#undef BOOST_NUMERIC_FUNCTIONAL_LEFT
#undef BOOST_NUMERIC_FUNCTIONAL_DEDUCED
#undef BOOST_NUMERIC_FUNCTIONAL_DEFINE_UNARY_OP
#undef BOOST_NUMERIC_FUNCTIONAL_DEFINE_BINARY_OP
namespace functional
{
template<typename Left, typename Right, typename EnableIf>
struct min_assign_base
{
typedef Left first_argument_type;
typedef Right second_argument_type;
typedef void result_type;
void operator ()(Left &left, Right &right) const
{
if(numeric::less(right, left))
{
left = right;
}
}
};
template<typename Left, typename Right, typename EnableIf>
struct max_assign_base
{
typedef Left first_argument_type;
typedef Right second_argument_type;
typedef void result_type;
void operator ()(Left &left, Right &right) const
{
if(numeric::greater(right, left))
{
left = right;
}
}
};
template<typename Left, typename Right, typename EnableIf>
struct fdiv_base
: functional::divides<Left, Right>
{};
// partial specialization that promotes the arguments to double for
// integral division.
template<typename Left, typename Right>
struct fdiv_base<Left, Right, typename enable_if<are_integral<Left, Right> >::type>
: functional::divides<double const, double const>
{};
template<typename To, typename From, typename EnableIf>
struct promote_base
{
typedef From argument_type;
typedef To result_type;
To operator ()(From &from) const
{
return from;
}
};
template<typename ToFrom>
struct promote_base<ToFrom, ToFrom, void>
{
typedef ToFrom argument_type;
typedef ToFrom result_type;
ToFrom &operator ()(ToFrom &tofrom)
{
return tofrom;
}
};
template<typename Arg, typename EnableIf>
struct as_min_base
{
BOOST_STATIC_ASSERT(std::numeric_limits<typename remove_const<Arg>::type>::is_specialized);
typedef Arg argument_type;
typedef typename remove_const<Arg>::type result_type;
typename remove_const<Arg>::type operator ()(Arg &) const
{
return (std::numeric_limits<typename remove_const<Arg>::type>::min)();
}
};
template<typename Arg>
struct as_min_base<Arg, typename enable_if<is_floating_point<Arg> >::type>
{
BOOST_STATIC_ASSERT(std::numeric_limits<typename remove_const<Arg>::type>::is_specialized);
typedef Arg argument_type;
typedef typename remove_const<Arg>::type result_type;
typename remove_const<Arg>::type operator ()(Arg &) const
{
return -(std::numeric_limits<typename remove_const<Arg>::type>::max)();
}
};
template<typename Arg, typename EnableIf>
struct as_max_base
{
BOOST_STATIC_ASSERT(std::numeric_limits<typename remove_const<Arg>::type>::is_specialized);
typedef Arg argument_type;
typedef typename remove_const<Arg>::type result_type;
typename remove_const<Arg>::type operator ()(Arg &) const
{
return (std::numeric_limits<typename remove_const<Arg>::type>::max)();
}
};
template<typename Arg, typename EnableIf>
struct as_zero_base
{
typedef Arg argument_type;
typedef typename remove_const<Arg>::type result_type;
typename remove_const<Arg>::type operator ()(Arg &) const
{
return numeric::zero<typename remove_const<Arg>::type>::value;
}
};
template<typename Arg, typename EnableIf>
struct as_one_base
{
typedef Arg argument_type;
typedef typename remove_const<Arg>::type result_type;
typename remove_const<Arg>::type operator ()(Arg &) const
{
return numeric::one<typename remove_const<Arg>::type>::value;
}
};
template<typename To, typename From, typename ToTag, typename FromTag>
struct promote
: promote_base<To, From, void>
{};
template<typename Left, typename Right, typename LeftTag, typename RightTag>
struct min_assign
: min_assign_base<Left, Right, void>
{};
template<typename Left, typename Right, typename LeftTag, typename RightTag>
struct max_assign
: max_assign_base<Left, Right, void>
{};
template<typename Left, typename Right, typename LeftTag, typename RightTag>
struct fdiv
: fdiv_base<Left, Right, void>
{};
/// INTERNAL ONLY
/// For back-compat only. Use fdiv.
template<typename Left, typename Right, typename LeftTag, typename RightTag>
struct average
: fdiv<Left, Right, LeftTag, RightTag>
{};
template<typename Arg, typename Tag>
struct as_min
: as_min_base<Arg, void>
{};
template<typename Arg, typename Tag>
struct as_max
: as_max_base<Arg, void>
{};
template<typename Arg, typename Tag>
struct as_zero
: as_zero_base<Arg, void>
{};
template<typename Arg, typename Tag>
struct as_one
: as_one_base<Arg, void>
{};
}
namespace op
{
template<typename To>
struct promote
: boost::detail::function1<functional::promote<To, _, typename functional::tag<To>::type, functional::tag<_> > >
{};
struct min_assign
: boost::detail::function2<functional::min_assign<_1, _2, functional::tag<_1>, functional::tag<_2> > >
{};
struct max_assign
: boost::detail::function2<functional::max_assign<_1, _2, functional::tag<_1>, functional::tag<_2> > >
{};
struct fdiv
: boost::detail::function2<functional::fdiv<_1, _2, functional::tag<_1>, functional::tag<_2> > >
{};
/// INTERNAL ONLY
struct average
: boost::detail::function2<functional::fdiv<_1, _2, functional::tag<_1>, functional::tag<_2> > >
{};
struct as_min
: boost::detail::function1<functional::as_min<_, functional::tag<_> > >
{};
struct as_max
: boost::detail::function1<functional::as_max<_, functional::tag<_> > >
{};
struct as_zero
: boost::detail::function1<functional::as_zero<_, functional::tag<_> > >
{};
struct as_one
: boost::detail::function1<functional::as_one<_, functional::tag<_> > >
{};
}
namespace
{
op::min_assign const &min_assign = boost::detail::pod_singleton<op::min_assign>::instance;
op::max_assign const &max_assign = boost::detail::pod_singleton<op::max_assign>::instance;
op::fdiv const &fdiv = boost::detail::pod_singleton<op::fdiv>::instance;
op::fdiv const &average = boost::detail::pod_singleton<op::fdiv>::instance; ///< INTERNAL ONLY
op::as_min const &as_min = boost::detail::pod_singleton<op::as_min>::instance;
op::as_max const &as_max = boost::detail::pod_singleton<op::as_max>::instance;
op::as_zero const &as_zero = boost::detail::pod_singleton<op::as_zero>::instance;
op::as_one const &as_one = boost::detail::pod_singleton<op::as_one>::instance;
BOOST_ACCUMULATORS_IGNORE_GLOBAL(min_assign)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(max_assign)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(fdiv)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(average)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(as_min)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(as_max)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(as_zero)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(as_one)
}
///////////////////////////////////////////////////////////////////////////////
// promote
template<typename To, typename From>
typename lazy_disable_if<is_const<From>, mpl::if_<is_same<To, From>, To &, To> >::type
promote(From &from)
{
return functional::promote<To, From>()(from);
}
template<typename To, typename From>
typename mpl::if_<is_same<To const, From const>, To const &, To const>::type
promote(From const &from)
{
return functional::promote<To const, From const>()(from);
}
template<typename T>
struct default_
{
typedef default_ type;
typedef T value_type;
static T const value;
operator T const & () const
{
return default_::value;
}
};
template<typename T>
T const default_<T>::value = T();
template<typename T>
struct one
{
typedef one type;
typedef T value_type;
static T const value;
operator T const & () const
{
return one::value;
}
};
template<typename T>
T const one<T>::value = T(1);
template<typename T>
struct zero
{
typedef zero type;
typedef T value_type;
static T const value;
operator T const & () const
{
return zero::value;
}
};
template<typename T>
T const zero<T>::value = T();
template<typename T>
struct one_or_default
: mpl::if_<is_empty<T>, default_<T>, one<T> >::type
{};
template<typename T>
struct zero_or_default
: mpl::if_<is_empty<T>, default_<T>, zero<T> >::type
{};
}} // namespace boost::numeric
#endif
@@ -0,0 +1,82 @@
///////////////////////////////////////////////////////////////////////////////
/// \file complex.hpp
///
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMERIC_FUNCTIONAL_COMPLEX_HPP_EAN_01_17_2006
#define BOOST_NUMERIC_FUNCTIONAL_COMPLEX_HPP_EAN_01_17_2006
#ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
# error Include this file before boost/accumulators/numeric/functional.hpp
#endif
#include <complex>
#include <boost/mpl/or.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/typeof/std/complex.hpp>
#include <boost/accumulators/numeric/functional_fwd.hpp>
namespace boost { namespace numeric { namespace operators
{
// So that the stats compile when Sample type is std::complex
template<typename T, typename U>
typename
disable_if<
mpl::or_<is_same<T, U>, is_same<std::complex<T>, U> >
, std::complex<T>
>::type
operator *(std::complex<T> ri, U const &u)
{
// BUGBUG promote result to typeof(T()*u) ?
return ri *= static_cast<T>(u);
}
template<typename T, typename U>
typename
disable_if<
mpl::or_<is_same<T, U>, is_same<std::complex<T>, U> >
, std::complex<T>
>::type
operator /(std::complex<T> ri, U const &u)
{
// BUGBUG promote result to typeof(T()*u) ?
return ri /= static_cast<T>(u);
}
}}} // namespace boost::numeric::operators
namespace boost { namespace numeric
{
namespace detail
{
template<typename T>
struct one_complex
{
static std::complex<T> const value;
};
template<typename T>
std::complex<T> const one_complex<T>::value
= std::complex<T>(numeric::one<T>::value, numeric::one<T>::value);
}
/// INTERNAL ONLY
///
template<typename T>
struct one<std::complex<T> >
: detail::one_complex<T>
{
typedef one type;
typedef std::complex<T> value_type;
operator value_type const & () const
{
return detail::one_complex<T>::value;
}
};
}} // namespace boost::numeric
#endif
@@ -0,0 +1,362 @@
///////////////////////////////////////////////////////////////////////////////
/// \file valarray.hpp
///
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMERIC_FUNCTIONAL_VALARRAY_HPP_EAN_12_12_2005
#define BOOST_NUMERIC_FUNCTIONAL_VALARRAY_HPP_EAN_12_12_2005
#ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
# error Include this file before boost/accumulators/numeric/functional.hpp
#endif
#include <valarray>
#include <functional>
#include <boost/assert.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/not.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_scalar.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/typeof/std/valarray.hpp>
#include <boost/accumulators/numeric/functional_fwd.hpp>
namespace boost { namespace numeric
{
namespace operators
{
namespace acc_detail
{
template<typename Fun>
struct make_valarray
{
typedef std::valarray<typename Fun::result_type> type;
};
}
///////////////////////////////////////////////////////////////////////////////
// Handle valarray<Left> / Right where Right is a scalar and Right != Left.
template<typename Left, typename Right>
typename lazy_enable_if<
mpl::and_<is_scalar<Right>, mpl::not_<is_same<Left, Right> > >
, acc_detail::make_valarray<functional::divides<Left, Right> >
>::type
operator /(std::valarray<Left> const &left, Right const &right)
{
typedef typename functional::divides<Left, Right>::result_type value_type;
std::valarray<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::divides(left[i], right);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle valarray<Left> * Right where Right is a scalar and Right != Left.
template<typename Left, typename Right>
typename lazy_enable_if<
mpl::and_<is_scalar<Right>, mpl::not_<is_same<Left, Right> > >
, acc_detail::make_valarray<functional::multiplies<Left, Right> >
>::type
operator *(std::valarray<Left> const &left, Right const &right)
{
typedef typename functional::multiplies<Left, Right>::result_type value_type;
std::valarray<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::multiplies(left[i], right);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle valarray<Left> + valarray<Right> where Right != Left.
template<typename Left, typename Right>
typename lazy_disable_if<
is_same<Left, Right>
, acc_detail::make_valarray<functional::plus<Left, Right> >
>::type
operator +(std::valarray<Left> const &left, std::valarray<Right> const &right)
{
typedef typename functional::plus<Left, Right>::result_type value_type;
std::valarray<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::plus(left[i], right[i]);
}
return result;
}
}
namespace functional
{
struct std_valarray_tag;
template<typename T>
struct tag<std::valarray<T> >
{
typedef std_valarray_tag type;
};
#ifdef __GLIBCXX__
template<typename T, typename U>
struct tag<std::_Expr<T, U> >
{
typedef std_valarray_tag type;
};
#endif
/// INTERNAL ONLY
///
// This is necessary because the GCC stdlib uses expression templates, and
// typeof(som-valarray-expression) is not an instance of std::valarray
#define BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(Name, Op) \
template<typename Left, typename Right> \
struct Name<Left, Right, std_valarray_tag, std_valarray_tag> \
{ \
typedef Left first_argument_type; \
typedef Right second_argument_type; \
typedef typename Left::value_type left_value_type; \
typedef typename Right::value_type right_value_type; \
typedef \
std::valarray< \
typename Name<left_value_type, right_value_type>::result_type \
> \
result_type; \
result_type \
operator ()(Left &left, Right &right) const \
{ \
return numeric::promote<std::valarray<left_value_type> >(left) \
Op numeric::promote<std::valarray<right_value_type> >(right); \
} \
}; \
template<typename Left, typename Right> \
struct Name<Left, Right, std_valarray_tag, void> \
{ \
typedef Left first_argument_type; \
typedef Right second_argument_type; \
typedef typename Left::value_type left_value_type; \
typedef \
std::valarray< \
typename Name<left_value_type, Right>::result_type \
> \
result_type; \
result_type \
operator ()(Left &left, Right &right) const \
{ \
return numeric::promote<std::valarray<left_value_type> >(left) Op right;\
} \
}; \
template<typename Left, typename Right> \
struct Name<Left, Right, void, std_valarray_tag> \
{ \
typedef Left first_argument_type; \
typedef Right second_argument_type; \
typedef typename Right::value_type right_value_type; \
typedef \
std::valarray< \
typename Name<Left, right_value_type>::result_type \
> \
result_type; \
result_type \
operator ()(Left &left, Right &right) const \
{ \
return left Op numeric::promote<std::valarray<right_value_type> >(right);\
} \
};
BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(plus, +)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(minus, -)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(multiplies, *)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(divides, /)
BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP(modulus, %)
#undef BOOST_NUMERIC_FUNCTIONAL_DEFINE_VALARRAY_BIN_OP
///////////////////////////////////////////////////////////////////////////////
// element-wise min of std::valarray
template<typename Left, typename Right>
struct min_assign<Left, Right, std_valarray_tag, std_valarray_tag>
{
typedef Left first_argument_type;
typedef Right second_argument_type;
typedef void result_type;
void operator ()(Left &left, Right &right) const
{
BOOST_ASSERT(left.size() == right.size());
for(std::size_t i = 0, size = left.size(); i != size; ++i)
{
if(numeric::less(right[i], left[i]))
{
left[i] = right[i];
}
}
}
};
///////////////////////////////////////////////////////////////////////////////
// element-wise max of std::valarray
template<typename Left, typename Right>
struct max_assign<Left, Right, std_valarray_tag, std_valarray_tag>
{
typedef Left first_argument_type;
typedef Right second_argument_type;
typedef void result_type;
void operator ()(Left &left, Right &right) const
{
BOOST_ASSERT(left.size() == right.size());
for(std::size_t i = 0, size = left.size(); i != size; ++i)
{
if(numeric::greater(right[i], left[i]))
{
left[i] = right[i];
}
}
}
};
// partial specialization of numeric::fdiv<> for std::valarray.
template<typename Left, typename Right, typename RightTag>
struct fdiv<Left, Right, std_valarray_tag, RightTag>
: mpl::if_<
are_integral<typename Left::value_type, Right>
, divides<Left, double const>
, divides<Left, Right>
>::type
{};
// promote
template<typename To, typename From>
struct promote<To, From, std_valarray_tag, std_valarray_tag>
{
typedef From argument_type;
typedef To result_type;
To operator ()(From &arr) const
{
typename remove_const<To>::type res(arr.size());
for(std::size_t i = 0, size = arr.size(); i != size; ++i)
{
res[i] = numeric::promote<typename To::value_type>(arr[i]);
}
return res;
}
};
template<typename ToFrom>
struct promote<ToFrom, ToFrom, std_valarray_tag, std_valarray_tag>
{
typedef ToFrom argument_type;
typedef ToFrom result_type;
ToFrom &operator ()(ToFrom &tofrom) const
{
return tofrom;
}
};
// for "promoting" a std::valarray<bool> to a bool, useful for
// comparing 2 valarrays for equality:
// if(numeric::promote<bool>(a == b))
template<typename From>
struct promote<bool, From, void, std_valarray_tag>
{
typedef From argument_type;
typedef bool result_type;
bool operator ()(From &arr) const
{
BOOST_MPL_ASSERT((is_same<bool, typename From::value_type>));
for(std::size_t i = 0, size = arr.size(); i != size; ++i)
{
if(!arr[i])
{
return false;
}
}
return true;
}
};
template<typename From>
struct promote<bool const, From, void, std_valarray_tag>
: promote<bool, From, void, std_valarray_tag>
{};
///////////////////////////////////////////////////////////////////////////////
// functional::as_min
template<typename T>
struct as_min<T, std_valarray_tag>
{
typedef T argument_type;
typedef typename remove_const<T>::type result_type;
typename remove_const<T>::type operator ()(T &arr) const
{
return 0 == arr.size()
? T()
: T(numeric::as_min(arr[0]), arr.size());
}
};
///////////////////////////////////////////////////////////////////////////////
// functional::as_max
template<typename T>
struct as_max<T, std_valarray_tag>
{
typedef T argument_type;
typedef typename remove_const<T>::type result_type;
typename remove_const<T>::type operator ()(T &arr) const
{
return 0 == arr.size()
? T()
: T(numeric::as_max(arr[0]), arr.size());
}
};
///////////////////////////////////////////////////////////////////////////////
// functional::as_zero
template<typename T>
struct as_zero<T, std_valarray_tag>
{
typedef T argument_type;
typedef typename remove_const<T>::type result_type;
typename remove_const<T>::type operator ()(T &arr) const
{
return 0 == arr.size()
? T()
: T(numeric::as_zero(arr[0]), arr.size());
}
};
///////////////////////////////////////////////////////////////////////////////
// functional::as_one
template<typename T>
struct as_one<T, std_valarray_tag>
{
typedef T argument_type;
typedef typename remove_const<T>::type result_type;
typename remove_const<T>::type operator ()(T &arr) const
{
return 0 == arr.size()
? T()
: T(numeric::as_one(arr[0]), arr.size());
}
};
} // namespace functional
}} // namespace boost::numeric
#endif
@@ -0,0 +1,347 @@
///////////////////////////////////////////////////////////////////////////////
/// \file vector.hpp
///
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMERIC_FUNCTIONAL_VECTOR_HPP_EAN_12_12_2005
#define BOOST_NUMERIC_FUNCTIONAL_VECTOR_HPP_EAN_12_12_2005
#ifdef BOOST_NUMERIC_FUNCTIONAL_HPP_INCLUDED
# error Include this file before boost/accumulators/numeric/functional.hpp
#endif
#include <vector>
#include <functional>
#include <boost/assert.hpp>
#include <boost/mpl/and.hpp>
#include <boost/mpl/not.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_scalar.hpp>
#include <boost/type_traits/remove_const.hpp>
#include <boost/typeof/std/vector.hpp>
#include <boost/accumulators/numeric/functional_fwd.hpp>
namespace boost { namespace numeric
{
namespace operators
{
namespace acc_detail
{
template<typename Fun>
struct make_vector
{
typedef std::vector<typename Fun::result_type> type;
};
}
///////////////////////////////////////////////////////////////////////////////
// Handle vector<Left> / Right where Right is a scalar.
template<typename Left, typename Right>
typename lazy_enable_if<
is_scalar<Right>
, acc_detail::make_vector<functional::divides<Left, Right> >
>::type
operator /(std::vector<Left> const &left, Right const &right)
{
typedef typename functional::divides<Left, Right>::result_type value_type;
std::vector<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::divides(left[i], right);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle vector<Left> / vector<Right>.
template<typename Left, typename Right>
std::vector<typename functional::divides<Left, Right>::result_type>
operator /(std::vector<Left> const &left, std::vector<Right> const &right)
{
typedef typename functional::divides<Left, Right>::result_type value_type;
std::vector<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::divides(left[i], right[i]);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle vector<Left> * Right where Right is a scalar.
template<typename Left, typename Right>
typename lazy_enable_if<
is_scalar<Right>
, acc_detail::make_vector<functional::multiplies<Left, Right> >
>::type
operator *(std::vector<Left> const &left, Right const &right)
{
typedef typename functional::multiplies<Left, Right>::result_type value_type;
std::vector<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::multiplies(left[i], right);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle Left * vector<Right> where Left is a scalar.
template<typename Left, typename Right>
typename lazy_enable_if<
is_scalar<Left>
, acc_detail::make_vector<functional::multiplies<Left, Right> >
>::type
operator *(Left const &left, std::vector<Right> const &right)
{
typedef typename functional::multiplies<Left, Right>::result_type value_type;
std::vector<value_type> result(right.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::multiplies(left, right[i]);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle vector<Left> * vector<Right>
template<typename Left, typename Right>
std::vector<typename functional::multiplies<Left, Right>::result_type>
operator *(std::vector<Left> const &left, std::vector<Right> const &right)
{
typedef typename functional::multiplies<Left, Right>::result_type value_type;
std::vector<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::multiplies(left[i], right[i]);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle vector<Left> + vector<Right>
template<typename Left, typename Right>
std::vector<typename functional::plus<Left, Right>::result_type>
operator +(std::vector<Left> const &left, std::vector<Right> const &right)
{
typedef typename functional::plus<Left, Right>::result_type value_type;
std::vector<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::plus(left[i], right[i]);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle vector<Left> - vector<Right>
template<typename Left, typename Right>
std::vector<typename functional::minus<Left, Right>::result_type>
operator -(std::vector<Left> const &left, std::vector<Right> const &right)
{
typedef typename functional::minus<Left, Right>::result_type value_type;
std::vector<value_type> result(left.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::minus(left[i], right[i]);
}
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Handle vector<Left> += vector<Left>
template<typename Left>
std::vector<Left> &
operator +=(std::vector<Left> &left, std::vector<Left> const &right)
{
BOOST_ASSERT(left.size() == right.size());
for(std::size_t i = 0, size = left.size(); i != size; ++i)
{
numeric::plus_assign(left[i], right[i]);
}
return left;
}
///////////////////////////////////////////////////////////////////////////////
// Handle -vector<Arg>
template<typename Arg>
std::vector<typename functional::unary_minus<Arg>::result_type>
operator -(std::vector<Arg> const &arg)
{
typedef typename functional::unary_minus<Arg>::result_type value_type;
std::vector<value_type> result(arg.size());
for(std::size_t i = 0, size = result.size(); i != size; ++i)
{
result[i] = numeric::unary_minus(arg[i]);
}
return result;
}
}
namespace functional
{
struct std_vector_tag;
template<typename T, typename Al>
struct tag<std::vector<T, Al> >
{
typedef std_vector_tag type;
};
///////////////////////////////////////////////////////////////////////////////
// element-wise min of std::vector
template<typename Left, typename Right>
struct min_assign<Left, Right, std_vector_tag, std_vector_tag>
{
typedef Left first_argument_type;
typedef Right second_argument_type;
typedef void result_type;
void operator ()(Left &left, Right &right) const
{
BOOST_ASSERT(left.size() == right.size());
for(std::size_t i = 0, size = left.size(); i != size; ++i)
{
if(numeric::less(right[i], left[i]))
{
left[i] = right[i];
}
}
}
};
///////////////////////////////////////////////////////////////////////////////
// element-wise max of std::vector
template<typename Left, typename Right>
struct max_assign<Left, Right, std_vector_tag, std_vector_tag>
{
typedef Left first_argument_type;
typedef Right second_argument_type;
typedef void result_type;
void operator ()(Left &left, Right &right) const
{
BOOST_ASSERT(left.size() == right.size());
for(std::size_t i = 0, size = left.size(); i != size; ++i)
{
if(numeric::greater(right[i], left[i]))
{
left[i] = right[i];
}
}
}
};
// partial specialization for std::vector.
template<typename Left, typename Right>
struct fdiv<Left, Right, std_vector_tag, void>
: mpl::if_<
are_integral<typename Left::value_type, Right>
, divides<Left, double const>
, divides<Left, Right>
>::type
{};
// promote
template<typename To, typename From>
struct promote<To, From, std_vector_tag, std_vector_tag>
{
typedef From argument_type;
typedef To result_type;
To operator ()(From &arr) const
{
typename remove_const<To>::type res(arr.size());
for(std::size_t i = 0, size = arr.size(); i != size; ++i)
{
res[i] = numeric::promote<typename To::value_type>(arr[i]);
}
return res;
}
};
template<typename ToFrom>
struct promote<ToFrom, ToFrom, std_vector_tag, std_vector_tag>
{
typedef ToFrom argument_type;
typedef ToFrom result_type;
ToFrom &operator ()(ToFrom &tofrom) const
{
return tofrom;
}
};
///////////////////////////////////////////////////////////////////////////////
// functional::as_min
template<typename T>
struct as_min<T, std_vector_tag>
{
typedef T argument_type;
typedef typename remove_const<T>::type result_type;
typename remove_const<T>::type operator ()(T &arr) const
{
return 0 == arr.size()
? T()
: T(arr.size(), numeric::as_min(arr[0]));
}
};
///////////////////////////////////////////////////////////////////////////////
// functional::as_max
template<typename T>
struct as_max<T, std_vector_tag>
{
typedef T argument_type;
typedef typename remove_const<T>::type result_type;
typename remove_const<T>::type operator ()(T &arr) const
{
return 0 == arr.size()
? T()
: T(arr.size(), numeric::as_max(arr[0]));
}
};
///////////////////////////////////////////////////////////////////////////////
// functional::as_zero
template<typename T>
struct as_zero<T, std_vector_tag>
{
typedef T argument_type;
typedef typename remove_const<T>::type result_type;
typename remove_const<T>::type operator ()(T &arr) const
{
return 0 == arr.size()
? T()
: T(arr.size(), numeric::as_zero(arr[0]));
}
};
///////////////////////////////////////////////////////////////////////////////
// functional::as_one
template<typename T>
struct as_one<T, std_vector_tag>
{
typedef T argument_type;
typedef typename remove_const<T>::type result_type;
typename remove_const<T>::type operator ()(T &arr) const
{
return 0 == arr.size()
? T()
: T(arr.size(), numeric::as_one(arr[0]));
}
};
} // namespace functional
}} // namespace boost::numeric
#endif
@@ -0,0 +1,221 @@
///////////////////////////////////////////////////////////////////////////////
/// \file functional_fwd.hpp
///
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_NUMERIC_FUNCTIONAL_FWD_HPP_EAN_08_12_2005
#define BOOST_NUMERIC_FUNCTIONAL_FWD_HPP_EAN_08_12_2005
#include <boost/mpl/if.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/utility/enable_if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/type_traits/is_const.hpp>
namespace boost { namespace numeric
{
// For using directives -- this namespace may be re-opened elsewhere
namespace operators
{}
namespace op
{
using mpl::_;
using mpl::_1;
using mpl::_2;
}
namespace functional
{
using namespace operators;
template<typename T>
struct tag
{
typedef void type;
};
template<typename T>
struct tag<T const>
: tag<T>
{};
template<typename T>
struct tag<T volatile>
: tag<T>
{};
template<typename T>
struct tag<T const volatile>
: tag<T>
{};
template<typename T>
struct static_;
template<typename A0, typename A1>
struct are_integral;
}
/// INTERNAL ONLY
///
#define BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(Name, Op) \
namespace functional \
{ \
template<typename Arg, typename EnableIf = void> \
struct Name ## _base; \
template<typename Arg, typename ArgTag = typename tag<Arg>::type> \
struct Name; \
} \
namespace op \
{ \
struct Name; \
} \
namespace \
{ \
extern op::Name const &Name; \
}
/// INTERNAL ONLY
///
#define BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(Name) \
namespace functional \
{ \
template<typename Left, typename Right, typename EnableIf = void> \
struct result_of_ ## Name; \
template<typename Left, typename Right, typename EnableIf = void> \
struct Name ## _base; \
template< \
typename Left \
, typename Right \
, typename LeftTag = typename tag<Left>::type \
, typename RightTag = typename tag<Right>::type \
> \
struct Name; \
} \
namespace op \
{ \
struct Name; \
} \
namespace \
{ \
extern op::Name const &Name; \
}
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(plus)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(minus)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(multiplies)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(divides)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(modulus)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(greater)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(greater_equal)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(less)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(less_equal)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(equal_to)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(not_equal_to)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(assign)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(plus_assign)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(minus_assign)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(multiplies_assign)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(divides_assign)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP(modulus_assign)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(unary_plus, +)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(unary_minus, -)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(complement, ~)
BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP(logical_not, !)
#undef BOOST_NUMERIC_FUNCTIONAL_DECLARE_UNARY_OP
#undef BOOST_NUMERIC_FUNCTIONAL_DECLARE_BINARY_OP
namespace functional
{
template<typename To, typename From, typename EnableIf = void>
struct promote_base;
template<typename Left, typename Right, typename EnableIf = void>
struct min_assign_base;
template<typename Left, typename Right, typename EnableIf = void>
struct max_assign_base;
template<typename Left, typename Right, typename EnableIf = void>
struct fdiv_base;
template<typename Arg, typename EnableIf = void>
struct as_min_base;
template<typename Arg, typename EnableIf = void>
struct as_max_base;
template<typename Arg, typename EnableIf = void>
struct as_zero_base;
template<typename Arg, typename EnableIf = void>
struct as_one_base;
template<typename To, typename From, typename ToTag = typename tag<To>::type, typename FromTag = typename tag<From>::type>
struct promote;
template<typename Left, typename Right, typename LeftTag = typename tag<Left>::type, typename RightTag = typename tag<Right>::type>
struct min_assign;
template<typename Left, typename Right, typename LeftTag = typename tag<Left>::type, typename RightTag = typename tag<Right>::type>
struct max_assign;
template<typename Left, typename Right, typename LeftTag = typename tag<Left>::type, typename RightTag = typename tag<Right>::type>
struct fdiv;
template<typename Arg, typename Tag = typename tag<Arg>::type>
struct as_min;
template<typename Arg, typename Tag = typename tag<Arg>::type>
struct as_max;
template<typename Arg, typename Tag = typename tag<Arg>::type>
struct as_zero;
template<typename Arg, typename Tag = typename tag<Arg>::type>
struct as_one;
}
namespace op
{
template<typename To>
struct promote;
struct min_assign;
struct max_assign;
struct fdiv;
struct as_min;
struct as_max;
struct as_zero;
struct as_one;
}
namespace
{
extern op::min_assign const &min_assign;
extern op::max_assign const &max_assign;
extern op::fdiv const &fdiv;
extern op::as_min const &as_min;
extern op::as_max const &as_max;
extern op::as_zero const &as_zero;
extern op::as_one const &as_one;
}
template<typename To, typename From>
typename lazy_disable_if<is_const<From>, mpl::if_<is_same<To, From>, To &, To> >::type
promote(From &from);
template<typename To, typename From>
typename mpl::if_<is_same<To const, From const>, To const &, To const>::type
promote(From const &from);
template<typename T>
struct default_;
template<typename T>
struct one;
template<typename T>
struct zero;
template<typename T>
struct one_or_default;
template<typename T>
struct zero_or_default;
}} // namespace boost::numeric
#endif
@@ -0,0 +1,61 @@
///////////////////////////////////////////////////////////////////////////////
/// \file statistics.hpp
/// Includes all of the Statistical Accumulators Library
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_HPP_EAN_01_17_2006
#define BOOST_ACCUMULATORS_STATISTICS_HPP_EAN_01_17_2006
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/covariance.hpp>
#include <boost/accumulators/statistics/density.hpp>
#include <boost/accumulators/statistics/error_of.hpp>
#include <boost/accumulators/statistics/error_of_mean.hpp>
#include <boost/accumulators/statistics/extended_p_square.hpp>
#include <boost/accumulators/statistics/extended_p_square_quantile.hpp>
#include <boost/accumulators/statistics/kurtosis.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/median.hpp>
#include <boost/accumulators/statistics/min.hpp>
#include <boost/accumulators/statistics/moment.hpp>
#include <boost/accumulators/statistics/peaks_over_threshold.hpp>
#include <boost/accumulators/statistics/pot_tail_mean.hpp>
#include <boost/accumulators/statistics/pot_quantile.hpp>
#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>
#include <boost/accumulators/statistics/p_square_quantile.hpp>
#include <boost/accumulators/statistics/skewness.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/sum.hpp>
#include <boost/accumulators/statistics/sum_kahan.hpp>
#include <boost/accumulators/statistics/tail.hpp>
#include <boost/accumulators/statistics/tail_quantile.hpp>
#include <boost/accumulators/statistics/tail_mean.hpp>
#include <boost/accumulators/statistics/tail_variate.hpp>
#include <boost/accumulators/statistics/tail_variate_means.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/accumulators/statistics/weighted_covariance.hpp>
#include <boost/accumulators/statistics/weighted_density.hpp>
#include <boost/accumulators/statistics/weighted_kurtosis.hpp>
#include <boost/accumulators/statistics/weighted_extended_p_square.hpp>
#include <boost/accumulators/statistics/weighted_mean.hpp>
#include <boost/accumulators/statistics/weighted_median.hpp>
#include <boost/accumulators/statistics/weighted_moment.hpp>
#include <boost/accumulators/statistics/weighted_peaks_over_threshold.hpp>
#include <boost/accumulators/statistics/weighted_p_square_cumul_dist.hpp>
#include <boost/accumulators/statistics/weighted_p_square_quantile.hpp>
#include <boost/accumulators/statistics/weighted_skewness.hpp>
#include <boost/accumulators/statistics/weighted_sum.hpp>
#include <boost/accumulators/statistics/weighted_sum_kahan.hpp>
#include <boost/accumulators/statistics/weighted_tail_quantile.hpp>
#include <boost/accumulators/statistics/weighted_tail_mean.hpp>
#include <boost/accumulators/statistics/weighted_tail_variate_means.hpp>
#include <boost/accumulators/statistics/weighted_variance.hpp>
#include <boost/accumulators/statistics/with_error.hpp>
#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
#include <boost/accumulators/statistics/variates/covariate.hpp>
#endif
@@ -0,0 +1,80 @@
///////////////////////////////////////////////////////////////////////////////
// count.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_COUNT_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_STATISTICS_COUNT_HPP_EAN_28_10_2005
#include <boost/mpl/always.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// count_impl
struct count_impl
: accumulator_base
{
// for boost::result_of
typedef std::size_t result_type;
count_impl(dont_care)
: cnt(0)
{
}
void operator ()(dont_care)
{
++this->cnt;
}
result_type result(dont_care) const
{
return this->cnt;
}
private:
std::size_t cnt;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::count
//
namespace tag
{
struct count
: depends_on<>
{
/// INTERNAL ONLY
///
typedef mpl::always<accumulators::impl::count_impl> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::count
//
namespace extract
{
extractor<tag::count> const count = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(count)
}
using extract::count;
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,212 @@
///////////////////////////////////////////////////////////////////////////////
// covariance.hpp
//
// Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_COVARIANCE_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_COVARIANCE_HPP_DE_01_01_2006
#include <vector>
#include <limits>
#include <numeric>
#include <functional>
#include <complex>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/bool.hpp>
#include <boost/range.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/numeric/ublas/io.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/type_traits/is_scalar.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/mean.hpp>
namespace boost { namespace numeric
{
namespace functional
{
struct std_vector_tag;
///////////////////////////////////////////////////////////////////////////////
// functional::outer_product
template<typename Left, typename Right, typename EnableIf = void>
struct outer_product_base
: functional::multiplies<Left, Right>
{};
template<typename Left, typename Right, typename LeftTag = typename tag<Left>::type, typename RightTag = typename tag<Right>::type>
struct outer_product
: outer_product_base<Left, Right, void>
{};
template<typename Left, typename Right>
struct outer_product<Left, Right, std_vector_tag, std_vector_tag>
{
typedef Left first_argument_type;
typedef Right second_argument_type;
typedef
ublas::matrix<
typename functional::multiplies<
typename Left::value_type
, typename Right::value_type
>::result_type
>
result_type;
result_type
operator ()(Left & left, Right & right) const
{
std::size_t left_size = left.size();
std::size_t right_size = right.size();
result_type result(left_size, right_size);
for (std::size_t i = 0; i < left_size; ++i)
for (std::size_t j = 0; j < right_size; ++j)
result(i,j) = numeric::multiplies(left[i], right[j]);
return result;
}
};
}
namespace op
{
struct outer_product
: boost::detail::function2<functional::outer_product<_1, _2, functional::tag<_1>, functional::tag<_2> > >
{};
}
namespace
{
op::outer_product const &outer_product = boost::detail::pod_singleton<op::outer_product>::instance;
}
}}
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// covariance_impl
//
/**
@brief Covariance Estimator
An iterative Monte Carlo estimator for the covariance \f$\mathrm{Cov}(X,X')\f$, where \f$X\f$ is a sample
and \f$X'\f$ is a variate, is given by:
\f[
\hat{c}_n = \frac{n-1}{n} \hat{c}_{n-1} + \frac{1}{n-1}(X_n - \hat{\mu}_n)(X_n' - \hat{\mu}_n'),\quad n\ge2,\quad\hat{c}_1 = 0,
\f]
\f$\hat{\mu}_n\f$ and \f$\hat{\mu}_n'\f$ being the means of the samples and variates.
*/
template<typename Sample, typename VariateType, typename VariateTag>
struct covariance_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type sample_type;
typedef typename numeric::functional::fdiv<VariateType, std::size_t>::result_type variate_type;
// for boost::result_of
typedef typename numeric::functional::outer_product<sample_type, variate_type>::result_type result_type;
template<typename Args>
covariance_impl(Args const &args)
: cov_(
numeric::outer_product(
numeric::fdiv(args[sample | Sample()], (std::size_t)1)
, numeric::fdiv(args[parameter::keyword<VariateTag>::get() | VariateType()], (std::size_t)1)
)
)
{
}
template<typename Args>
void operator ()(Args const &args)
{
std::size_t cnt = count(args);
if (cnt > 1)
{
extractor<tag::mean_of_variates<VariateType, VariateTag> > const some_mean_of_variates = {};
this->cov_ = this->cov_*(cnt-1.)/cnt
+ numeric::outer_product(
some_mean_of_variates(args) - args[parameter::keyword<VariateTag>::get()]
, mean(args) - args[sample]
) / (cnt-1.);
}
}
result_type result(dont_care) const
{
return this->cov_;
}
private:
result_type cov_;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::covariance
//
namespace tag
{
template<typename VariateType, typename VariateTag>
struct covariance
: depends_on<count, mean, mean_of_variates<VariateType, VariateTag> >
{
typedef accumulators::impl::covariance_impl<mpl::_1, VariateType, VariateTag> impl;
};
struct abstract_covariance
: depends_on<>
{
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::covariance
//
namespace extract
{
extractor<tag::abstract_covariance> const covariance = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(covariance)
}
using extract::covariance;
template<typename VariateType, typename VariateTag>
struct feature_of<tag::covariance<VariateType, VariateTag> >
: feature_of<tag::abstract_covariance>
{
};
// So that covariance can be automatically substituted with
// weighted_covariance when the weight parameter is non-void.
template<typename VariateType, typename VariateTag>
struct as_weighted_feature<tag::covariance<VariateType, VariateTag> >
{
typedef tag::weighted_covariance<VariateType, VariateTag> type;
};
template<typename VariateType, typename VariateTag>
struct feature_of<tag::weighted_covariance<VariateType, VariateTag> >
: feature_of<tag::covariance<VariateType, VariateTag> >
{};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,250 @@
///////////////////////////////////////////////////////////////////////////////
// density.hpp
//
// Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_DENSITY_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_DENSITY_HPP_DE_01_01_2006
#include <vector>
#include <limits>
#include <functional>
#include <boost/range.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/max.hpp>
#include <boost/accumulators/statistics/min.hpp>
namespace boost { namespace accumulators
{
///////////////////////////////////////////////////////////////////////////////
// cache_size and num_bins named parameters
//
BOOST_PARAMETER_NESTED_KEYWORD(tag, density_cache_size, cache_size)
BOOST_PARAMETER_NESTED_KEYWORD(tag, density_num_bins, num_bins)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(density_cache_size)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(density_num_bins)
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// density_impl
// density histogram
/**
@brief Histogram density estimator
The histogram density estimator returns a histogram of the sample distribution. The positions and sizes of the bins
are determined using a specifiable number of cached samples (cache_size). The range between the minimum and the
maximum of the cached samples is subdivided into a specifiable number of bins (num_bins) of same size. Additionally,
an under- and an overflow bin is added to capture future under- and overflow samples. Once the bins are determined,
the cached samples and all subsequent samples are added to the correct bins. At the end, a range of std::pair is
return, where each pair contains the position of the bin (lower bound) and the samples count (normalized with the
total number of samples).
@param density_cache_size Number of first samples used to determine min and max.
@param density_num_bins Number of bins (two additional bins collect under- and overflow samples).
*/
template<typename Sample>
struct density_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
typedef std::vector<std::pair<float_type, float_type> > histogram_type;
typedef std::vector<float_type> array_type;
// for boost::result_of
typedef iterator_range<typename histogram_type::iterator> result_type;
template<typename Args>
density_impl(Args const &args)
: cache_size(args[density_cache_size])
, cache(cache_size)
, num_bins(args[density_num_bins])
, samples_in_bin(num_bins + 2, 0.)
, bin_positions(num_bins + 2)
, histogram(
num_bins + 2
, std::make_pair(
numeric::fdiv(args[sample | Sample()],(std::size_t)1)
, numeric::fdiv(args[sample | Sample()],(std::size_t)1)
)
)
, is_dirty(true)
{
}
template<typename Args>
void operator ()(Args const &args)
{
this->is_dirty = true;
std::size_t cnt = count(args);
// Fill up cache with cache_size first samples
if (cnt <= this->cache_size)
{
this->cache[cnt - 1] = args[sample];
}
// Once cache_size samples have been accumulated, create num_bins bins of same size between
// the minimum and maximum of the cached samples as well as under and overflow bins.
// Store their lower bounds (bin_positions) and fill the bins with the cached samples (samples_in_bin).
if (cnt == this->cache_size)
{
float_type minimum = numeric::fdiv((min)(args), (std::size_t)1);
float_type maximum = numeric::fdiv((max)(args), (std::size_t)1);
float_type bin_size = numeric::fdiv(maximum - minimum, this->num_bins );
// determine bin positions (their lower bounds)
for (std::size_t i = 0; i < this->num_bins + 2; ++i)
{
this->bin_positions[i] = minimum + (i - 1.) * bin_size;
}
for (typename array_type::const_iterator iter = this->cache.begin(); iter != this->cache.end(); ++iter)
{
if (*iter < this->bin_positions[1])
{
++(this->samples_in_bin[0]);
}
else if (*iter >= this->bin_positions[this->num_bins + 1])
{
++(this->samples_in_bin[this->num_bins + 1]);
}
else
{
typename array_type::iterator it = std::upper_bound(
this->bin_positions.begin()
, this->bin_positions.end()
, *iter
);
std::size_t d = std::distance(this->bin_positions.begin(), it);
++(this->samples_in_bin[d - 1]);
}
}
}
// Add each subsequent sample to the correct bin
else if (cnt > this->cache_size)
{
if (args[sample] < this->bin_positions[1])
{
++(this->samples_in_bin[0]);
}
else if (args[sample] >= this->bin_positions[this->num_bins + 1])
{
++(this->samples_in_bin[this->num_bins + 1]);
}
else
{
typename array_type::iterator it = std::upper_bound(
this->bin_positions.begin()
, this->bin_positions.end()
, args[sample]
);
std::size_t d = std::distance(this->bin_positions.begin(), it);
++(this->samples_in_bin[d - 1]);
}
}
}
/**
@pre The number of samples must meet or exceed the cache size
*/
template<typename Args>
result_type result(Args const &args) const
{
if (this->is_dirty)
{
this->is_dirty = false;
// creates a vector of std::pair where each pair i holds
// the values bin_positions[i] (x-axis of histogram) and
// samples_in_bin[i] / cnt (y-axis of histogram).
for (std::size_t i = 0; i < this->num_bins + 2; ++i)
{
this->histogram[i] = std::make_pair(this->bin_positions[i], numeric::fdiv(this->samples_in_bin[i], count(args)));
}
}
// returns a range of pairs
return make_iterator_range(this->histogram);
}
private:
std::size_t cache_size; // number of cached samples
array_type cache; // cache to store the first cache_size samples
std::size_t num_bins; // number of bins
array_type samples_in_bin; // number of samples in each bin
array_type bin_positions; // lower bounds of bins
mutable histogram_type histogram; // histogram
mutable bool is_dirty;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::density
//
namespace tag
{
struct density
: depends_on<count, min, max>
, density_cache_size
, density_num_bins
{
/// INTERNAL ONLY
///
typedef accumulators::impl::density_impl<mpl::_1> impl;
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
/// tag::density::cache_size named parameter
/// tag::density::num_bins named parameter
static boost::parameter::keyword<density_cache_size> const cache_size;
static boost::parameter::keyword<density_num_bins> const num_bins;
#endif
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::density
//
namespace extract
{
extractor<tag::density> const density = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(density)
}
using extract::density;
// So that density can be automatically substituted
// with weighted_density when the weight parameter is non-void.
template<>
struct as_weighted_feature<tag::density>
{
typedef tag::weighted_density type;
};
template<>
struct feature_of<tag::weighted_density>
: feature_of<tag::density>
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,99 @@
///////////////////////////////////////////////////////////////////////////////
// error_of.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_HPP_EAN_29_11_2005
#define BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_HPP_EAN_29_11_2005
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
/// INTERNAL ONLY
///
template<typename Feature>
struct this_feature_has_no_error_calculation
: mpl::false_
{
};
///////////////////////////////////////////////////////////////////////////////
// error_of_impl
/// INTERNAL ONLY
///
template<typename Sample, typename Feature>
struct error_of_impl
: accumulator_base
{
// TODO: specialize this on the specific features that have errors we're
// interested in.
BOOST_MPL_ASSERT((this_feature_has_no_error_calculation<Feature>));
// for boost::result_of
typedef int result_type;
error_of_impl(dont_care)
{
}
result_type result(dont_care) const
{
return 0;
}
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::error_of
//
namespace tag
{
template<typename Feature>
struct error_of
: depends_on<Feature>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::error_of_impl<mpl::_1, Feature> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::error_of
//
namespace extract
{
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, error_of, (typename))
}
using extract::error_of;
// make tag::error_of<tag::feature(modifier)> work
template<typename Feature>
struct as_feature<tag::error_of<Feature> >
{
typedef tag::error_of<typename as_feature<Feature>::type> type;
};
// make error_of<tag::mean> work with non-void weights (should become
// error_of<tag::weighted_mean>
template<typename Feature>
struct as_weighted_feature<tag::error_of<Feature> >
{
typedef tag::error_of<typename as_weighted_feature<Feature>::type> type;
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,73 @@
///////////////////////////////////////////////////////////////////////////////
// error_of.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_MEAN_HPP_EAN_27_03_2006
#define BOOST_ACCUMULATORS_STATISTICS_ERROR_OF_MEAN_HPP_EAN_27_03_2006
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/error_of.hpp>
#include <boost/accumulators/statistics/variance.hpp>
#include <boost/accumulators/statistics/count.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// error_of_mean_impl
template<typename Sample, typename Variance>
struct error_of_mean_impl
: accumulator_base
{
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
error_of_mean_impl(dont_care) {}
template<typename Args>
result_type result(Args const &args) const
{
using namespace std;
extractor<Variance> const variance = {};
return sqrt(numeric::fdiv(variance(args), count(args) - 1));
}
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::error_of
//
namespace tag
{
template<>
struct error_of<mean>
: depends_on<lazy_variance, count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::error_of_mean_impl<mpl::_1, lazy_variance> impl;
};
template<>
struct error_of<immediate_mean>
: depends_on<variance, count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::error_of_mean_impl<mpl::_1, variance> impl;
};
}
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,295 @@
///////////////////////////////////////////////////////////////////////////////
// extended_p_square.hpp
//
// Copyright 2005 Daniel Egloff. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_HPP_DE_01_01_2006
#include <vector>
#include <functional>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/permutation_iterator.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/times2_iterator.hpp>
namespace boost { namespace accumulators
{
///////////////////////////////////////////////////////////////////////////////
// probabilities named parameter
//
BOOST_PARAMETER_NESTED_KEYWORD(tag, extended_p_square_probabilities, probabilities)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square_probabilities)
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// extended_p_square_impl
// multiple quantile estimation
/**
@brief Multiple quantile estimation with the extended \f$P^2\f$ algorithm
Extended \f$P^2\f$ algorithm for estimation of several quantiles without storing samples.
Assume that \f$m\f$ quantiles \f$\xi_{p_1}, \ldots, \xi_{p_m}\f$ are to be estimated.
Instead of storing the whole sample cumulative distribution, the algorithm maintains only
\f$m+2\f$ principal markers and \f$m+1\f$ middle markers, whose positions are updated
with each sample and whose heights are adjusted (if necessary) using a piecewise-parablic
formula. The heights of these central markers are the current estimates of the quantiles
and returned as an iterator range.
For further details, see
K. E. E. Raatikainen, Simultaneous estimation of several quantiles, Simulation, Volume 49,
Number 4 (October), 1986, p. 159-164.
The extended \f$ P^2 \f$ algorithm generalizes the \f$ P^2 \f$ algorithm of
R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and
histograms without storing observations, Communications of the ACM,
Volume 28 (October), Number 10, 1985, p. 1076-1085.
@param extended_p_square_probabilities A vector of quantile probabilities.
*/
template<typename Sample>
struct extended_p_square_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
typedef std::vector<float_type> array_type;
// for boost::result_of
typedef iterator_range<
detail::lvalue_index_iterator<
permutation_iterator<
typename array_type::const_iterator
, detail::times2_iterator
>
>
> result_type;
template<typename Args>
extended_p_square_impl(Args const &args)
: probabilities(
boost::begin(args[extended_p_square_probabilities])
, boost::end(args[extended_p_square_probabilities])
)
, heights(2 * probabilities.size() + 3)
, actual_positions(heights.size())
, desired_positions(heights.size())
, positions_increments(heights.size())
{
std::size_t num_quantiles = this->probabilities.size();
std::size_t num_markers = this->heights.size();
for(std::size_t i = 0; i < num_markers; ++i)
{
this->actual_positions[i] = i + 1;
}
this->positions_increments[0] = 0.;
this->positions_increments[num_markers - 1] = 1.;
for(std::size_t i = 0; i < num_quantiles; ++i)
{
this->positions_increments[2 * i + 2] = probabilities[i];
}
for(std::size_t i = 0; i <= num_quantiles; ++i)
{
this->positions_increments[2 * i + 1] =
0.5 * (this->positions_increments[2 * i] + this->positions_increments[2 * i + 2]);
}
for(std::size_t i = 0; i < num_markers; ++i)
{
this->desired_positions[i] = 1. + 2. * (num_quantiles + 1.) * this->positions_increments[i];
}
}
template<typename Args>
void operator ()(Args const &args)
{
std::size_t cnt = count(args);
// m+2 principal markers and m+1 middle markers
std::size_t num_markers = 2 * this->probabilities.size() + 3;
// first accumulate num_markers samples
if(cnt <= num_markers)
{
this->heights[cnt - 1] = args[sample];
// complete the initialization of heights by sorting
if(cnt == num_markers)
{
std::sort(this->heights.begin(), this->heights.end());
}
}
else
{
std::size_t sample_cell = 1;
// find cell k = sample_cell such that heights[k-1] <= sample < heights[k]
if(args[sample] < this->heights[0])
{
this->heights[0] = args[sample];
sample_cell = 1;
}
else if(args[sample] >= this->heights[num_markers - 1])
{
this->heights[num_markers - 1] = args[sample];
sample_cell = num_markers - 1;
}
else
{
typedef typename array_type::iterator iterator;
iterator it = std::upper_bound(
this->heights.begin()
, this->heights.end()
, args[sample]
);
sample_cell = std::distance(this->heights.begin(), it);
}
// update actual positions of all markers above sample_cell index
for(std::size_t i = sample_cell; i < num_markers; ++i)
{
++this->actual_positions[i];
}
// update desired positions of all markers
for(std::size_t i = 0; i < num_markers; ++i)
{
this->desired_positions[i] += this->positions_increments[i];
}
// adjust heights and actual positions of markers 1 to num_markers-2 if necessary
for(std::size_t i = 1; i <= num_markers - 2; ++i)
{
// offset to desired position
float_type d = this->desired_positions[i] - this->actual_positions[i];
// offset to next position
float_type dp = this->actual_positions[i+1] - this->actual_positions[i];
// offset to previous position
float_type dm = this->actual_positions[i-1] - this->actual_positions[i];
// height ds
float_type hp = (this->heights[i+1] - this->heights[i]) / dp;
float_type hm = (this->heights[i-1] - this->heights[i]) / dm;
if((d >= 1 && dp > 1) || (d <= -1 && dm < -1))
{
short sign_d = static_cast<short>(d / std::abs(d));
float_type h = this->heights[i] + sign_d / (dp - dm) * ((sign_d - dm)*hp
+ (dp - sign_d) * hm);
// try adjusting heights[i] using p-squared formula
if(this->heights[i - 1] < h && h < this->heights[i + 1])
{
this->heights[i] = h;
}
else
{
// use linear formula
if(d > 0)
{
this->heights[i] += hp;
}
if(d < 0)
{
this->heights[i] -= hm;
}
}
this->actual_positions[i] += sign_d;
}
}
}
}
result_type result(dont_care) const
{
// for i in [1,probabilities.size()], return heights[i * 2]
detail::times2_iterator idx_begin = detail::make_times2_iterator(1);
detail::times2_iterator idx_end = detail::make_times2_iterator(this->probabilities.size() + 1);
return result_type(
make_permutation_iterator(this->heights.begin(), idx_begin)
, make_permutation_iterator(this->heights.begin(), idx_end)
);
}
private:
array_type probabilities; // the quantile probabilities
array_type heights; // q_i
array_type actual_positions; // n_i
array_type desired_positions; // d_i
array_type positions_increments; // f_i
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::extended_p_square
//
namespace tag
{
struct extended_p_square
: depends_on<count>
, extended_p_square_probabilities
{
typedef accumulators::impl::extended_p_square_impl<mpl::_1> impl;
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
/// tag::extended_p_square::probabilities named parameter
static boost::parameter::keyword<tag::probabilities> const probabilities;
#endif
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::extended_p_square
//
namespace extract
{
extractor<tag::extended_p_square> const extended_p_square = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square)
}
using extract::extended_p_square;
// So that extended_p_square can be automatically substituted with
// weighted_extended_p_square when the weight parameter is non-void
template<>
struct as_weighted_feature<tag::extended_p_square>
{
typedef tag::weighted_extended_p_square type;
};
template<>
struct feature_of<tag::weighted_extended_p_square>
: feature_of<tag::extended_p_square>
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,320 @@
///////////////////////////////////////////////////////////////////////////////
// extended_p_square_quantile.hpp
//
// Copyright 2005 Daniel Egloff. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_QUANTILE_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_EXTENDED_SINGLE_QUANTILE_HPP_DE_01_01_2006
#include <vector>
#include <functional>
#include <boost/throw_exception.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/iterator/transform_iterator.hpp>
#include <boost/iterator/counting_iterator.hpp>
#include <boost/iterator/permutation_iterator.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
#include <boost/accumulators/statistics/extended_p_square.hpp>
#include <boost/accumulators/statistics/weighted_extended_p_square.hpp>
#include <boost/accumulators/statistics/times2_iterator.hpp>
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4127) // conditional expression is constant
#endif
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// extended_p_square_quantile_impl
// single quantile estimation
/**
@brief Quantile estimation using the extended \f$P^2\f$ algorithm for weighted and unweighted samples
Uses the quantile estimates calculated by the extended \f$P^2\f$ algorithm to compute
intermediate quantile estimates by means of quadratic interpolation.
@param quantile_probability The probability of the quantile to be estimated.
*/
template<typename Sample, typename Impl1, typename Impl2> // Impl1: weighted/unweighted // Impl2: linear/quadratic
struct extended_p_square_quantile_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
typedef std::vector<float_type> array_type;
typedef iterator_range<
detail::lvalue_index_iterator<
permutation_iterator<
typename array_type::const_iterator
, detail::times2_iterator
>
>
> range_type;
// for boost::result_of
typedef float_type result_type;
template<typename Args>
extended_p_square_quantile_impl(Args const &args)
: probabilities(
boost::begin(args[extended_p_square_probabilities])
, boost::end(args[extended_p_square_probabilities])
)
{
}
template<typename Args>
result_type result(Args const &args) const
{
typedef
typename mpl::if_<
is_same<Impl1, weighted>
, tag::weighted_extended_p_square
, tag::extended_p_square
>::type
extended_p_square_tag;
extractor<extended_p_square_tag> const some_extended_p_square = {};
array_type heights(some_extended_p_square(args).size());
std::copy(some_extended_p_square(args).begin(), some_extended_p_square(args).end(), heights.begin());
this->probability = args[quantile_probability];
typename array_type::const_iterator iter_probs = std::lower_bound(this->probabilities.begin(), this->probabilities.end(), this->probability);
std::size_t dist = std::distance(this->probabilities.begin(), iter_probs);
typename array_type::const_iterator iter_heights = heights.begin() + dist;
// If this->probability is not in a valid range return NaN or throw exception
if (this->probability < *this->probabilities.begin() || this->probability > *(this->probabilities.end() - 1))
{
if (std::numeric_limits<result_type>::has_quiet_NaN)
{
return std::numeric_limits<result_type>::quiet_NaN();
}
else
{
std::ostringstream msg;
msg << "probability = " << this->probability << " is not in valid range (";
msg << *this->probabilities.begin() << ", " << *(this->probabilities.end() - 1) << ")";
boost::throw_exception(std::runtime_error(msg.str()));
return Sample(0);
}
}
if (*iter_probs == this->probability)
{
return heights[dist];
}
else
{
result_type res;
if (is_same<Impl2, linear>::value)
{
/////////////////////////////////////////////////////////////////////////////////
// LINEAR INTERPOLATION
//
float_type p1 = *iter_probs;
float_type p0 = *(iter_probs - 1);
float_type h1 = *iter_heights;
float_type h0 = *(iter_heights - 1);
float_type a = numeric::fdiv(h1 - h0, p1 - p0);
float_type b = h1 - p1 * a;
res = a * this->probability + b;
}
else
{
/////////////////////////////////////////////////////////////////////////////////
// QUADRATIC INTERPOLATION
//
float_type p0, p1, p2;
float_type h0, h1, h2;
if ( (dist == 1 || *iter_probs - this->probability <= this->probability - *(iter_probs - 1) ) && dist != this->probabilities.size() - 1 )
{
p0 = *(iter_probs - 1);
p1 = *iter_probs;
p2 = *(iter_probs + 1);
h0 = *(iter_heights - 1);
h1 = *iter_heights;
h2 = *(iter_heights + 1);
}
else
{
p0 = *(iter_probs - 2);
p1 = *(iter_probs - 1);
p2 = *iter_probs;
h0 = *(iter_heights - 2);
h1 = *(iter_heights - 1);
h2 = *iter_heights;
}
float_type hp21 = numeric::fdiv(h2 - h1, p2 - p1);
float_type hp10 = numeric::fdiv(h1 - h0, p1 - p0);
float_type p21 = numeric::fdiv(p2 * p2 - p1 * p1, p2 - p1);
float_type p10 = numeric::fdiv(p1 * p1 - p0 * p0, p1 - p0);
float_type a = numeric::fdiv(hp21 - hp10, p21 - p10);
float_type b = hp21 - a * p21;
float_type c = h2 - a * p2 * p2 - b * p2;
res = a * this->probability * this-> probability + b * this->probability + c;
}
return res;
}
}
private:
array_type probabilities;
mutable float_type probability;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::extended_p_square_quantile
//
namespace tag
{
struct extended_p_square_quantile
: depends_on<extended_p_square>
{
typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, unweighted, linear> impl;
};
struct extended_p_square_quantile_quadratic
: depends_on<extended_p_square>
{
typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, unweighted, quadratic> impl;
};
struct weighted_extended_p_square_quantile
: depends_on<weighted_extended_p_square>
{
typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, weighted, linear> impl;
};
struct weighted_extended_p_square_quantile_quadratic
: depends_on<weighted_extended_p_square>
{
typedef accumulators::impl::extended_p_square_quantile_impl<mpl::_1, weighted, quadratic> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::extended_p_square_quantile
// extract::weighted_extended_p_square_quantile
//
namespace extract
{
extractor<tag::extended_p_square_quantile> const extended_p_square_quantile = {};
extractor<tag::extended_p_square_quantile_quadratic> const extended_p_square_quantile_quadratic = {};
extractor<tag::weighted_extended_p_square_quantile> const weighted_extended_p_square_quantile = {};
extractor<tag::weighted_extended_p_square_quantile_quadratic> const weighted_extended_p_square_quantile_quadratic = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square_quantile)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(extended_p_square_quantile_quadratic)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_extended_p_square_quantile)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_extended_p_square_quantile_quadratic)
}
using extract::extended_p_square_quantile;
using extract::extended_p_square_quantile_quadratic;
using extract::weighted_extended_p_square_quantile;
using extract::weighted_extended_p_square_quantile_quadratic;
// extended_p_square_quantile(linear) -> extended_p_square_quantile
template<>
struct as_feature<tag::extended_p_square_quantile(linear)>
{
typedef tag::extended_p_square_quantile type;
};
// extended_p_square_quantile(quadratic) -> extended_p_square_quantile_quadratic
template<>
struct as_feature<tag::extended_p_square_quantile(quadratic)>
{
typedef tag::extended_p_square_quantile_quadratic type;
};
// weighted_extended_p_square_quantile(linear) -> weighted_extended_p_square_quantile
template<>
struct as_feature<tag::weighted_extended_p_square_quantile(linear)>
{
typedef tag::weighted_extended_p_square_quantile type;
};
// weighted_extended_p_square_quantile(quadratic) -> weighted_extended_p_square_quantile_quadratic
template<>
struct as_feature<tag::weighted_extended_p_square_quantile(quadratic)>
{
typedef tag::weighted_extended_p_square_quantile_quadratic type;
};
// for the purposes of feature-based dependency resolution,
// extended_p_square_quantile and weighted_extended_p_square_quantile
// provide the same feature as quantile
template<>
struct feature_of<tag::extended_p_square_quantile>
: feature_of<tag::quantile>
{
};
template<>
struct feature_of<tag::extended_p_square_quantile_quadratic>
: feature_of<tag::quantile>
{
};
// So that extended_p_square_quantile can be automatically substituted with
// weighted_extended_p_square_quantile when the weight parameter is non-void
template<>
struct as_weighted_feature<tag::extended_p_square_quantile>
{
typedef tag::weighted_extended_p_square_quantile type;
};
template<>
struct feature_of<tag::weighted_extended_p_square_quantile>
: feature_of<tag::extended_p_square_quantile>
{
};
// So that extended_p_square_quantile_quadratic can be automatically substituted with
// weighted_extended_p_square_quantile_quadratic when the weight parameter is non-void
template<>
struct as_weighted_feature<tag::extended_p_square_quantile_quadratic>
{
typedef tag::weighted_extended_p_square_quantile_quadratic type;
};
template<>
struct feature_of<tag::weighted_extended_p_square_quantile_quadratic>
: feature_of<tag::extended_p_square_quantile_quadratic>
{
};
}} // namespace boost::accumulators
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#endif
@@ -0,0 +1,112 @@
///////////////////////////////////////////////////////////////////////////////
// kurtosis.hpp
//
// Copyright 2006 Olivier Gygi, Daniel Egloff. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_KURTOSIS_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_STATISTICS_KURTOSIS_HPP_EAN_28_10_2005
#include <limits>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics/mean.hpp>
#include <boost/accumulators/statistics/moment.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// kurtosis_impl
/**
@brief Kurtosis estimation
The kurtosis of a sample distribution is defined as the ratio of the 4th central moment and the square of the 2nd central
moment (the variance) of the samples, minus 3. The term \f$ -3 \f$ is added in order to ensure that the normal distribution
has zero kurtosis. The kurtosis can also be expressed by the simple moments:
\f[
\hat{g}_2 =
\frac
{\widehat{m}_n^{(4)}-4\widehat{m}_n^{(3)}\hat{\mu}_n+6\widehat{m}_n^{(2)}\hat{\mu}_n^2-3\hat{\mu}_n^4}
{\left(\widehat{m}_n^{(2)} - \hat{\mu}_n^{2}\right)^2} - 3,
\f]
where \f$ \widehat{m}_n^{(i)} \f$ are the \f$ i \f$-th moment and \f$ \hat{\mu}_n \f$ the mean (first moment) of the
\f$ n \f$ samples.
*/
template<typename Sample>
struct kurtosis_impl
: accumulator_base
{
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, Sample>::result_type result_type;
kurtosis_impl(dont_care) {}
template<typename Args>
result_type result(Args const &args) const
{
return numeric::fdiv(
accumulators::moment<4>(args)
- 4. * accumulators::moment<3>(args) * mean(args)
+ 6. * accumulators::moment<2>(args) * mean(args) * mean(args)
- 3. * mean(args) * mean(args) * mean(args) * mean(args)
, ( accumulators::moment<2>(args) - mean(args) * mean(args) )
* ( accumulators::moment<2>(args) - mean(args) * mean(args) )
) - 3.;
}
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::kurtosis
//
namespace tag
{
struct kurtosis
: depends_on<mean, moment<2>, moment<3>, moment<4> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::kurtosis_impl<mpl::_1> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::kurtosis
//
namespace extract
{
extractor<tag::kurtosis> const kurtosis = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(kurtosis)
}
using extract::kurtosis;
// So that kurtosis can be automatically substituted with
// weighted_kurtosis when the weight parameter is non-void
template<>
struct as_weighted_feature<tag::kurtosis>
{
typedef tag::weighted_kurtosis type;
};
template<>
struct feature_of<tag::weighted_kurtosis>
: feature_of<tag::kurtosis>
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,85 @@
///////////////////////////////////////////////////////////////////////////////
// max.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_MAX_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_STATISTICS_MAX_HPP_EAN_28_10_2005
#include <limits>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// max_impl
template<typename Sample>
struct max_impl
: accumulator_base
{
// for boost::result_of
typedef Sample result_type;
template<typename Args>
max_impl(Args const &args)
: max_(numeric::as_min(args[sample | Sample()]))
{
}
template<typename Args>
void operator ()(Args const &args)
{
numeric::max_assign(this->max_, args[sample]);
}
result_type result(dont_care) const
{
return this->max_;
}
private:
Sample max_;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::max
//
namespace tag
{
struct max
: depends_on<>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::max_impl<mpl::_1> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::max
//
namespace extract
{
extractor<tag::max> const max = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(max)
}
using extract::max;
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,298 @@
///////////////////////////////////////////////////////////////////////////////
// mean.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_MEAN_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_STATISTICS_MEAN_HPP_EAN_28_10_2005
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/sum.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// mean_impl
// lazy, by default
template<typename Sample, typename SumFeature>
struct mean_impl
: accumulator_base
{
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
mean_impl(dont_care) {}
template<typename Args>
result_type result(Args const &args) const
{
extractor<SumFeature> sum;
return numeric::fdiv(sum(args), count(args));
}
};
template<typename Sample, typename Tag>
struct immediate_mean_impl
: accumulator_base
{
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
template<typename Args>
immediate_mean_impl(Args const &args)
: mean(numeric::fdiv(args[sample | Sample()], numeric::one<std::size_t>::value))
{
}
template<typename Args>
void operator ()(Args const &args)
{
std::size_t cnt = count(args);
this->mean = numeric::fdiv(
(this->mean * (cnt - 1)) + args[parameter::keyword<Tag>::get()]
, cnt
);
}
result_type result(dont_care) const
{
return this->mean;
}
private:
result_type mean;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::mean
// tag::immediate_mean
// tag::mean_of_weights
// tag::immediate_mean_of_weights
// tag::mean_of_variates
// tag::immediate_mean_of_variates
//
namespace tag
{
struct mean
: depends_on<count, sum>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::mean_impl<mpl::_1, sum> impl;
};
struct immediate_mean
: depends_on<count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::immediate_mean_impl<mpl::_1, tag::sample> impl;
};
struct mean_of_weights
: depends_on<count, sum_of_weights>
{
typedef mpl::true_ is_weight_accumulator;
/// INTERNAL ONLY
///
typedef accumulators::impl::mean_impl<mpl::_2, sum_of_weights> impl;
};
struct immediate_mean_of_weights
: depends_on<count>
{
typedef mpl::true_ is_weight_accumulator;
/// INTERNAL ONLY
///
typedef accumulators::impl::immediate_mean_impl<mpl::_2, tag::weight> impl;
};
template<typename VariateType, typename VariateTag>
struct mean_of_variates
: depends_on<count, sum_of_variates<VariateType, VariateTag> >
{
/// INTERNAL ONLY
///
typedef mpl::always<accumulators::impl::mean_impl<VariateType, sum_of_variates<VariateType, VariateTag> > > impl;
};
template<typename VariateType, typename VariateTag>
struct immediate_mean_of_variates
: depends_on<count>
{
/// INTERNAL ONLY
///
typedef mpl::always<accumulators::impl::immediate_mean_impl<VariateType, VariateTag> > impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::mean
// extract::mean_of_weights
// extract::mean_of_variates
//
namespace extract
{
extractor<tag::mean> const mean = {};
extractor<tag::mean_of_weights> const mean_of_weights = {};
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, mean_of_variates, (typename)(typename))
BOOST_ACCUMULATORS_IGNORE_GLOBAL(mean)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(mean_of_weights)
}
using extract::mean;
using extract::mean_of_weights;
using extract::mean_of_variates;
// mean(lazy) -> mean
template<>
struct as_feature<tag::mean(lazy)>
{
typedef tag::mean type;
};
// mean(immediate) -> immediate_mean
template<>
struct as_feature<tag::mean(immediate)>
{
typedef tag::immediate_mean type;
};
// mean_of_weights(lazy) -> mean_of_weights
template<>
struct as_feature<tag::mean_of_weights(lazy)>
{
typedef tag::mean_of_weights type;
};
// mean_of_weights(immediate) -> immediate_mean_of_weights
template<>
struct as_feature<tag::mean_of_weights(immediate)>
{
typedef tag::immediate_mean_of_weights type;
};
// mean_of_variates<VariateType, VariateTag>(lazy) -> mean_of_variates<VariateType, VariateTag>
template<typename VariateType, typename VariateTag>
struct as_feature<tag::mean_of_variates<VariateType, VariateTag>(lazy)>
{
typedef tag::mean_of_variates<VariateType, VariateTag> type;
};
// mean_of_variates<VariateType, VariateTag>(immediate) -> immediate_mean_of_variates<VariateType, VariateTag>
template<typename VariateType, typename VariateTag>
struct as_feature<tag::mean_of_variates<VariateType, VariateTag>(immediate)>
{
typedef tag::immediate_mean_of_variates<VariateType, VariateTag> type;
};
// for the purposes of feature-based dependency resolution,
// immediate_mean provides the same feature as mean
template<>
struct feature_of<tag::immediate_mean>
: feature_of<tag::mean>
{
};
// for the purposes of feature-based dependency resolution,
// immediate_mean provides the same feature as mean
template<>
struct feature_of<tag::immediate_mean_of_weights>
: feature_of<tag::mean_of_weights>
{
};
// for the purposes of feature-based dependency resolution,
// immediate_mean provides the same feature as mean
template<typename VariateType, typename VariateTag>
struct feature_of<tag::immediate_mean_of_variates<VariateType, VariateTag> >
: feature_of<tag::mean_of_variates<VariateType, VariateTag> >
{
};
// So that mean can be automatically substituted with
// weighted_mean when the weight parameter is non-void.
template<>
struct as_weighted_feature<tag::mean>
{
typedef tag::weighted_mean type;
};
template<>
struct feature_of<tag::weighted_mean>
: feature_of<tag::mean>
{};
// So that immediate_mean can be automatically substituted with
// immediate_weighted_mean when the weight parameter is non-void.
template<>
struct as_weighted_feature<tag::immediate_mean>
{
typedef tag::immediate_weighted_mean type;
};
template<>
struct feature_of<tag::immediate_weighted_mean>
: feature_of<tag::immediate_mean>
{};
// So that mean_of_weights<> can be automatically substituted with
// weighted_mean_of_variates<> when the weight parameter is non-void.
template<typename VariateType, typename VariateTag>
struct as_weighted_feature<tag::mean_of_variates<VariateType, VariateTag> >
{
typedef tag::weighted_mean_of_variates<VariateType, VariateTag> type;
};
template<typename VariateType, typename VariateTag>
struct feature_of<tag::weighted_mean_of_variates<VariateType, VariateTag> >
: feature_of<tag::mean_of_variates<VariateType, VariateTag> >
{
};
// So that immediate_mean_of_weights<> can be automatically substituted with
// immediate_weighted_mean_of_variates<> when the weight parameter is non-void.
template<typename VariateType, typename VariateTag>
struct as_weighted_feature<tag::immediate_mean_of_variates<VariateType, VariateTag> >
{
typedef tag::immediate_weighted_mean_of_variates<VariateType, VariateTag> type;
};
template<typename VariateType, typename VariateTag>
struct feature_of<tag::immediate_weighted_mean_of_variates<VariateType, VariateTag> >
: feature_of<tag::immediate_mean_of_variates<VariateType, VariateTag> >
{
};
////////////////////////////////////////////////////////////////////////////
//// droppable_accumulator<mean_impl>
//// need to specialize droppable lazy mean to cache the result at the
//// point the accumulator is dropped.
///// INTERNAL ONLY
/////
//template<typename Sample, typename SumFeature>
//struct droppable_accumulator<impl::mean_impl<Sample, SumFeature> >
// : droppable_accumulator_base<
// with_cached_result<impl::mean_impl<Sample, SumFeature> >
// >
//{
// template<typename Args>
// droppable_accumulator(Args const &args)
// : droppable_accumulator::base(args)
// {
// }
//};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,301 @@
///////////////////////////////////////////////////////////////////////////////
// median.hpp
//
// Copyright 2006 Eric Niebler, Olivier Gygi. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_MEDIAN_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_STATISTICS_MEDIAN_HPP_EAN_28_10_2005
#include <boost/mpl/placeholders.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/p_square_quantile.hpp>
#include <boost/accumulators/statistics/density.hpp>
#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// median_impl
//
/**
@brief Median estimation based on the \f$P^2\f$ quantile estimator
The \f$P^2\f$ algorithm is invoked with a quantile probability of 0.5.
*/
template<typename Sample>
struct median_impl
: accumulator_base
{
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
median_impl(dont_care) {}
template<typename Args>
result_type result(Args const &args) const
{
return p_square_quantile_for_median(args);
}
};
///////////////////////////////////////////////////////////////////////////////
// with_density_median_impl
//
/**
@brief Median estimation based on the density estimator
The algorithm determines the bin in which the \f$0.5*cnt\f$-th sample lies, \f$cnt\f$ being
the total number of samples. It returns the approximate horizontal position of this sample,
based on a linear interpolation inside the bin.
*/
template<typename Sample>
struct with_density_median_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
typedef std::vector<std::pair<float_type, float_type> > histogram_type;
typedef iterator_range<typename histogram_type::iterator> range_type;
// for boost::result_of
typedef float_type result_type;
template<typename Args>
with_density_median_impl(Args const &args)
: sum(numeric::fdiv(args[sample | Sample()], (std::size_t)1))
, is_dirty(true)
{
}
void operator ()(dont_care)
{
this->is_dirty = true;
}
template<typename Args>
result_type result(Args const &args) const
{
if (this->is_dirty)
{
this->is_dirty = false;
std::size_t cnt = count(args);
range_type histogram = density(args);
typename range_type::iterator it = histogram.begin();
while (this->sum < 0.5 * cnt)
{
this->sum += it->second * cnt;
++it;
}
--it;
float_type over = numeric::fdiv(this->sum - 0.5 * cnt, it->second * cnt);
this->median = it->first * over + (it + 1)->first * (1. - over);
}
return this->median;
}
private:
mutable float_type sum;
mutable bool is_dirty;
mutable float_type median;
};
///////////////////////////////////////////////////////////////////////////////
// with_p_square_cumulative_distribution_median_impl
//
/**
@brief Median estimation based on the \f$P^2\f$ cumulative distribution estimator
The algorithm determines the first (leftmost) bin with a height exceeding 0.5. It
returns the approximate horizontal position of where the cumulative distribution
equals 0.5, based on a linear interpolation inside the bin.
*/
template<typename Sample>
struct with_p_square_cumulative_distribution_median_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
typedef std::vector<std::pair<float_type, float_type> > histogram_type;
typedef iterator_range<typename histogram_type::iterator> range_type;
// for boost::result_of
typedef float_type result_type;
with_p_square_cumulative_distribution_median_impl(dont_care)
: is_dirty(true)
{
}
void operator ()(dont_care)
{
this->is_dirty = true;
}
template<typename Args>
result_type result(Args const &args) const
{
if (this->is_dirty)
{
this->is_dirty = false;
range_type histogram = p_square_cumulative_distribution(args);
typename range_type::iterator it = histogram.begin();
while (it->second < 0.5)
{
++it;
}
float_type over = numeric::fdiv(it->second - 0.5, it->second - (it - 1)->second);
this->median = it->first * over + (it + 1)->first * ( 1. - over );
}
return this->median;
}
private:
mutable bool is_dirty;
mutable float_type median;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::median
// tag::with_densisty_median
// tag::with_p_square_cumulative_distribution_median
//
namespace tag
{
struct median
: depends_on<p_square_quantile_for_median>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::median_impl<mpl::_1> impl;
};
struct with_density_median
: depends_on<count, density>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::with_density_median_impl<mpl::_1> impl;
};
struct with_p_square_cumulative_distribution_median
: depends_on<p_square_cumulative_distribution>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::with_p_square_cumulative_distribution_median_impl<mpl::_1> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::median
// extract::with_density_median
// extract::with_p_square_cumulative_distribution_median
//
namespace extract
{
extractor<tag::median> const median = {};
extractor<tag::with_density_median> const with_density_median = {};
extractor<tag::with_p_square_cumulative_distribution_median> const with_p_square_cumulative_distribution_median = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(median)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(with_density_median)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(with_p_square_cumulative_distribution_median)
}
using extract::median;
using extract::with_density_median;
using extract::with_p_square_cumulative_distribution_median;
// median(with_p_square_quantile) -> median
template<>
struct as_feature<tag::median(with_p_square_quantile)>
{
typedef tag::median type;
};
// median(with_density) -> with_density_median
template<>
struct as_feature<tag::median(with_density)>
{
typedef tag::with_density_median type;
};
// median(with_p_square_cumulative_distribution) -> with_p_square_cumulative_distribution_median
template<>
struct as_feature<tag::median(with_p_square_cumulative_distribution)>
{
typedef tag::with_p_square_cumulative_distribution_median type;
};
// for the purposes of feature-based dependency resolution,
// with_density_median and with_p_square_cumulative_distribution_median
// provide the same feature as median
template<>
struct feature_of<tag::with_density_median>
: feature_of<tag::median>
{
};
template<>
struct feature_of<tag::with_p_square_cumulative_distribution_median>
: feature_of<tag::median>
{
};
// So that median can be automatically substituted with
// weighted_median when the weight parameter is non-void.
template<>
struct as_weighted_feature<tag::median>
{
typedef tag::weighted_median type;
};
template<>
struct feature_of<tag::weighted_median>
: feature_of<tag::median>
{
};
// So that with_density_median can be automatically substituted with
// with_density_weighted_median when the weight parameter is non-void.
template<>
struct as_weighted_feature<tag::with_density_median>
{
typedef tag::with_density_weighted_median type;
};
template<>
struct feature_of<tag::with_density_weighted_median>
: feature_of<tag::with_density_median>
{
};
// So that with_p_square_cumulative_distribution_median can be automatically substituted with
// with_p_square_cumulative_distribution_weighted_median when the weight parameter is non-void.
template<>
struct as_weighted_feature<tag::with_p_square_cumulative_distribution_median>
{
typedef tag::with_p_square_cumulative_distribution_weighted_median type;
};
template<>
struct feature_of<tag::with_p_square_cumulative_distribution_weighted_median>
: feature_of<tag::with_p_square_cumulative_distribution_median>
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,85 @@
///////////////////////////////////////////////////////////////////////////////
// min.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_MIN_HPP_EAN_28_10_2005
#define BOOST_ACCUMULATORS_STATISTICS_MIN_HPP_EAN_28_10_2005
#include <limits>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// min_impl
template<typename Sample>
struct min_impl
: accumulator_base
{
// for boost::result_of
typedef Sample result_type;
template<typename Args>
min_impl(Args const &args)
: min_(numeric::as_max(args[sample | Sample()]))
{
}
template<typename Args>
void operator ()(Args const &args)
{
numeric::min_assign(this->min_, args[sample]);
}
result_type result(dont_care) const
{
return this->min_;
}
private:
Sample min_;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::min
//
namespace tag
{
struct min
: depends_on<>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::min_impl<mpl::_1> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::min
//
namespace extract
{
extractor<tag::min> const min = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(min)
}
using extract::min;
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,125 @@
///////////////////////////////////////////////////////////////////////////////
// moment.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_MOMENT_HPP_EAN_15_11_2005
#define BOOST_ACCUMULATORS_STATISTICS_MOMENT_HPP_EAN_15_11_2005
#include <boost/config/no_tr1/cmath.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/assert.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
namespace boost { namespace numeric
{
/// INTERNAL ONLY
///
template<typename T>
T const &pow(T const &x, mpl::int_<1>)
{
return x;
}
/// INTERNAL ONLY
///
template<typename T, int N>
T pow(T const &x, mpl::int_<N>)
{
using namespace operators;
T y = numeric::pow(x, mpl::int_<N/2>());
T z = y * y;
return (N % 2) ? (z * x) : z;
}
}}
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// moment_impl
template<typename N, typename Sample>
struct moment_impl
: accumulator_base // TODO: also depends_on sum of powers
{
BOOST_MPL_ASSERT_RELATION(N::value, >, 0);
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
template<typename Args>
moment_impl(Args const &args)
: sum(args[sample | Sample()])
{
}
template<typename Args>
void operator ()(Args const &args)
{
this->sum += numeric::pow(args[sample], N());
}
template<typename Args>
result_type result(Args const &args) const
{
return numeric::fdiv(this->sum, count(args));
}
private:
Sample sum;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::moment
//
namespace tag
{
template<int N>
struct moment
: depends_on<count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::moment_impl<mpl::int_<N>, mpl::_1> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::moment
//
namespace extract
{
BOOST_ACCUMULATORS_DEFINE_EXTRACTOR(tag, moment, (int))
}
using extract::moment;
// So that moment<N> can be automatically substituted with
// weighted_moment<N> when the weight parameter is non-void
template<int N>
struct as_weighted_feature<tag::moment<N> >
{
typedef tag::weighted_moment<N> type;
};
template<int N>
struct feature_of<tag::weighted_moment<N> >
: feature_of<tag::moment<N> >
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,263 @@
///////////////////////////////////////////////////////////////////////////////
// p_square_cumulative_distribution.hpp
//
// Copyright 2005 Daniel Egloff, Olivier Gygi. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006
#include <vector>
#include <functional>
#include <boost/parameter/keyword.hpp>
#include <boost/range.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
namespace boost { namespace accumulators
{
///////////////////////////////////////////////////////////////////////////////
// num_cells named parameter
//
BOOST_PARAMETER_NESTED_KEYWORD(tag, p_square_cumulative_distribution_num_cells, num_cells)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_cumulative_distribution_num_cells)
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// p_square_cumulative_distribution_impl
// cumulative_distribution calculation (as histogram)
/**
@brief Histogram calculation of the cumulative distribution with the \f$P^2\f$ algorithm
A histogram of the sample cumulative distribution is computed dynamically without storing samples
based on the \f$ P^2 \f$ algorithm. The returned histogram has a specifiable amount (num_cells)
equiprobable (and not equal-sized) cells.
For further details, see
R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and
histograms without storing observations, Communications of the ACM,
Volume 28 (October), Number 10, 1985, p. 1076-1085.
@param p_square_cumulative_distribution_num_cells.
*/
template<typename Sample>
struct p_square_cumulative_distribution_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
typedef std::vector<float_type> array_type;
typedef std::vector<std::pair<float_type, float_type> > histogram_type;
// for boost::result_of
typedef iterator_range<typename histogram_type::iterator> result_type;
template<typename Args>
p_square_cumulative_distribution_impl(Args const &args)
: num_cells(args[p_square_cumulative_distribution_num_cells])
, heights(num_cells + 1)
, actual_positions(num_cells + 1)
, desired_positions(num_cells + 1)
, positions_increments(num_cells + 1)
, histogram(num_cells + 1)
, is_dirty(true)
{
std::size_t b = this->num_cells;
for (std::size_t i = 0; i < b + 1; ++i)
{
this->actual_positions[i] = i + 1.;
this->desired_positions[i] = i + 1.;
this->positions_increments[i] = numeric::fdiv(i, b);
}
}
template<typename Args>
void operator ()(Args const &args)
{
this->is_dirty = true;
std::size_t cnt = count(args);
std::size_t sample_cell = 1; // k
std::size_t b = this->num_cells;
// accumulate num_cells + 1 first samples
if (cnt <= b + 1)
{
this->heights[cnt - 1] = args[sample];
// complete the initialization of heights by sorting
if (cnt == b + 1)
{
std::sort(this->heights.begin(), this->heights.end());
}
}
else
{
// find cell k such that heights[k-1] <= args[sample] < heights[k] and adjust extreme values
if (args[sample] < this->heights[0])
{
this->heights[0] = args[sample];
sample_cell = 1;
}
else if (this->heights[b] <= args[sample])
{
this->heights[b] = args[sample];
sample_cell = b;
}
else
{
typename array_type::iterator it;
it = std::upper_bound(
this->heights.begin()
, this->heights.end()
, args[sample]
);
sample_cell = std::distance(this->heights.begin(), it);
}
// increment positions of markers above sample_cell
for (std::size_t i = sample_cell; i < b + 1; ++i)
{
++this->actual_positions[i];
}
// update desired position of markers 2 to num_cells + 1
// (desired position of first marker is always 1)
for (std::size_t i = 1; i < b + 1; ++i)
{
this->desired_positions[i] += this->positions_increments[i];
}
// adjust heights of markers 2 to num_cells if necessary
for (std::size_t i = 1; i < b; ++i)
{
// offset to desire position
float_type d = this->desired_positions[i] - this->actual_positions[i];
// offset to next position
float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];
// offset to previous position
float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];
// height ds
float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;
float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;
if ( ( d >= 1. && dp > 1. ) || ( d <= -1. && dm < -1. ) )
{
short sign_d = static_cast<short>(d / std::abs(d));
// try adjusting heights[i] using p-squared formula
float_type h = this->heights[i] + sign_d / (dp - dm) * ( (sign_d - dm) * hp + (dp - sign_d) * hm );
if ( this->heights[i - 1] < h && h < this->heights[i + 1] )
{
this->heights[i] = h;
}
else
{
// use linear formula
if (d>0)
{
this->heights[i] += hp;
}
if (d<0)
{
this->heights[i] -= hm;
}
}
this->actual_positions[i] += sign_d;
}
}
}
}
template<typename Args>
result_type result(Args const &args) const
{
if (this->is_dirty)
{
this->is_dirty = false;
// creates a vector of std::pair where each pair i holds
// the values heights[i] (x-axis of histogram) and
// actual_positions[i] / cnt (y-axis of histogram)
std::size_t cnt = count(args);
for (std::size_t i = 0; i < this->histogram.size(); ++i)
{
this->histogram[i] = std::make_pair(this->heights[i], numeric::fdiv(this->actual_positions[i], cnt));
}
}
//return histogram;
return make_iterator_range(this->histogram);
}
private:
std::size_t num_cells; // number of cells b
array_type heights; // q_i
array_type actual_positions; // n_i
array_type desired_positions; // n'_i
array_type positions_increments; // dn'_i
mutable histogram_type histogram; // histogram
mutable bool is_dirty;
};
} // namespace detail
///////////////////////////////////////////////////////////////////////////////
// tag::p_square_cumulative_distribution
//
namespace tag
{
struct p_square_cumulative_distribution
: depends_on<count>
, p_square_cumulative_distribution_num_cells
{
/// INTERNAL ONLY
///
typedef accumulators::impl::p_square_cumulative_distribution_impl<mpl::_1> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::p_square_cumulative_distribution
//
namespace extract
{
extractor<tag::p_square_cumulative_distribution> const p_square_cumulative_distribution = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_cumulative_distribution)
}
using extract::p_square_cumulative_distribution;
// So that p_square_cumulative_distribution can be automatically substituted with
// weighted_p_square_cumulative_distribution when the weight parameter is non-void
template<>
struct as_weighted_feature<tag::p_square_cumulative_distribution>
{
typedef tag::weighted_p_square_cumulative_distribution type;
};
template<>
struct feature_of<tag::weighted_p_square_cumulative_distribution>
: feature_of<tag::p_square_cumulative_distribution>
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,19 @@
///////////////////////////////////////////////////////////////////////////////
// p_square_cumulative_distribution.hpp
//
// Copyright 2012 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMULATIVE_DISTRIBUTION_HPP_03_19_2012
#define BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_CUMULATIVE_DISTRIBUTION_HPP_03_19_2012
#if defined(_MSC_VER) || defined(__BORLANDC__) || defined(__DMC__)
# pragma message ("Warning: This header is deprecated. Please use: boost/accumulators/statistics/p_square_cumul_dist.hpp")
#elif defined(__GNUC__) || defined(__HP_aCC) || defined(__SUNPRO_CC) || defined(__IBMCPP__)
# warning "This header is deprecated. Please use: boost/accumulators/statistics/p_square_cumul_dist.hpp"
#endif
#include <boost/accumulators/statistics/p_square_cumul_dist.hpp>
#endif
@@ -0,0 +1,257 @@
///////////////////////////////////////////////////////////////////////////////
// p_square_quantile.hpp
//
// Copyright 2005 Daniel Egloff. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_QUANTILE_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_P_SQUARE_QUANTILE_HPP_DE_01_01_2006
#include <cmath>
#include <functional>
#include <boost/array.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// p_square_quantile_impl
// single quantile estimation
/**
@brief Single quantile estimation with the \f$P^2\f$ algorithm
The \f$P^2\f$ algorithm estimates a quantile dynamically without storing samples. Instead of
storing the whole sample cumulative distribution, only five points (markers) are stored. The heights
of these markers are the minimum and the maximum of the samples and the current estimates of the
\f$(p/2)\f$-, \f$p\f$- and \f$(1+p)/2\f$-quantiles. Their positions are equal to the number
of samples that are smaller or equal to the markers. Each time a new samples is recorded, the
positions of the markers are updated and if necessary their heights are adjusted using a piecewise-
parabolic formula.
For further details, see
R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and
histograms without storing observations, Communications of the ACM,
Volume 28 (October), Number 10, 1985, p. 1076-1085.
@param quantile_probability
*/
template<typename Sample, typename Impl>
struct p_square_quantile_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
typedef array<float_type, 5> array_type;
// for boost::result_of
typedef float_type result_type;
template<typename Args>
p_square_quantile_impl(Args const &args)
: p(is_same<Impl, for_median>::value ? 0.5 : args[quantile_probability | 0.5])
, heights()
, actual_positions()
, desired_positions()
, positions_increments()
{
for(std::size_t i = 0; i < 5; ++i)
{
this->actual_positions[i] = i + 1.;
}
this->desired_positions[0] = 1.;
this->desired_positions[1] = 1. + 2. * this->p;
this->desired_positions[2] = 1. + 4. * this->p;
this->desired_positions[3] = 3. + 2. * this->p;
this->desired_positions[4] = 5.;
this->positions_increments[0] = 0.;
this->positions_increments[1] = this->p / 2.;
this->positions_increments[2] = this->p;
this->positions_increments[3] = (1. + this->p) / 2.;
this->positions_increments[4] = 1.;
}
template<typename Args>
void operator ()(Args const &args)
{
std::size_t cnt = count(args);
// accumulate 5 first samples
if(cnt <= 5)
{
this->heights[cnt - 1] = args[sample];
// complete the initialization of heights by sorting
if(cnt == 5)
{
std::sort(this->heights.begin(), this->heights.end());
}
}
else
{
std::size_t sample_cell = 1; // k
// find cell k such that heights[k-1] <= args[sample] < heights[k] and adjust extreme values
if (args[sample] < this->heights[0])
{
this->heights[0] = args[sample];
sample_cell = 1;
}
else if (this->heights[4] <= args[sample])
{
this->heights[4] = args[sample];
sample_cell = 4;
}
else
{
typedef typename array_type::iterator iterator;
iterator it = std::upper_bound(
this->heights.begin()
, this->heights.end()
, args[sample]
);
sample_cell = std::distance(this->heights.begin(), it);
}
// update positions of markers above sample_cell
for(std::size_t i = sample_cell; i < 5; ++i)
{
++this->actual_positions[i];
}
// update desired positions of all markers
for(std::size_t i = 0; i < 5; ++i)
{
this->desired_positions[i] += this->positions_increments[i];
}
// adjust heights and actual positions of markers 1 to 3 if necessary
for(std::size_t i = 1; i <= 3; ++i)
{
// offset to desired positions
float_type d = this->desired_positions[i] - this->actual_positions[i];
// offset to next position
float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];
// offset to previous position
float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];
// height ds
float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;
float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;
if((d >= 1. && dp > 1.) || (d <= -1. && dm < -1.))
{
short sign_d = static_cast<short>(d / std::abs(d));
// try adjusting heights[i] using p-squared formula
float_type h = this->heights[i] + sign_d / (dp - dm) * ((sign_d - dm) * hp
+ (dp - sign_d) * hm);
if(this->heights[i - 1] < h && h < this->heights[i + 1])
{
this->heights[i] = h;
}
else
{
// use linear formula
if(d > 0)
{
this->heights[i] += hp;
}
if(d < 0)
{
this->heights[i] -= hm;
}
}
this->actual_positions[i] += sign_d;
}
}
}
}
result_type result(dont_care) const
{
return this->heights[2];
}
private:
float_type p; // the quantile probability p
array_type heights; // q_i
array_type actual_positions; // n_i
array_type desired_positions; // n'_i
array_type positions_increments; // dn'_i
};
} // namespace detail
///////////////////////////////////////////////////////////////////////////////
// tag::p_square_quantile
//
namespace tag
{
struct p_square_quantile
: depends_on<count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::p_square_quantile_impl<mpl::_1, regular> impl;
};
struct p_square_quantile_for_median
: depends_on<count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::p_square_quantile_impl<mpl::_1, for_median> impl;
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::p_square_quantile
// extract::p_square_quantile_for_median
//
namespace extract
{
extractor<tag::p_square_quantile> const p_square_quantile = {};
extractor<tag::p_square_quantile_for_median> const p_square_quantile_for_median = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_quantile)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(p_square_quantile_for_median)
}
using extract::p_square_quantile;
using extract::p_square_quantile_for_median;
// So that p_square_quantile can be automatically substituted with
// weighted_p_square_quantile when the weight parameter is non-void
template<>
struct as_weighted_feature<tag::p_square_quantile>
{
typedef tag::weighted_p_square_quantile type;
};
template<>
struct feature_of<tag::weighted_p_square_quantile>
: feature_of<tag::p_square_quantile>
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,23 @@
///////////////////////////////////////////////////////////////////////////////
// quantile_probability.hpp
//
// Copyright 2005 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_PARAMETERS_QUANTILE_PROBABILITY_HPP_EAN_03_11_2005
#define BOOST_ACCUMULATORS_STATISTICS_PARAMETERS_QUANTILE_PROBABILITY_HPP_EAN_03_11_2005
#include <boost/parameter/keyword.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
namespace boost { namespace accumulators
{
BOOST_PARAMETER_KEYWORD(tag, quantile_probability)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(quantile_probability)
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,405 @@
///////////////////////////////////////////////////////////////////////////////
// peaks_over_threshold.hpp
//
// Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_PEAKS_OVER_THRESHOLD_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_PEAKS_OVER_THRESHOLD_HPP_DE_01_01_2006
#include <vector>
#include <limits>
#include <numeric>
#include <functional>
#include <boost/config/no_tr1/cmath.hpp> // pow
#include <sstream> // stringstream
#include <stdexcept> // runtime_error
#include <boost/throw_exception.hpp>
#include <boost/range.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/int.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/accumulators/accumulators_fwd.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/parameters/quantile_probability.hpp>
#include <boost/accumulators/statistics/count.hpp>
#include <boost/accumulators/statistics/tail.hpp>
#ifdef _MSC_VER
# pragma warning(push)
# pragma warning(disable: 4127) // conditional expression is constant
#endif
namespace boost { namespace accumulators
{
///////////////////////////////////////////////////////////////////////////////
// threshold_probability and threshold named parameters
//
BOOST_PARAMETER_NESTED_KEYWORD(tag, pot_threshold_value, threshold_value)
BOOST_PARAMETER_NESTED_KEYWORD(tag, pot_threshold_probability, threshold_probability)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(pot_threshold_value)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(pot_threshold_probability)
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// peaks_over_threshold_impl
// works with an explicit threshold value and does not depend on order statistics
/**
@brief Peaks over Threshold Method for Quantile and Tail Mean Estimation
According to the theorem of Pickands-Balkema-de Haan, the distribution function \f$F_u(x)\f$ of
the excesses \f$x\f$ over some sufficiently high threshold \f$u\f$ of a distribution function \f$F(x)\f$
may be approximated by a generalized Pareto distribution
\f[
G_{\xi,\beta}(x) =
\left\{
\begin{array}{ll}
\beta^{-1}\left(1+\frac{\xi x}{\beta}\right)^{-1/\xi-1} & \textrm{if }\xi\neq0\\
\beta^{-1}\exp\left(-\frac{x}{\beta}\right) & \textrm{if }\xi=0,
\end{array}
\right.
\f]
with suitable parameters \f$\xi\f$ and \f$\beta\f$ that can be estimated, e.g., with the method of moments, cf.
Hosking and Wallis (1987),
\f[
\begin{array}{lll}
\hat{\xi} & = & \frac{1}{2}\left[1-\frac{(\hat{\mu}-u)^2}{\hat{\sigma}^2}\right]\\
\hat{\beta} & = & \frac{\hat{\mu}-u}{2}\left[\frac{(\hat{\mu}-u)^2}{\hat{\sigma}^2}+1\right],
\end{array}
\f]
\f$\hat{\mu}\f$ and \f$\hat{\sigma}^2\f$ being the empirical mean and variance of the samples over
the threshold \f$u\f$. Equivalently, the distribution function
\f$F_u(x-u)\f$ of the exceedances \f$x-u\f$ can be approximated by
\f$G_{\xi,\beta}(x-u)=G_{\xi,\beta,u}(x)\f$. Since for \f$x\geq u\f$ the distribution function \f$F(x)\f$
can be written as
\f[
F(x) = [1 - \P(X \leq u)]F_u(x - u) + \P(X \leq u)
\f]
and the probability \f$\P(X \leq u)\f$ can be approximated by the empirical distribution function
\f$F_n(u)\f$ evaluated at \f$u\f$, an estimator of \f$F(x)\f$ is given by
\f[
\widehat{F}(x) = [1 - F_n(u)]G_{\xi,\beta,u}(x) + F_n(u).
\f]
It can be shown that \f$\widehat{F}(x)\f$ is a generalized
Pareto distribution \f$G_{\xi,\bar{\beta},\bar{u}}(x)\f$ with \f$\bar{\beta}=\beta[1-F_n(u)]^{\xi}\f$
and \f$\bar{u}=u-\bar{\beta}\left\{[1-F_n(u)]^{-\xi}-1\right\}/\xi\f$. By inverting \f$\widehat{F}(x)\f$,
one obtains an estimator for the \f$\alpha\f$-quantile,
\f[
\hat{q}_{\alpha} = \bar{u} + \frac{\bar{\beta}}{\xi}\left[(1-\alpha)^{-\xi}-1\right],
\f]
and similarly an estimator for the (coherent) tail mean,
\f[
\widehat{CTM}_{\alpha} = \hat{q}_{\alpha} - \frac{\bar{\beta}}{\xi-1}(1-\alpha)^{-\xi},
\f]
cf. McNeil and Frey (2000).
Note that in case extreme values of the left tail are fitted, the distribution is mirrored with respect to the
\f$y\f$ axis such that the left tail can be treated as a right tail. The computed fit parameters thus define
the Pareto distribution that fits the mirrored left tail. When quantities like a quantile or a tail mean are
computed using the fit parameters obtained from the mirrored data, the result is mirrored back, yielding the
correct result.
For further details, see
J. R. M. Hosking and J. R. Wallis, Parameter and quantile estimation for the generalized Pareto distribution,
Technometrics, Volume 29, 1987, p. 339-349
A. J. McNeil and R. Frey, Estimation of Tail-Related Risk Measures for Heteroscedastic Financial Time Series:
an Extreme Value Approach, Journal of Empirical Finance, Volume 7, 2000, p. 271-300
@param quantile_probability
@param pot_threshold_value
*/
template<typename Sample, typename LeftRight>
struct peaks_over_threshold_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
// for boost::result_of
typedef boost::tuple<float_type, float_type, float_type> result_type;
// for left tail fitting, mirror the extreme values
typedef mpl::int_<is_same<LeftRight, left>::value ? -1 : 1> sign;
template<typename Args>
peaks_over_threshold_impl(Args const &args)
: Nu_(0)
, mu_(sign::value * numeric::fdiv(args[sample | Sample()], (std::size_t)1))
, sigma2_(numeric::fdiv(args[sample | Sample()], (std::size_t)1))
, threshold_(sign::value * args[pot_threshold_value])
, fit_parameters_(boost::make_tuple(0., 0., 0.))
, is_dirty_(true)
{
}
template<typename Args>
void operator ()(Args const &args)
{
this->is_dirty_ = true;
if (sign::value * args[sample] > this->threshold_)
{
this->mu_ += args[sample];
this->sigma2_ += args[sample] * args[sample];
++this->Nu_;
}
}
template<typename Args>
result_type result(Args const &args) const
{
if (this->is_dirty_)
{
this->is_dirty_ = false;
std::size_t cnt = count(args);
this->mu_ = sign::value * numeric::fdiv(this->mu_, this->Nu_);
this->sigma2_ = numeric::fdiv(this->sigma2_, this->Nu_);
this->sigma2_ -= this->mu_ * this->mu_;
float_type threshold_probability = numeric::fdiv(cnt - this->Nu_, cnt);
float_type tmp = numeric::fdiv(( this->mu_ - this->threshold_ )*( this->mu_ - this->threshold_ ), this->sigma2_);
float_type xi_hat = 0.5 * ( 1. - tmp );
float_type beta_hat = 0.5 * ( this->mu_ - this->threshold_ ) * ( 1. + tmp );
float_type beta_bar = beta_hat * std::pow(1. - threshold_probability, xi_hat);
float_type u_bar = this->threshold_ - beta_bar * ( std::pow(1. - threshold_probability, -xi_hat) - 1.)/xi_hat;
this->fit_parameters_ = boost::make_tuple(u_bar, beta_bar, xi_hat);
}
return this->fit_parameters_;
}
private:
std::size_t Nu_; // number of samples larger than threshold
mutable float_type mu_; // mean of Nu_ largest samples
mutable float_type sigma2_; // variance of Nu_ largest samples
float_type threshold_;
mutable result_type fit_parameters_; // boost::tuple that stores fit parameters
mutable bool is_dirty_;
};
///////////////////////////////////////////////////////////////////////////////
// peaks_over_threshold_prob_impl
// determines threshold from a given threshold probability using order statistics
/**
@brief Peaks over Threshold Method for Quantile and Tail Mean Estimation
@sa peaks_over_threshold_impl
@param quantile_probability
@param pot_threshold_probability
*/
template<typename Sample, typename LeftRight>
struct peaks_over_threshold_prob_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
// for boost::result_of
typedef boost::tuple<float_type, float_type, float_type> result_type;
// for left tail fitting, mirror the extreme values
typedef mpl::int_<is_same<LeftRight, left>::value ? -1 : 1> sign;
template<typename Args>
peaks_over_threshold_prob_impl(Args const &args)
: mu_(sign::value * numeric::fdiv(args[sample | Sample()], (std::size_t)1))
, sigma2_(numeric::fdiv(args[sample | Sample()], (std::size_t)1))
, threshold_probability_(args[pot_threshold_probability])
, fit_parameters_(boost::make_tuple(0., 0., 0.))
, is_dirty_(true)
{
}
void operator ()(dont_care)
{
this->is_dirty_ = true;
}
template<typename Args>
result_type result(Args const &args) const
{
if (this->is_dirty_)
{
this->is_dirty_ = false;
std::size_t cnt = count(args);
// the n'th cached sample provides an approximate threshold value u
std::size_t n = static_cast<std::size_t>(
std::ceil(
cnt * ( ( is_same<LeftRight, left>::value ) ? this->threshold_probability_ : 1. - this->threshold_probability_ )
)
);
// If n is in a valid range, return result, otherwise return NaN or throw exception
if ( n >= static_cast<std::size_t>(tail(args).size()))
{
if (std::numeric_limits<float_type>::has_quiet_NaN)
{
return boost::make_tuple(
std::numeric_limits<float_type>::quiet_NaN()
, std::numeric_limits<float_type>::quiet_NaN()
, std::numeric_limits<float_type>::quiet_NaN()
);
}
else
{
std::ostringstream msg;
msg << "index n = " << n << " is not in valid range [0, " << tail(args).size() << ")";
boost::throw_exception(std::runtime_error(msg.str()));
return boost::make_tuple(Sample(0), Sample(0), Sample(0));
}
}
else
{
float_type u = *(tail(args).begin() + n - 1) * sign::value;
// compute mean and variance of samples above/under threshold value u
for (std::size_t i = 0; i < n; ++i)
{
mu_ += *(tail(args).begin() + i);
sigma2_ += *(tail(args).begin() + i) * (*(tail(args).begin() + i));
}
this->mu_ = sign::value * numeric::fdiv(this->mu_, n);
this->sigma2_ = numeric::fdiv(this->sigma2_, n);
this->sigma2_ -= this->mu_ * this->mu_;
if (is_same<LeftRight, left>::value)
this->threshold_probability_ = 1. - this->threshold_probability_;
float_type tmp = numeric::fdiv(( this->mu_ - u )*( this->mu_ - u ), this->sigma2_);
float_type xi_hat = 0.5 * ( 1. - tmp );
float_type beta_hat = 0.5 * ( this->mu_ - u ) * ( 1. + tmp );
float_type beta_bar = beta_hat * std::pow(1. - threshold_probability_, xi_hat);
float_type u_bar = u - beta_bar * ( std::pow(1. - threshold_probability_, -xi_hat) - 1.)/xi_hat;
this->fit_parameters_ = boost::make_tuple(u_bar, beta_bar, xi_hat);
}
}
return this->fit_parameters_;
}
private:
mutable float_type mu_; // mean of samples above threshold u
mutable float_type sigma2_; // variance of samples above threshold u
mutable float_type threshold_probability_;
mutable result_type fit_parameters_; // boost::tuple that stores fit parameters
mutable bool is_dirty_;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::peaks_over_threshold
//
namespace tag
{
template<typename LeftRight>
struct peaks_over_threshold
: depends_on<count>
, pot_threshold_value
{
/// INTERNAL ONLY
///
typedef accumulators::impl::peaks_over_threshold_impl<mpl::_1, LeftRight> impl;
};
template<typename LeftRight>
struct peaks_over_threshold_prob
: depends_on<count, tail<LeftRight> >
, pot_threshold_probability
{
/// INTERNAL ONLY
///
typedef accumulators::impl::peaks_over_threshold_prob_impl<mpl::_1, LeftRight> impl;
};
struct abstract_peaks_over_threshold
: depends_on<>
{
};
}
///////////////////////////////////////////////////////////////////////////////
// extract::peaks_over_threshold
//
namespace extract
{
extractor<tag::abstract_peaks_over_threshold> const peaks_over_threshold = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(peaks_over_threshold)
}
using extract::peaks_over_threshold;
// peaks_over_threshold<LeftRight>(with_threshold_value) -> peaks_over_threshold<LeftRight>
template<typename LeftRight>
struct as_feature<tag::peaks_over_threshold<LeftRight>(with_threshold_value)>
{
typedef tag::peaks_over_threshold<LeftRight> type;
};
// peaks_over_threshold<LeftRight>(with_threshold_probability) -> peaks_over_threshold_prob<LeftRight>
template<typename LeftRight>
struct as_feature<tag::peaks_over_threshold<LeftRight>(with_threshold_probability)>
{
typedef tag::peaks_over_threshold_prob<LeftRight> type;
};
template<typename LeftRight>
struct feature_of<tag::peaks_over_threshold<LeftRight> >
: feature_of<tag::abstract_peaks_over_threshold>
{
};
template<typename LeftRight>
struct feature_of<tag::peaks_over_threshold_prob<LeftRight> >
: feature_of<tag::abstract_peaks_over_threshold>
{
};
// So that peaks_over_threshold can be automatically substituted
// with weighted_peaks_over_threshold when the weight parameter is non-void.
template<typename LeftRight>
struct as_weighted_feature<tag::peaks_over_threshold<LeftRight> >
{
typedef tag::weighted_peaks_over_threshold<LeftRight> type;
};
template<typename LeftRight>
struct feature_of<tag::weighted_peaks_over_threshold<LeftRight> >
: feature_of<tag::peaks_over_threshold<LeftRight> >
{};
// So that peaks_over_threshold_prob can be automatically substituted
// with weighted_peaks_over_threshold_prob when the weight parameter is non-void.
template<typename LeftRight>
struct as_weighted_feature<tag::peaks_over_threshold_prob<LeftRight> >
{
typedef tag::weighted_peaks_over_threshold_prob<LeftRight> type;
};
template<typename LeftRight>
struct feature_of<tag::weighted_peaks_over_threshold_prob<LeftRight> >
: feature_of<tag::peaks_over_threshold_prob<LeftRight> >
{};
}} // namespace boost::accumulators
#ifdef _MSC_VER
# pragma warning(pop)
#endif
#endif
@@ -0,0 +1,205 @@
///////////////////////////////////////////////////////////////////////////////
// pot_quantile.hpp
//
// Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_POT_QUANTILE_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_POT_QUANTILE_HPP_DE_01_01_2006
#include <vector>
#include <limits>
#include <numeric>
#include <functional>
#include <boost/parameter/keyword.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/mpl/if.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/tail.hpp>
#include <boost/accumulators/statistics/peaks_over_threshold.hpp>
#include <boost/accumulators/statistics/weighted_peaks_over_threshold.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// pot_quantile_impl
//
/**
@brief Quantile Estimation based on Peaks over Threshold Method (for both left and right tails)
Computes an estimate
\f[
\hat{q}_{\alpha} = \bar{u} + \frac{\bar{\beta}}{\xi}\left[(1-\alpha)^{-\xi}-1\right]
\f]
for a right or left extreme quantile, \f$\bar[u]\f$, \f$\bar{\beta}\f$ and \f$\xi\f$ being the parameters of the
generalized Pareto distribution that approximates the right tail of the distribution (or the mirrored left tail,
in case the left tail is used). In the latter case, the result is mirrored back, yielding the correct result.
*/
template<typename Sample, typename Impl, typename LeftRight>
struct pot_quantile_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
// for boost::result_of
typedef float_type result_type;
pot_quantile_impl(dont_care)
: sign_((is_same<LeftRight, left>::value) ? -1 : 1)
{
}
template<typename Args>
result_type result(Args const &args) const
{
typedef
typename mpl::if_<
is_same<Impl, weighted>
, tag::weighted_peaks_over_threshold<LeftRight>
, tag::peaks_over_threshold<LeftRight>
>::type
peaks_over_threshold_tag;
extractor<peaks_over_threshold_tag> const some_peaks_over_threshold = {};
float_type u_bar = some_peaks_over_threshold(args).template get<0>();
float_type beta_bar = some_peaks_over_threshold(args).template get<1>();
float_type xi_hat = some_peaks_over_threshold(args).template get<2>();
return this->sign_ * (u_bar + beta_bar/xi_hat * ( std::pow(
is_same<LeftRight, left>::value ? args[quantile_probability] : 1. - args[quantile_probability]
, -xi_hat
) - 1.));
}
private:
short sign_; // if the fit parameters from the mirrored left tail extreme values are used, mirror back the result
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::pot_quantile<>
// tag::pot_quantile_prob<>
// tag::weighted_pot_quantile<>
// tag::weighted_pot_quantile_prob<>
//
namespace tag
{
template<typename LeftRight>
struct pot_quantile
: depends_on<peaks_over_threshold<LeftRight> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::pot_quantile_impl<mpl::_1, unweighted, LeftRight> impl;
};
template<typename LeftRight>
struct pot_quantile_prob
: depends_on<peaks_over_threshold_prob<LeftRight> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::pot_quantile_impl<mpl::_1, unweighted, LeftRight> impl;
};
template<typename LeftRight>
struct weighted_pot_quantile
: depends_on<weighted_peaks_over_threshold<LeftRight> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::pot_quantile_impl<mpl::_1, weighted, LeftRight> impl;
};
template<typename LeftRight>
struct weighted_pot_quantile_prob
: depends_on<weighted_peaks_over_threshold_prob<LeftRight> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::pot_quantile_impl<mpl::_1, weighted, LeftRight> impl;
};
}
// pot_quantile<LeftRight>(with_threshold_value) -> pot_quantile<LeftRight>
template<typename LeftRight>
struct as_feature<tag::pot_quantile<LeftRight>(with_threshold_value)>
{
typedef tag::pot_quantile<LeftRight> type;
};
// pot_quantile<LeftRight>(with_threshold_probability) -> pot_quantile_prob<LeftRight>
template<typename LeftRight>
struct as_feature<tag::pot_quantile<LeftRight>(with_threshold_probability)>
{
typedef tag::pot_quantile_prob<LeftRight> type;
};
// weighted_pot_quantile<LeftRight>(with_threshold_value) -> weighted_pot_quantile<LeftRight>
template<typename LeftRight>
struct as_feature<tag::weighted_pot_quantile<LeftRight>(with_threshold_value)>
{
typedef tag::weighted_pot_quantile<LeftRight> type;
};
// weighted_pot_quantile<LeftRight>(with_threshold_probability) -> weighted_pot_quantile_prob<LeftRight>
template<typename LeftRight>
struct as_feature<tag::weighted_pot_quantile<LeftRight>(with_threshold_probability)>
{
typedef tag::weighted_pot_quantile_prob<LeftRight> type;
};
// for the purposes of feature-based dependency resolution,
// pot_quantile<LeftRight> and pot_quantile_prob<LeftRight> provide
// the same feature as quantile
template<typename LeftRight>
struct feature_of<tag::pot_quantile<LeftRight> >
: feature_of<tag::quantile>
{
};
template<typename LeftRight>
struct feature_of<tag::pot_quantile_prob<LeftRight> >
: feature_of<tag::quantile>
{
};
// So that pot_quantile can be automatically substituted
// with weighted_pot_quantile when the weight parameter is non-void.
template<typename LeftRight>
struct as_weighted_feature<tag::pot_quantile<LeftRight> >
{
typedef tag::weighted_pot_quantile<LeftRight> type;
};
template<typename LeftRight>
struct feature_of<tag::weighted_pot_quantile<LeftRight> >
: feature_of<tag::pot_quantile<LeftRight> >
{
};
// So that pot_quantile_prob can be automatically substituted
// with weighted_pot_quantile_prob when the weight parameter is non-void.
template<typename LeftRight>
struct as_weighted_feature<tag::pot_quantile_prob<LeftRight> >
{
typedef tag::weighted_pot_quantile_prob<LeftRight> type;
};
template<typename LeftRight>
struct feature_of<tag::weighted_pot_quantile_prob<LeftRight> >
: feature_of<tag::pot_quantile_prob<LeftRight> >
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,211 @@
///////////////////////////////////////////////////////////////////////////////
// pot_tail_mean.hpp
//
// Copyright 2006 Daniel Egloff, Olivier Gygi. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_POT_TAIL_MEAN_HPP_DE_01_01_2006
#define BOOST_ACCUMULATORS_STATISTICS_POT_TAIL_MEAN_HPP_DE_01_01_2006
#include <vector>
#include <limits>
#include <numeric>
#include <functional>
#include <boost/range.hpp>
#include <boost/parameter/keyword.hpp>
#include <boost/tuple/tuple.hpp>
#include <boost/mpl/if.hpp>
#include <boost/mpl/placeholders.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/peaks_over_threshold.hpp>
#include <boost/accumulators/statistics/weighted_peaks_over_threshold.hpp>
#include <boost/accumulators/statistics/pot_quantile.hpp>
#include <boost/accumulators/statistics/tail_mean.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// pot_tail_mean_impl
//
/**
@brief Estimation of the (coherent) tail mean based on the peaks over threshold method (for both left and right tails)
Computes an estimate for the (coherent) tail mean
\f[
\widehat{CTM}_{\alpha} = \hat{q}_{\alpha} - \frac{\bar{\beta}}{\xi-1}(1-\alpha)^{-\xi},
\f]
where \f$\bar[u]\f$, \f$\bar{\beta}\f$ and \f$\xi\f$ are the parameters of the
generalized Pareto distribution that approximates the right tail of the distribution (or the
mirrored left tail, in case the left tail is used). In the latter case, the result is mirrored
back, yielding the correct result.
*/
template<typename Sample, typename Impl, typename LeftRight>
struct pot_tail_mean_impl
: accumulator_base
{
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type float_type;
// for boost::result_of
typedef float_type result_type;
pot_tail_mean_impl(dont_care)
: sign_((is_same<LeftRight, left>::value) ? -1 : 1)
{
}
template<typename Args>
result_type result(Args const &args) const
{
typedef
typename mpl::if_<
is_same<Impl, weighted>
, tag::weighted_peaks_over_threshold<LeftRight>
, tag::peaks_over_threshold<LeftRight>
>::type
peaks_over_threshold_tag;
typedef
typename mpl::if_<
is_same<Impl, weighted>
, tag::weighted_pot_quantile<LeftRight>
, tag::pot_quantile<LeftRight>
>::type
pot_quantile_tag;
extractor<peaks_over_threshold_tag> const some_peaks_over_threshold = {};
extractor<pot_quantile_tag> const some_pot_quantile = {};
float_type beta_bar = some_peaks_over_threshold(args).template get<1>();
float_type xi_hat = some_peaks_over_threshold(args).template get<2>();
return some_pot_quantile(args) - this->sign_ * beta_bar/( xi_hat - 1. ) * std::pow(
is_same<LeftRight, left>::value ? args[quantile_probability] : 1. - args[quantile_probability]
, -xi_hat);
}
private:
short sign_; // if the fit parameters from the mirrored left tail extreme values are used, mirror back the result
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::pot_tail_mean
// tag::pot_tail_mean_prob
//
namespace tag
{
template<typename LeftRight>
struct pot_tail_mean
: depends_on<peaks_over_threshold<LeftRight>, pot_quantile<LeftRight> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, unweighted, LeftRight> impl;
};
template<typename LeftRight>
struct pot_tail_mean_prob
: depends_on<peaks_over_threshold_prob<LeftRight>, pot_quantile_prob<LeftRight> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, unweighted, LeftRight> impl;
};
template<typename LeftRight>
struct weighted_pot_tail_mean
: depends_on<weighted_peaks_over_threshold<LeftRight>, weighted_pot_quantile<LeftRight> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, weighted, LeftRight> impl;
};
template<typename LeftRight>
struct weighted_pot_tail_mean_prob
: depends_on<weighted_peaks_over_threshold_prob<LeftRight>, weighted_pot_quantile_prob<LeftRight> >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::pot_tail_mean_impl<mpl::_1, weighted, LeftRight> impl;
};
}
// pot_tail_mean<LeftRight>(with_threshold_value) -> pot_tail_mean<LeftRight>
template<typename LeftRight>
struct as_feature<tag::pot_tail_mean<LeftRight>(with_threshold_value)>
{
typedef tag::pot_tail_mean<LeftRight> type;
};
// pot_tail_mean<LeftRight>(with_threshold_probability) -> pot_tail_mean_prob<LeftRight>
template<typename LeftRight>
struct as_feature<tag::pot_tail_mean<LeftRight>(with_threshold_probability)>
{
typedef tag::pot_tail_mean_prob<LeftRight> type;
};
// weighted_pot_tail_mean<LeftRight>(with_threshold_value) -> weighted_pot_tail_mean<LeftRight>
template<typename LeftRight>
struct as_feature<tag::weighted_pot_tail_mean<LeftRight>(with_threshold_value)>
{
typedef tag::weighted_pot_tail_mean<LeftRight> type;
};
// weighted_pot_tail_mean<LeftRight>(with_threshold_probability) -> weighted_pot_tail_mean_prob<LeftRight>
template<typename LeftRight>
struct as_feature<tag::weighted_pot_tail_mean<LeftRight>(with_threshold_probability)>
{
typedef tag::weighted_pot_tail_mean_prob<LeftRight> type;
};
// for the purposes of feature-based dependency resolution,
// pot_tail_mean<LeftRight> and pot_tail_mean_prob<LeftRight> provide
// the same feature as tail_mean
template<typename LeftRight>
struct feature_of<tag::pot_tail_mean<LeftRight> >
: feature_of<tag::tail_mean>
{
};
template<typename LeftRight>
struct feature_of<tag::pot_tail_mean_prob<LeftRight> >
: feature_of<tag::tail_mean>
{
};
// So that pot_tail_mean can be automatically substituted
// with weighted_pot_tail_mean when the weight parameter is non-void.
template<typename LeftRight>
struct as_weighted_feature<tag::pot_tail_mean<LeftRight> >
{
typedef tag::weighted_pot_tail_mean<LeftRight> type;
};
template<typename LeftRight>
struct feature_of<tag::weighted_pot_tail_mean<LeftRight> >
: feature_of<tag::pot_tail_mean<LeftRight> >
{
};
// So that pot_tail_mean_prob can be automatically substituted
// with weighted_pot_tail_mean_prob when the weight parameter is non-void.
template<typename LeftRight>
struct as_weighted_feature<tag::pot_tail_mean_prob<LeftRight> >
{
typedef tag::weighted_pot_tail_mean_prob<LeftRight> type;
};
template<typename LeftRight>
struct feature_of<tag::weighted_pot_tail_mean_prob<LeftRight> >
: feature_of<tag::pot_tail_mean_prob<LeftRight> >
{
};
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,80 @@
///////////////////////////////////////////////////////////////////////////////
// rolling_count.hpp
//
// Copyright 2008 Eric Niebler. Distributed under the Boost
// Software License, Version 1.0. (See accompanying file
// LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_COUNT_HPP_EAN_26_12_2008
#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_COUNT_HPP_EAN_26_12_2008
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/rolling_window.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// rolling_count_impl
// returns the count of elements in the rolling window
template<typename Sample>
struct rolling_count_impl
: accumulator_base
{
typedef std::size_t result_type;
rolling_count_impl(dont_care)
{}
template<typename Args>
result_type result(Args const &args) const
{
return static_cast<std::size_t>(rolling_window_plus1(args).size()) - is_rolling_window_plus1_full(args);
}
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::rolling_count
//
namespace tag
{
struct rolling_count
: depends_on< rolling_window_plus1 >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::rolling_count_impl< mpl::_1 > impl;
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
/// tag::rolling_window::window_size named parameter
static boost::parameter::keyword<tag::rolling_window_size> const window_size;
#endif
};
} // namespace tag
///////////////////////////////////////////////////////////////////////////////
// extract::rolling_count
//
namespace extract
{
extractor<tag::rolling_count> const rolling_count = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_count)
}
using extract::rolling_count;
}} // namespace boost::accumulators
#endif
@@ -0,0 +1,179 @@
///////////////////////////////////////////////////////////////////////////////
// rolling_mean.hpp
// Copyright (C) 2008 Eric Niebler.
// Copyright (C) 2012 Pieter Bastiaan Ober (Integricom).
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef BOOST_ACCUMULATORS_STATISTICS_ROLLING_MEAN_HPP_EAN_26_12_2008
#define BOOST_ACCUMULATORS_STATISTICS_ROLLING_MEAN_HPP_EAN_26_12_2008
#include <boost/mpl/placeholders.hpp>
#include <boost/accumulators/framework/accumulator_base.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/accumulators/numeric/functional.hpp>
#include <boost/accumulators/framework/parameters/sample.hpp>
#include <boost/accumulators/framework/depends_on.hpp>
#include <boost/accumulators/statistics_fwd.hpp>
#include <boost/accumulators/statistics/rolling_sum.hpp>
#include <boost/accumulators/statistics/rolling_count.hpp>
namespace boost { namespace accumulators
{
namespace impl
{
///////////////////////////////////////////////////////////////////////////////
// lazy_rolling_mean_impl
// returns the mean over the rolling window and is calculated only
// when the result is requested
template<typename Sample>
struct lazy_rolling_mean_impl
: accumulator_base
{
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t, void, void>::result_type result_type;
lazy_rolling_mean_impl(dont_care)
{
}
template<typename Args>
result_type result(Args const &args) const
{
return numeric::fdiv(rolling_sum(args), rolling_count(args));
}
};
///////////////////////////////////////////////////////////////////////////////
// immediate_rolling_mean_impl
// The non-lazy version computes the rolling mean recursively when a new
// sample is added
template<typename Sample>
struct immediate_rolling_mean_impl
: accumulator_base
{
// for boost::result_of
typedef typename numeric::functional::fdiv<Sample, std::size_t>::result_type result_type;
template<typename Args>
immediate_rolling_mean_impl(Args const &args)
: mean_(numeric::fdiv(args[sample | Sample()],numeric::one<std::size_t>::value))
{
}
template<typename Args>
void operator()(Args const &args)
{
if(is_rolling_window_plus1_full(args))
{
mean_ += numeric::fdiv(args[sample]-rolling_window_plus1(args).front(),rolling_count(args));
}
else
{
result_type prev_mean = mean_;
mean_ += numeric::fdiv(args[sample]-prev_mean,rolling_count(args));
}
}
template<typename Args>
result_type result(Args const &) const
{
return mean_;
}
private:
result_type mean_;
};
} // namespace impl
///////////////////////////////////////////////////////////////////////////////
// tag::lazy_rolling_mean
// tag::immediate_rolling_mean
// tag::rolling_mean
//
namespace tag
{
struct lazy_rolling_mean
: depends_on< rolling_sum, rolling_count >
{
/// INTERNAL ONLY
///
typedef accumulators::impl::lazy_rolling_mean_impl< mpl::_1 > impl;
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
/// tag::rolling_window::window_size named parameter
static boost::parameter::keyword<tag::rolling_window_size> const window_size;
#endif
};
struct immediate_rolling_mean
: depends_on< rolling_window_plus1, rolling_count>
{
/// INTERNAL ONLY
///
typedef accumulators::impl::immediate_rolling_mean_impl< mpl::_1> impl;
#ifdef BOOST_ACCUMULATORS_DOXYGEN_INVOKED
/// tag::rolling_window::window_size named parameter
static boost::parameter::keyword<tag::rolling_window_size> const window_size;
#endif
};
// make immediate_rolling_mean the default implementation
struct rolling_mean : immediate_rolling_mean {};
} // namespace tag
///////////////////////////////////////////////////////////////////////////////
// extract::lazy_rolling_mean
// extract::immediate_rolling_mean
// extract::rolling_mean
//
namespace extract
{
extractor<tag::lazy_rolling_mean> const lazy_rolling_mean = {};
extractor<tag::immediate_rolling_mean> const immediate_rolling_mean = {};
extractor<tag::rolling_mean> const rolling_mean = {};
BOOST_ACCUMULATORS_IGNORE_GLOBAL(lazy_rolling_mean)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(immediate_rolling_mean)
BOOST_ACCUMULATORS_IGNORE_GLOBAL(rolling_mean)
}
using extract::lazy_rolling_mean;
using extract::immediate_rolling_mean;
using extract::rolling_mean;
// rolling_mean(lazy) -> lazy_rolling_mean
template<>
struct as_feature<tag::rolling_mean(lazy)>
{
typedef tag::lazy_rolling_mean type;
};
// rolling_mean(immediate) -> immediate_rolling_mean
template<>
struct as_feature<tag::rolling_mean(immediate)>
{
typedef tag::immediate_rolling_mean type;
};
// for the purposes of feature-based dependency resolution,
// immediate_rolling_mean provides the same feature as rolling_mean
template<>
struct feature_of<tag::immediate_rolling_mean>
: feature_of<tag::rolling_mean>
{
};
// for the purposes of feature-based dependency resolution,
// lazy_rolling_mean provides the same feature as rolling_mean
template<>
struct feature_of<tag::lazy_rolling_mean>
: feature_of<tag::rolling_mean>
{
};
}} // namespace boost::accumulators
#endif
Loaded 100 of 15685 files, more files were not shown because too many files have changed in this diff. Show more