-
Notifications
You must be signed in to change notification settings - Fork 10.5k
[Accelerate] [Quadrature] New Quadrature Overlay #23127
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
stephentyrone
merged 14 commits into
swiftlang:master
from
FlexMonkey:accelerate-quadrature
Apr 19, 2019
Merged
Changes from all commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
0ab6417
[Accelerate] [Quadrature] New Quadrature Overlay
FlexMonkey 93dcf3a
Fixes in response to PR Review.
FlexMonkey dfa1f7a
Code Review Fixes.
FlexMonkey 60d723f
Code Review Fixes.
FlexMonkey 8640fa5
Tidy up Passing Integrand to `quadrature_integrate_function`.
FlexMonkey 36f8882
Make `Quadrature` a struct, and remove requirement for `integrand` to…
FlexMonkey 2dd0f7d
Code Review Changes
4078112
Vectorized Integrand for Quadrature
FlexMonkey 31935b0
Vectorized Integrand for Quadrature
FlexMonkey 69d2a0f
Vectorized Integrand for Quadrature
FlexMonkey 8a31d6b
Delete ContiguousCollection.swift
FlexMonkey 4f323a9
Merge branch 'master' into accelerate-quadrature
FlexMonkey b25cb01
Refactor tests.
FlexMonkey 85918ce
Merge branch 'master' into accelerate-quadrature
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,295 @@ | ||
//===----------------------------------------------------------------------===// | ||
// | ||
// This source file is part of the Swift.org open source project | ||
// | ||
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors | ||
// Licensed under Apache License v2.0 with Runtime Library Exception | ||
// | ||
// See https://swift.org/LICENSE.txt for license information | ||
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors | ||
// | ||
//===----------------------------------------------------------------------===// | ||
|
||
import Accelerate | ||
|
||
// MARK: Quadrature | ||
|
||
@available(iOS 9999, macOS 9999, tvOS 9999, watchOS 9999, *) | ||
/// A structure that approximates the definite integral of a function over a finite interval. | ||
/// | ||
/// The following code is an example of using a `Quadrature` structure to calculate the | ||
/// area under a curve defined by `y = sqrt(radius * radius - pow(x - radius, 2))`: | ||
/// | ||
/// | ||
/// let quadrature = Quadrature(integrator: .qags(maxIntervals: 10), | ||
/// absoluteTolerance: 1.0e-8, | ||
/// relativeTolerance: 1.0e-2) | ||
/// | ||
/// let result = quadrature.integrate(over: 0.0 ... 25.0) { x in | ||
/// let radius: Double = 12.5 | ||
/// return sqrt(radius * radius - pow(x - radius, 2)) | ||
/// } | ||
/// | ||
/// switch result { | ||
/// case .success(let integralResult, let estimatedAbsoluteError): | ||
/// print("quadrature success:", integralResult, | ||
/// estimatedAbsoluteError) | ||
/// case .failure(let error): | ||
/// print("quadrature error:", error.errorDescription) | ||
/// } | ||
/// | ||
/// Alternatively, you can integrate over a function that uses vectors for its | ||
/// source and destination. For example: | ||
/// | ||
/// func vectorExp(x: UnsafeBufferPointer<Double>, | ||
/// y: UnsafeMutableBufferPointer<Double>) { | ||
/// let radius: Double = 12.5 | ||
/// for i in 0 ..< x.count { | ||
/// y[i] = sqrt(radius * radius - pow(x[i] - radius, 2)) | ||
/// } | ||
/// } | ||
/// | ||
/// let vRresult = quadrature.integrate(over: 0.0 ... diameter, | ||
/// integrand: vectorExp) | ||
public struct Quadrature { | ||
|
||
private var integrateOptions = quadrature_integrate_options() | ||
|
||
/// Initializes and returns a quadrature instance. | ||
/// | ||
/// - Parameter integrator: An enumeration specifying the integration algorithm and relevant properties. | ||
/// - Parameter absoluteTolerance: Requested absolute tolerance on the result. | ||
/// - Parameter relativeTolerance: Requested relative tolerance on the result. | ||
public init(integrator: Integrator, | ||
absoluteTolerance: Double = 1.0e-8, | ||
relativeTolerance: Double = 1.0e-2){ | ||
|
||
integrateOptions.abs_tolerance = absoluteTolerance | ||
integrateOptions.rel_tolerance = relativeTolerance | ||
|
||
switch integrator { | ||
case .qng: | ||
integrateOptions.integrator = QUADRATURE_INTEGRATE_QNG | ||
case .qag(let pointsPerInterval, let maxIntervals): | ||
integrateOptions.integrator = QUADRATURE_INTEGRATE_QAG | ||
integrateOptions.qag_points_per_interval = pointsPerInterval.points | ||
integrateOptions.max_intervals = maxIntervals | ||
case .qags(let maxIntervals): | ||
integrateOptions.integrator = QUADRATURE_INTEGRATE_QAGS | ||
integrateOptions.max_intervals = maxIntervals | ||
} | ||
} | ||
|
||
/// The quadrature instance's requested absolute tolerance on the result. | ||
public var absoluteTolerance: Double { | ||
set { | ||
integrateOptions.abs_tolerance = newValue | ||
} | ||
get { | ||
return integrateOptions.abs_tolerance | ||
} | ||
} | ||
|
||
/// The quadrature instance's requested relative tolerance on the result. | ||
public var relativeTolerance: Double { | ||
set { | ||
integrateOptions.rel_tolerance = newValue | ||
} | ||
get { | ||
return integrateOptions.rel_tolerance | ||
} | ||
} | ||
|
||
/// Performs the integration over the supplied function. | ||
/// | ||
/// - Parameter interval: The lower and upper bounds of the integration interval. | ||
/// - Parameter integrand: The function to integrate. The input value is `x` that's within the interval over which the integrand is being integrated, and the output value is the corresponding value `y = integrand(x)` at those points. | ||
public func integrate(over interval: ClosedRange<Double>, | ||
integrand: (_ input: UnsafeBufferPointer<Double>, _ result: UnsafeMutableBufferPointer<Double>) -> ()) -> | ||
Result<(integralResult: Double, estimatedAbsoluteError: Double), Error>{ | ||
|
||
var status = QUADRATURE_SUCCESS | ||
var estimatedAbsoluteError: Double = 0 | ||
var result: Double = 0 | ||
|
||
var callback: quadrature_integrate_function! | ||
|
||
withoutActuallyEscaping(integrand) {escapableIntegrand in | ||
withUnsafePointer(to: escapableIntegrand) { | ||
let integrandPointer = UnsafeMutableRawPointer(mutating: $0) | ||
|
||
callback = quadrature_integrate_function( | ||
fun: { (arg: UnsafeMutableRawPointer?, | ||
n: Int, | ||
x: UnsafePointer<Double>, | ||
y: UnsafeMutablePointer<Double> | ||
) in | ||
|
||
guard let integrand = arg?.load(as: ((UnsafeBufferPointer<Double>, UnsafeMutableBufferPointer<Double>) ->()).self) else { | ||
return | ||
} | ||
|
||
integrand(UnsafeBufferPointer(start: x, count: n), | ||
UnsafeMutableBufferPointer(start: y, count: n)) | ||
}, | ||
fun_arg: integrandPointer) | ||
|
||
withUnsafePointer(to: self.integrateOptions) { options in | ||
result = quadrature_integrate(&callback, | ||
interval.lowerBound, | ||
interval.upperBound, | ||
options, | ||
&status, | ||
&estimatedAbsoluteError, | ||
0, | ||
nil) | ||
} | ||
} | ||
} | ||
|
||
if status == QUADRATURE_SUCCESS { | ||
return .success((integralResult: result, | ||
estimatedAbsoluteError: estimatedAbsoluteError)) | ||
} else { | ||
return .failure(Error(quadratureStatus: status)) | ||
} | ||
} | ||
|
||
/// Performs the integration over the supplied function. | ||
/// | ||
/// - Parameter interval: The lower and upper bounds of the integration interval. | ||
/// - Parameter integrand: The function to integrate. The input value is `x` that's within the interval over which the integrand is being integrated, and the output value is the corresponding value `y = integrand(x)` at those points. | ||
public func integrate(over interval: ClosedRange<Double>, | ||
FlexMonkey marked this conversation as resolved.
Show resolved
Hide resolved
|
||
integrand: (Double) -> Double) -> | ||
Result<(integralResult: Double, estimatedAbsoluteError: Double), Error> { | ||
|
||
var status = QUADRATURE_SUCCESS | ||
var estimatedAbsoluteError: Double = 0 | ||
var result: Double = 0 | ||
|
||
var callback: quadrature_integrate_function! | ||
|
||
withoutActuallyEscaping(integrand) {escapableIntegrand in | ||
withUnsafePointer(to: escapableIntegrand) { | ||
let integrandPointer = UnsafeMutableRawPointer(mutating: $0) | ||
|
||
callback = quadrature_integrate_function( | ||
fun: { (arg: UnsafeMutableRawPointer?, | ||
n: Int, | ||
x: UnsafePointer<Double>, | ||
y: UnsafeMutablePointer<Double> | ||
) in | ||
|
||
guard let integrand = arg?.load(as: ((Double) -> Double).self) else { | ||
return | ||
} | ||
|
||
(0 ..< n).forEach { i in | ||
y[i] = integrand(x[i]) | ||
} | ||
}, | ||
fun_arg: integrandPointer) | ||
|
||
withUnsafePointer(to: self.integrateOptions) { options in | ||
result = quadrature_integrate(&callback, | ||
interval.lowerBound, | ||
interval.upperBound, | ||
options, | ||
&status, | ||
&estimatedAbsoluteError, | ||
0, | ||
nil) | ||
} | ||
} | ||
} | ||
|
||
if status == QUADRATURE_SUCCESS { | ||
return .success((integralResult: result, | ||
estimatedAbsoluteError: estimatedAbsoluteError)) | ||
} else { | ||
return .failure(Error(quadratureStatus: status)) | ||
} | ||
} | ||
|
||
public enum Integrator { | ||
/// Simple non-adaptive automatic integrator using Gauss-Kronrod-Patterson quadrature coefficients. | ||
/// Evaluates 21, or 43, or 87 points in the interval until the requested accuracy is reached. | ||
case qng | ||
|
||
/// Simple non-adaptive automatic integrator using Gauss-Kronrod-Patterson quadrature coefficients. | ||
/// Evaluates 21, or 43, or 87 points in the interval until the requested accuracy is reached. | ||
public static let nonAdaptive = Integrator.qng | ||
|
||
/// Simple globally adaptive integrator. | ||
/// Allows selection of the number of Gauss-Kronrod points used in each subinterval, and the max number of subintervals. | ||
case qag(pointsPerInterval: QAGPointsPerInterval, maxIntervals: Int) | ||
|
||
/// Simple globally adaptive integrator. | ||
/// Allows selection of the number of Gauss-Kronrod points used in each subinterval, and the max number of subintervals. | ||
public static func adaptive(pointsPerInterval: QAGPointsPerInterval, maxIntervals: Int) -> Integrator { | ||
return Integrator.qag(pointsPerInterval: pointsPerInterval, maxIntervals: maxIntervals) | ||
} | ||
|
||
/// Global adaptive quadrature based on 21-point or 15-point (if at least one bound is infinite) Gauss–Kronrod quadrature within each subinterval, with acceleration by Peter Wynn's epsilon algorithm. | ||
/// If at least one of the interval bounds is infinite, this is equivalent to the QUADPACK QAGI routine. Otherwise, this is equivalent to the QUADPACK QAGS routine. | ||
case qags(maxIntervals: Int) | ||
|
||
/// Global adaptive quadrature based on 21-point or 15-point (if at least one bound is infinite) Gauss–Kronrod quadrature within each subinterval, with acceleration by Peter Wynn's epsilon algorithm. | ||
/// If at least one of the interval bounds is infinite, this is equivalent to the QUADPACK QAGI routine. Otherwise, this is equivalent to the QUADPACK QAGS routine. | ||
public static func adaptiveWithSingularities(maxIntervals: Int) -> Integrator { | ||
return Integrator.qags(maxIntervals: maxIntervals) | ||
} | ||
} | ||
|
||
public struct QAGPointsPerInterval { | ||
public let points: Int | ||
private init(points: Int) { self.points = points } | ||
|
||
public static let fifteen = QAGPointsPerInterval(points: 15) | ||
public static let twentyOne = QAGPointsPerInterval(points: 21) | ||
public static let thirtyOne = QAGPointsPerInterval(points: 31) | ||
public static let fortyOne = QAGPointsPerInterval(points: 41) | ||
public static let fiftyOne = QAGPointsPerInterval(points: 51) | ||
public static let sixtyOne = QAGPointsPerInterval(points: 61) | ||
} | ||
|
||
public enum Error: Swift.Error { | ||
case generic | ||
case invalidArgument | ||
case `internal` | ||
case integrateMaxEval | ||
case badIntegrandBehaviour | ||
|
||
public init(quadratureStatus: quadrature_status) { | ||
switch quadratureStatus { | ||
case QUADRATURE_ERROR: | ||
self = .generic | ||
case QUADRATURE_INVALID_ARG_ERROR: | ||
self = .invalidArgument | ||
case QUADRATURE_INTERNAL_ERROR: | ||
self = .internal | ||
case QUADRATURE_INTEGRATE_MAX_EVAL_ERROR: | ||
self = .integrateMaxEval | ||
case QUADRATURE_INTEGRATE_BAD_BEHAVIOUR_ERROR: | ||
self = .badIntegrandBehaviour | ||
default: | ||
self = .internal | ||
} | ||
} | ||
|
||
public var errorDescription: String { | ||
switch self { | ||
case .generic: | ||
return "Generic error." | ||
case .invalidArgument: | ||
return "Invalid Argument." | ||
case .internal: | ||
return "This is a bug in the Quadrature code, please file a bug report." | ||
case .integrateMaxEval: | ||
return "The requested accuracy limit could not be reached with the allowed number of evals/subdivisions." | ||
case .badIntegrandBehaviour: | ||
return "Extremely bad integrand behaviour, or excessive roundoff error occurs at some points of the integration interval." | ||
} | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.