licenses
sequencelengths 1
3
| version
stringclasses 677
values | tree_hash
stringlengths 40
40
| path
stringclasses 1
value | type
stringclasses 2
values | size
stringlengths 2
8
| text
stringlengths 25
67.1M
| package_name
stringlengths 2
41
| repo
stringlengths 33
86
|
---|---|---|---|---|---|---|---|---|
[
"MIT"
] | 0.3.1 | 1467be4e01897dae9b5c739643d2de0d790d25e0 | code | 14521 | module ReusePatterns
using InteractiveUtils
using Combinatorics
export forward, @forward,
@copy_fields,
@quasiabstract, concretetype, isquasiabstract, isquasiconcrete
"""
`forward(sender::Tuple{Type,Symbol}, receiver::Type, method::Method; withtypes=true, allargs=true)`
Return a `Vector{String}` containing the Julia code to properly forward `method` calls from a `sender` type to a receiver type.
The `sender` tuple must contain a structure type, and a symbol with the name of one of its fields.
The `withtypes` keyword controls whether the forwarding method has type annotated arguments. The `allargs` keyword controls whether all arguments should be used, or just the first ones up to the last containing the `receiver` type.
Both keywords are `true` by default, but they can be set to `false` to decrease the number of forwarded methods.
# Example:
Implement a wrapper for an `Int` object, and forward the `+` method accepting `Int`:
```julia-repl
struct Wrapper{T}
wrappee::T
extra
Wrapper{T}(args...; kw...) where T = new(T(args...; kw...), nothing)
end
# Prepare and evaluate forwarding methods:
m = forward((Wrapper, :wrappee), Int, which(+, (Int, Int)))
eval.(Meta.parse.(m))
# Instantiate two wrapped `Int`
i1 = Wrapper{Int}(1)
i2 = Wrapper{Int}(2)
# And add them seamlessly
println(i1 + 2)
println( 1 + i2)
println(i1 + i2)
```
"""
function forward(sender::Tuple{Type,Symbol}, receiver::Type, method::Method;
withtypes=true, allargs=true)
function newmethod(sender_type, sender_symb, argid, method, withtypes, allargs)
s = "p" .* string.(1:method.nargs-1)
(withtypes) && (s .*= "::" .* string.(fieldtype.(Ref(method.sig), 2:method.nargs)))
s[argid] .= "p" .* string.(argid) .* "::$sender_type"
if !allargs
s = s[1:argid[end]]
push!(s, "args...")
end
# Module where the method is defined
ff = fieldtype(method.sig, 1)
if isabstracttype(ff)
# costructors
m = string(method.module)
# m = string(method.module.eval(:(parentmodule($(method.name))))) # Constructor
else
# all methods except constructors
m = string(parentmodule(ff))
end
m *= "."
l = "$m:(" * string(method.name) * ")(" * join(s,", ") * "; kw..."
m = string(method.module) * "."
l *= ") = $m:(" * string(method.name) * ")("
s = "p" .* string.(1:method.nargs-1)
if !allargs
s = s[1:argid[end]]
push!(s, "args...")
end
s[argid] .= "getfield(" .* s[argid] .* ", :$sender_symb)"
l *= join(s, ", ") * "; kw...)"
l = join(split(l, "#"))
return l
end
@assert isstructtype(sender[1])
@assert sender[2] in fieldnames(sender[1])
sender_type = string(parentmodule(sender[1])) * "." * string(nameof(sender[1]))
sender_symb = string(sender[2])
code = Vector{String}()
# Search for receiver type in method arguments
foundat = Vector{Int}()
for i in 2:method.nargs
argtype = fieldtype(method.sig, i)
(sender[1] == argtype) && (return code)
if argtype != Any
(typeintersect(receiver, argtype) != Union{}) && (push!(foundat, i-1))
end
end
(length(foundat) == 0) && (return code)
if string(method.name)[1] == '@'
@warn "Forwarding macros is not yet supported." # TODO
display(method)
println()
return code
end
for ii in combinations(foundat)
push!(code, newmethod(sender_type, sender_symb, ii, method, withtypes, allargs))
end
tmp = split(string(method.module), ".")[1]
code = "@eval " .* tmp .* " " .* code .*
" # " .* string(method.file) .* ":" .* string(method.line)
if (tmp != "Base") &&
(tmp != "Main")
pushfirst!(code, "using $tmp")
end
code = unique(code)
return code
end
"""
`forward(sender::Tuple{Type,Symbol}, receiver::Type; super=true, kw...)`
"""
function forward(sender::Tuple{Type,Symbol}, receiver::Type; kw...)
code = Vector{String}()
for m in methodswith(receiver, supertypes=true)
append!(code, forward(sender, receiver, m; kw...))
end
return unique(code)
end
"""
`@forward(sender, receiver, ekws...)`
Evaluate the Julia code to forward methods. The syntax is exactly the same as the `forward` function.
# Example:
```julia-repl
julia> struct Book
title::String
author::String
end
julia> Base.show(io::IO, b::Book) = println(io, "\$(b.title) (by \$(b.author))")
julia> Base.print(b::Book) = println("In a hole in the ground there lived a hobbit...")
julia> author(b::Book) = b.author
julia> struct PaperBook
b::Book
number_of_pages::Int
end
julia> @forward((PaperBook, :b), Book)
julia> pages(book::PaperBook) = book.number_of_pages
julia> struct Edition
b::PaperBook
year::Int
end
julia> @forward((Edition, :b), PaperBook)
julia> year(book::Edition) = book.year
julia> book = Edition(PaperBook(Book("The Hobbit", "J.R.R. Tolkien"), 374), 2013)
julia> print(author(book), ", ", pages(book), " pages, Ed. ", year(book))
J.R.R. Tolkien, 374 pages, Ed. 2013
julia> print(book)
In a hole in the ground there lived a hobbit...
```
"""
macro forward(sender, receiver, ekws...)
kws = Vector{Pair{Symbol,Any}}()
for kw in ekws
if isa(kw, Expr) && (kw.head == :(=))
push!(kws, Pair(kw.args[1], kw.args[2]))
else
error("The @forward macro requires two arguments and (optionally) the same keywords accepted by forward()")
end
end
out = quote
counterr = 0
mylist = forward($sender, $receiver; $kws...)
for line in mylist
try
eval(Meta.parse("$line"))
catch err
global counterr += 1
println()
println("$line")
@error err;
end
end
if counterr > 0
println(counterr, " method(s) raised an error")
end
end
return esc(out)
end
"""
`@copy_fields T`
Copy all field definitions from a structure into another.
# Example
```julia-repl
julia> struct First
field1
field2::Int
end
julia> struct Second
@copy_fields(First)
field3::String
end
julia> println(fieldnames(Second))
(:field1, :filed2, :field3)
julia> println(fieldtype.(Second, fieldnames(Second)))
(Any, Int64, String)
```
"""
macro copy_fields(T)
out = Expr(:block)
for name in fieldnames(__module__.eval(T))
e = Expr(Symbol("::"))
push!(e.args, name)
push!(e.args, fieldtype(__module__.eval(T), name))
push!(out.args, e)
end
return esc(out)
end
# New methods for the following functions will be implemented when the @quasiabstract macro is invoked
"""
`concretetype(T::Type)`
Return the concrete type associated with the *quasi abstract* type `T`. If `T` is not *quasi abstract* returns nothing.
See also: `@quasiabstract`
"""
concretetype(T::Type) = nothing
"""
`isquasiabstract(T::Type)`
Return `true` if `T` is *quasi abstract*, `false` otherwise.
See also: `@quasiabstract`
"""
isquasiabstract(T::Type) = false
"""
`isquasiconcrete(T::Type)`
Return `true` if `T` is a concrete type associated to a *quasi abstract* type, `false` otherwise.
See also: `@quasiabstract`
"""
isquasiconcrete(T::Type) = false
"""
`@quasiabstract expression`
Create a *quasi abstract* type.
This macro accepts an expression defining a (mutable or immutable) structure, and outputs the code for two new type definitions:
- an abstract type with the same name and (if given) supertype of the input structure;
- a concrete structure definition with name prefix `Concrete_`, subtyping the abstract type defined above.
The relation between the types ensure there will be a single concrete type associated to the abstract one, hence you can use the abstract type to annotate method arguments, and be sure to receive the associated concrete type, or one of its subtypes (which shares all field names and types of the ancestors).
The concrete type associated to an *quasi abstract* type can be retrieved with the `concretetype` function. The `Concrete_` prefix can be customized passing a second symbol argument to the macro.
These newly defined types allows to easily implement concrete subtyping: simply use the *quasi abstract* type name for both object construction and to annotate method arguments.
# Example:
```julia-repl
julia> @quasiabstract struct Book
title::String
author::String
end
julia> Base.show(io::IO, b::Book) = println(io, "\$(b.title) (by \$(b.author))")
julia> Base.print(b::Book) = println("In a hole in the ground there lived a hobbit...")
julia> author(b::Book) = b.author
julia> @quasiabstract struct PaperBook <: Book
number_of_pages::Int
end
julia> pages(book::PaperBook) = book.number_of_pages
julia> @quasiabstract struct Edition <: PaperBook
year::Int
end
julia> year(book::Edition) = book.year
julia> println(fieldnames(concretetype(Edition)))
(:title, :author, :number_of_pages, :year)
julia> book = Edition("The Hobbit", "J.R.R. Tolkien", 374, 2013)
julia> print(author(book), ", ", pages(book), " pages, Ed. ", year(book))
J.R.R. Tolkien, 374 pages, Ed. 2013
julia> print(book)
In a hole in the ground there lived a hobbit...
julia> @assert isquasiconcrete(typeof(book))
julia> @assert isquasiabstract(supertype(typeof(book)))
julia> @assert concretetype(supertype(typeof(book))) === typeof(book)
```
"""
macro quasiabstract(expr, prefix::Symbol=:Concrete_)
function change_symbol!(expr, from::Symbol, to::Symbol)
if isa(expr, Expr)
for i in 1:length(expr.args)
if isa(expr.args[i], Symbol) && (expr.args[i] == from)
expr.args[1] = to
else
if isa(expr.args[i], Expr)
change_symbol!(expr.args[i], from, to)
end
end
end
end
end
drop_parameter_types(expr::Symbol) = expr
function drop_parameter_types(_aaa::Expr)
aaa = deepcopy(_aaa)
for ii in 1:length(aaa.args)
if isa(aaa.args[ii], Expr) && (aaa.args[ii].head == :<:)
insert!(aaa.args, ii, aaa.args[ii].args[1])
deleteat!(aaa.args, ii+1)
end
end
return aaa
end
function prepare_where(expr::Expr, orig::Expr)
@assert expr.head == :curly
whereclause = Expr(:where)
push!(whereclause.args, orig)
for i in 2:length(expr.args)
@assert (isa(expr.args[i], Symbol) || (isa(expr.args[i], Expr) && (expr.args[i].head == :<:)))
push!(whereclause.args, expr.args[i])
end
return whereclause
end
@assert isa(expr, Expr)
@assert expr.head == :struct "Expression must be a `struct`"
# Ensure there is room for the super type in the expression
if isa(expr.args[2], Symbol)
name = deepcopy(expr.args[2])
deleteat!(expr.args, 2)
insert!(expr.args, 2, Expr(:<:, name, :Any))
end
if isa(expr.args[2], Expr) && (expr.args[2].head != :<:)
insert!(expr.args, 2, Expr(:<:, expr.args[2], :Any))
deleteat!(expr.args, 3)
end
@assert isa(expr.args[2], Expr)
@assert expr.args[2].head == :<:
# Get name and super type
tmp = expr.args[2].args[1]
@assert (isa(tmp, Symbol) || (isa(tmp, Expr) && (tmp.head == :curly)))
name = deepcopy(tmp)
name_symb = (isa(tmp, Symbol) ? tmp : tmp.args[1])
tmp = expr.args[2].args[2]
@assert (isa(tmp, Symbol) || (isa(tmp, Expr) && ((tmp.head == :curly) || (tmp.head == :(.)))))
super = deepcopy(tmp)
super_symb = ((isa(tmp, Expr) && (tmp.head == :curly)) ? tmp.args[1] : tmp)
# Output abstract type
out = Expr(:block)
push!(out.args, :(abstract type $name <: $super end))
# Change name in input expression
concrete_symb = Symbol(prefix, name_symb)
if isa(name, Symbol)
concrete = concrete_symb
else
concrete = deepcopy(name)
change_symbol!(concrete, name_symb, concrete_symb)
end
change_symbol!(expr, name_symb, concrete_symb)
# Drop all types from parameters in `name`, or they'll raise syntax errors
name = drop_parameter_types(name)
# Change super type in input expression to actual name
deleteat!(expr.args[2].args, 2)
insert!( expr.args[2].args, 2, name)
# If an ancestor type is quasi abstract retrieve the associated
# concrete type and add its fields as members
p = __module__.eval(super_symb)
while (p != Any)
if isquasiabstract(p)
parent = concretetype(p)
for i in fieldcount(parent):-1:1
e = Expr(Symbol("::"))
push!(e.args, fieldname(parent, i))
push!(e.args, fieldtype(parent, i))
pushfirst!(expr.args[3].args, e)
end
break
end
p = __module__.eval(supertype(p))
end
# Add modified input structure to output
push!(out.args, expr)
# Add a constructor whose name is the same as the abstract type
if isa(name, Expr)
whereclause = prepare_where(name, :($name(args...; kw...)))
push!(out.args, :($whereclause = $concrete(args...; kw...)))
else
push!(out.args, :($name(args...; kw...) = $concrete(args...; kw...)))
end
# Add `concretetype`, `isquasiabstract` and `isquasiconcrete` methods
push!(out.args, :(ReusePatterns.concretetype(::Type{$name_symb}) = $concrete_symb))
push!(out.args, :(ReusePatterns.isquasiabstract(::Type{$name_symb}) = true))
push!(out.args, :(ReusePatterns.isquasiconcrete(::Type{$concrete_symb}) = true))
if isa(name, Expr)
whereclause = prepare_where(name, :(ReusePatterns.concretetype(::Type{$name})))
push!(out.args, :($whereclause = $concrete))
whereclause = prepare_where(name, :(ReusePatterns.isquasiabstract(::Type{$name})))
push!(out.args, :($whereclause = true))
# Drop all types from parameters in `concrete`, or they'll raise syntax errors
concrete = drop_parameter_types(concrete)
whereclause = prepare_where(name, :(ReusePatterns.isquasiconcrete(::Type{$concrete})))
push!(out.args, :($whereclause = true))
end
return esc(out)
end
end # module
| ReusePatterns | https://github.com/gcalderone/ReusePatterns.jl.git |
|
[
"MIT"
] | 0.3.1 | 1467be4e01897dae9b5c739643d2de0d790d25e0 | code | 4148 | using ReusePatterns
using Test
@quasiabstract struct Rectangle1
width::Real
height::Real
end
@quasiabstract struct Rectangle2{T<:Real}
width::T
height::T
end
@quasiabstract struct Rectangle3{T} <: Number
width::T
height::T
end
@quasiabstract struct Rectangle4{T<:Real} <: Number
width::T
height::T
end
@quasiabstract struct Box1 <: Rectangle1
depth::Real
end
@quasiabstract struct Box2{T<:Real} <: Rectangle2{T}
depth::T
end
@quasiabstract struct Box3{T} <: Rectangle3{T}
depth::T
end
@quasiabstract struct Box4{T<:Real} <: Rectangle4{T}
depth::T
end
#_____________________________________________________________________
# Alice's code
#
using Statistics, ReusePatterns
abstract type AbstractPolygon end
@quasiabstract mutable struct Polygon <: AbstractPolygon
x::Vector{Float64}
y::Vector{Float64}
end
# Retrieve the number of vertices, and their X and Y coordinates
vertices(p::Polygon) = length(p.x)
coords_x(p::Polygon) = p.x
coords_y(p::Polygon) = p.y
# Move, scale and rotate a polygon
function move!(p::Polygon, dx::Real, dy::Real)
p.x .+= dx
p.y .+= dy
end
function scale!(p::Polygon, scale::Real)
m = mean(p.x); p.x = (p.x .- m) .* scale .+ m
m = mean(p.y); p.y = (p.y .- m) .* scale .+ m
end
function rotate!(p::Polygon, angle_deg::Real)
θ = float(angle_deg) * pi / 180
R = [cos(θ) -sin(θ); sin(θ) cos(θ)]
x = p.x .- mean(p.x)
y = p.y .- mean(p.y)
(x, y) = R * [x, y]
p.x = x .+ mean(p.x)
p.y = y .+ mean(p.y)
end
#_____________________________________________________________________
# Bob's code
#
@quasiabstract mutable struct RegularPolygon <: Polygon
radius::Float64
end
function RegularPolygon(n::Integer, radius::Real)
@assert n >= 3
θ = range(0, stop=2pi-(2pi/n), length=n)
c = radius .* exp.(im .* θ)
return RegularPolygon(real(c), imag(c), radius)
end
# Compute length of a side and the polygon area
side(p::RegularPolygon) = 2 * p.radius * sin(pi / vertices(p))
area(p::RegularPolygon) = side(p)^2 * vertices(p) / 4 / tan(pi / vertices(p))
function scale!(p::RegularPolygon, scale::Real)
invoke(scale!, Tuple{supertype(RegularPolygon), typeof(scale)}, p, scale) # call "super" method
p.radius *= scale # update internal state
end
# Attach a label to a polygon
mutable struct Named{T} <: AbstractPolygon
polygon::T
name::String
end
Named{T}(name, args...; kw...) where T = Named{T}(T(args...; kw...), name)
name(p::Named) = p.name
# Forward methods from `Named` to `Polygon`
@forward (Named, :polygon) RegularPolygon
#_____________________________________________________________________
# Charlie's code
#
# Here I use `Gnuplot.jl`, but any other package would work...
#=
using Gnuplot
Gnuplot.setverb(false)
@gp "set size ratio -1" "set grid" "set key bottom right" xr=(-1.5, 2.5) :-
=#
# Methods to plot a Polygon
plotlabel(p::Polygon) = "Polygon (" * string(length(p.x)) * " vert.)"
plotlabel(p::RegularPolygon) = "RegularPolygon (" * string(vertices(p)) * " vert., area=" * string(round(area(p) * 100) / 100) * ")"
plotlabel(p::Named) = name(p) * " (" * string(vertices(p)) * " vert., area=" * string(round(area(p) * 100) / 100) * ")"
function plot(p::AbstractPolygon; dt=1, color="black")
x = coords_x(p); x = [x; x[1]]
y = coords_y(p); y = [y; y[1]]
title = plotlabel(p)
# @gp :- x y "w l tit '$title' dt $dt lw 2 lc rgb '$color'"
end
# Finally, let's have fun with the shapes!
line = Polygon([0., 1.], [0., 1.])
triangle = RegularPolygon(3, 1)
square = Named{RegularPolygon}("Square", 4, 1)
plot(line, color="black")
plot(triangle, color="blue")
plot(square, color="red")
rotate!(triangle, 90)
move!(triangle, 1, 1)
scale!(triangle, 0.32)
scale!(square, sqrt(2))
plot(triangle, color="blue", dt=2)
plot(square, color="red", dt=2)
# Increase number of vertices
p = Named{RegularPolygon}("Heptagon", 7, 1)
plot(p, color="orange", dt=4)
circle = Named{RegularPolygon}("Circle", 1000, 1)
plot(circle, color="dark-green", dt=4)
| ReusePatterns | https://github.com/gcalderone/ReusePatterns.jl.git |
|
[
"MIT"
] | 0.3.1 | 1467be4e01897dae9b5c739643d2de0d790d25e0 | docs | 18891 | # ReusePatterns.jl
## Simple tools to implement *composition* and *concrete subtyping* patterns in Julia.
[](https://travis-ci.org/gcalderone/ReusePatterns.jl)
### Warning
The **ReusePatterns.jl** package provides an implementation for the concepts described below, namely method forwarding and concrete subtyping, to pursue code reusing in the Julia language. However the approaches suggested here are essentially workarounds, i.e. they work perfectly in most cases, but may not work as expected in some corner case. A more fundamental tool, possibly built-in into the language, is required to solve the problem in all cases (a recent discussion is available [here](https://discourse.julialang.org/t/dataframes-jl-metadata/84544/94), see also the links at the end of this page).
As a consequence, this package **is no longer** actively maintained, and will be updated only occasionally.
**Use it at your own risk!**
______
Assume an author **A** (say, Alice) wrote a very powerful Julia code, extensively used by user **C** (say, Charlie). The best code reusing practice in this "two actors" scenario is the package deployment, thoroughly discussed in the Julia manual. Now assume a third person **B** (say, Bob) slips between Alice and Charlie: he wish to reuse Alice's code to provide more complex/extended functionalities to Charlie. Most likely Bob will need a more sophisticated reuse pattern...
This package provides a few tools to facilitate Bob's work in reusing Alice's code, by mean of two of the most common reuse patterns: *composition* and *subtyping* ([implementation inheritance](https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)) is not supported in Julia), and check which one provides the best solution. Also, it aims to relieve Charlie from dealing with the underlying details, and seamlessly use the new functionalities introduced by Bob.
The motivation to develop this package stems from the following posts on the Discourse:
- https://discourse.julialang.org/t/how-to-add-metadata-info-to-a-dataframe/11168
- https://discourse.julialang.org/t/composition-and-inheritance-the-julian-way/11231
but several other topics apply as well (see list in the *Links* section below).
## Installation
Latest version of **ReusePatterns.jl** is 0.3.1, which you may install with:
```julia
] add ReusePatterns
```
## Composition
With [composition](https://en.wikipedia.org/wiki/Object_composition) we wrap an Alice's object into a structure implemented by Bob, and let Charlie use the latter without even knowing if it actually is the original Alice's object, or the wrapped one by Bob.
We pursue this goal by automatically forwarding all methods calls from Bob's structure to the appropriate Alice's object.
### Example:
Alice implemented a code to keep track of all her books, but forgot to add room for the number of pages and the issue year of each book. Bob wishes to add these informations, and to provide the final functionalities to Charlie:
```julia
# ##### Alice's code #####
julia> struct Book
title::String
author::String
end
julia> Base.show(io::IO, b::Book) = println(io, "$(b.title) (by $(b.author))")
julia> Base.print(b::Book) = println("In a hole in the ground there lived a hobbit...")
julia> author(b::Book) = b.author
# ##### Bob's code #####
julia> using ReusePatterns
julia> struct PaperBook
b::Book
number_of_pages::Int
end
julia> @forward((PaperBook, :b), Book)
julia> pages(book::PaperBook) = book.number_of_pages
julia> struct Edition
b::PaperBook
year::Int
end
julia> @forward((Edition, :b), PaperBook)
julia> year(book::Edition) = book.year
# ##### Charlie's code #####
julia> book = Edition(PaperBook(Book("The Hobbit", "J.R.R. Tolkien"), 374), 2013)
julia> print(author(book), ", ", pages(book), " pages, Ed. ", year(book))
J.R.R. Tolkien, 374 pages, Ed. 2013
julia> print(book)
In a hole in the ground there lived a hobbit...
```
The key lines here are:
```julia
@forward((PaperBook, :b), Book)
@forward((Edition, :b), PaperBook)
```
The `@forward` macro identifies all methods accepting a `Book` object, and defines new methods with the same name and arguments, but accepting `PaperBook` arguments in place of the `Book` ones. The purpose of each newly defined method is simply to forward the call to the original method, passing the `Book` object stored in the `:p` field. The second line does the same job, forwarding calls from `Edition` objects to `PaperBook` ones.
The **ReusePatterns.jl** package exports the following functions and macros aimed at supporting *composition* in Julia:
- `@forward`: forward method calls from an object to a field structure;
- `forward`: returns a `Vector{String}` with the Julia code to properly forward method calls.
To preview the forwarding code without actually evaluating it you can use the `forward` function, which has the same syntax as the `@forward` macro. Continuing from previous example:
```
julia> println.(sort(forward((Edition, :b), PaperBook)));
@eval Main Base.:(print)(p1::Main.Edition; kw...) = Main.:(print)(getfield(p1, :b); kw...) # none:1
@eval Main Base.:(show)(p1::IO, p2::Main.Edition; kw...) = Main.:(show)(p1, getfield(p2, :b); kw...) # none:1
@eval Main Main.:(Edition)(p1::Main.Edition, p2::Int64; kw...) = Main.:(Edition)(getfield(p1, :b), p2; kw...) # REPL[10]:2
@eval Main Main.:(PaperBook)(p1::Main.Edition, p2::Int64; kw...) = Main.:(PaperBook)(getfield(p1, :b), p2; kw...) # none:1
@eval Main Main.:(author)(p1::Main.Edition; kw...) = Main.:(author)(getfield(p1, :b); kw...) # none:1
@eval Main Main.:(pages)(p1::Main.Edition; kw...) = Main.:(pages)(getfield(p1, :b); kw...) # REPL[9]:1
```
Each function and macro has its own online documentation accessible by prepending `?` to the name.
The *composition* approach has the following advantages:
- It is applicable even if Alice and Bob do not agree on a particular type architecture;
- it is the recommended Julian way to pursue code reusing;
...and disadvantages:
- It may be cumbersome to apply if the number of involved methods is very high, or if the method definitions are spread across many modules;
- *composition* is not recursive, i.e. if further users (**D**an, **E**mily, etc.) build composite layers on top of Bob's one they'll need to implement new forwarding methods;
- It may introduces tiny overheads for each composition layer, resulting in performance loss.
**NOTE:** The `@forward` has been tested and successfully used on many types defined in the Julia package ecosystem. However there may be corner cases where it fails to identify the proper methods to forward. In this case the best option is to have a look to the output of the `forward()` function for the methods which are automatically identified, and manually add the missing ones.
## Concrete subtyping
Julia supports [subtyping](https://en.wikipedia.org/wiki/Subtyping) of abstract types, allowing to build type hierarchies where each node represents, for any given *function*, a desired behaviour for the node itself, and a fall back behaviour for all its subtypes. This is one of the most powerful feature in Julia: in a function argument you may require an *AbstractArray* and seamlessly work with any of its concrete implementations (e.g. dense, strided or sparse arrays, ranges, etc.). This mechanism actually stem from a **rigid separation** of the desired behavior for a type (represented by the abstract type and the [interface](https://docs.julialang.org/en/v1/manual/interfaces) definition) and the actual machine implementation (represented by the concrete type and the interface implementations).
However, in Julia you can only subtype abstract types, hence this powerful substitutability mechanism can not be pushed beyond a concrete type. Citing the [manual](https://docs.julialang.org/en/v1/manual/types): *this [limitation] might at first seem unduly restrictive, [but] it has many beneficial consequences with surprisingly few drawbacks.*
The most striking drawback pops out in case Alice defines an abstract type with only one subtype, namely a concrete one. Clearly, in all methods requiring access to the actual data representation, the argument types will be annotated with the concrete type, not the abstract one. This is an important protection against Alice's package misuse: those methods require **exactly** that concrete type, not something else, even if it is a subtype of the same parent abstract type. However, this is a serious problem for Bob, since he can not reuse those methods even if he defines concrete structures with the same contents as Alice's one (plus something else).
The **ReusePatterns.jl** package allows to overtake this limitation by introducing the concept of *quasi-abstract* type, i.e. an abstract type without a rigid separation between a type behaviour and its concrete implementation. Operatively, a *quasi-abstract* type is an abstract type satisfying the following constraints:
1 - it can have as many abstract or *quasi-abstract* subtypes as desired, but it can have **only one** concrete subtype (the so called *associated concrete type*);
2 - if a *quasi-abstract* type has another *quasi-abstract* type among its ancestors, its associated concrete type must have (at least) the same field names and types of the ancestor associated data structure.
Note that for the example discussed above constraint 1 is not an actual limitation, since Alice already defined only one concrete type. Also note that constraint 2 implies *concrete structure subtyping*.
The `@quasiabstract` macro provided by the **ReusePatterns.jl** package, ensure the above constraints are properly satisfied.
The guidelines to exploit *quasi-abstract* types are straightforward:
- define the *quasi-abstract* type as a simple structure, possibly with a parent type;
- use the *quasi-abstract* type name for object creation, method argument annotations, etc.
Finally note that although two types are actually defined under the hood (an abstract one and an associated concrete one), you may simply forget about the concrete one, and safely use the abstract one everywhere in the code.
### Example:
As for the *composition* case discussed above, assume alice implemented a code to keep track of all her books, but forgot to add room for the number of pages and the issue year of each book. Bob wishes to add these informations, and to provide the final functionalities to Charlie.
```julia
# ##### Alice's code #####
julia> @quasiabstract struct Book
title::String
author::String
end
julia> Base.show(io::IO, b::Book) = println(io, "$(b.title) (by $(b.author))")
julia> Base.print(b::Book) = println("In a hole in the ground there lived a hobbit...")
julia> author(b::Book) = b.author
# ##### Bob's code #####
julia> using ReusePatterns
julia> @quasiabstract struct PaperBook <: Book
number_of_pages::Int
end
julia> pages(book::PaperBook) = book.number_of_pages
julia> @quasiabstract struct Edition <: PaperBook
year::Int
end
julia> year(book::Edition) = book.year
julia> println(fieldnames(concretetype(Edition)))
(:title, :author, :number_of_pages, :year)
# ##### Charlie's code #####
julia> book = Edition("The Hobbit", "J.R.R. Tolkien", 374, 2013)
julia> print(author(book), ", ", pages(book), " pages, Ed. ", year(book))
J.R.R. Tolkien, 374 pages, Ed. 2013
julia> print(book)
In a hole in the ground there lived a hobbit...
```
The **ReusePatterns.jl** package exports the following functions and macros aimed at supporting *concrete subtyping* in Julia:
- `@quasiabstract`: define a new *quasi-abstract* type, i.e. a pair of an abstract and an exclusively associated concrete types;
- `concretetype`: return the concrete type associated to a *quasi-abstract* type;
- `isquasiabstract`: test whether a type is *quasi-abstract*;
- `isquasiconcrete`: test whether a type is the concrete type associated to a *quasi-abstract* type.
Continuing the previous example:
```julia
julia> isquasiconcrete(typeof(book))
true
julia> isquasiabstract(supertype(typeof(book)))
true
julia> concretetype(supertype(typeof(book))) === typeof(book)
true
```
Each function and macro has its own online documentation accessible by prepending `?` to the name.
This *concrete subtyping* approach has the following advantages:
- It is a recursive approach, i.e. if further users (**D**an, **E**mily, etc.) subtype Bob's structure they will have all the inherited behavior for free;
- There is no overhead or performance loss.
...and disadvantages:
- it is applicable **only if** both Alice and Bob agree to use *quasi-abstract* types;
- Charlie may break Alice's or Bob's code by using a concrete type with the *quasi-abstract* type as ancestor, but without the required fields. However, this problem can be easily fixed by adding the following check to the methods accepting a *quasi-abstract* type, e.g. in the `pages` method shown above:
```julia
function pages(book::PaperBook)
@assert isquasiconcrete(typeof(book))
book.number_of_pages
end
```
Note also that `isquasiconcrete` is a pure function, hence it can be used as a trait.
## Complete examples
### Adding metadata to a `DataFrame` object
This [topic](https://discourse.julialang.org/t/how-to-add-metadata-info-to-a-dataframe/11168) raised a long discussion about the possibility to extend the functionalities provided by the [DataFrames](https://github.com/JuliaData/DataFrames.jl) package by adding a simple metadata dictionary, and the approaches to follow. With the *composition* tools provided by **ReusePatterns.jl** this problem can now be solved with just 8 lines of code:
```julia
using DataFrames, ReusePatterns
struct DataFrameMeta <: AbstractDataFrame
p::DataFrame
meta::Dict{String, Any}
DataFrameMeta(args...; kw...) = new(DataFrame(args...; kw...), Dict{Symbol, Any}())
end
meta(d::DataFrameMeta) = getfield(d,:meta) # <-- new functionality added to DataFrameMeta
@forward((DataFrameMeta, :p), DataFrame) # <-- reuse all existing DataFrame functionalities
```
(see the complete example [here](https://github.com/gcalderone/ReusePatterns.jl/blob/master/examples/dataframes.jl)).
### Polygon drawings (a comparison of the *composition* and *concrete subtyping* approaches)
We will consider the problem of implementing the code to draw several polygons on a plot.
The objects and methods implemented by Alice are:
- `Polygon`: a structure to store the 2D cartesian coordinates of a **generic polygon**;
- `vertices`, `coords_x` and `coords_y`: methods to retrieve the number of vertices and the X and Y coordinates;
- `move!`, `scale!` and `rotate!`: methods to move, scale and rotate a polygon.
The objects and methods implemented by Bob are:
- `RegularPolygon`: a structure including (in the *composition* case) or subtyping (in the *concrete subtyping* case) a `Polygon` object, and represeting a **regular polygon**;
- `side`, `area`: methods to caluclate the length of a side and the area of a regular polygon;
- `Named`: a generic wrapper for an object (either a `Polygon`, or `RegularPolygon`), providing the possibility to attach a label for plotting purposes.
Finally, Charlie's code will:
- Instantiate several regular polygons;
- Move, scale and rotate them;
- and produce the final plot.
The same problem has been implemented following both the *composition* and the *concrete subtype* approaches in order to highlight the differences. Also, each approach has been implemented both with and without **ReusePatterns.jl** facilities, in order to clearly show the code being generated by the macros.
The four complete examples are available here:
- [*composition*](https://github.com/gcalderone/ReusePatterns.jl/blob/master/examples/composition.jl) (without using **ReusePatterns.jl** facilities);
- [*composition*](https://github.com/gcalderone/ReusePatterns.jl/blob/master/examples/composition_wmacro.jl) (with **ReusePatterns.jl** facilities);
- [*concrete subtyping*](https://github.com/gcalderone/ReusePatterns.jl/blob/master/examples/subtyping.jl) (without using **ReusePatterns.jl** facilities);
- [*concrete subtyping*](https://github.com/gcalderone/ReusePatterns.jl/blob/master/examples/subtyping_wmacro.jl) (with **ReusePatterns.jl** facilities);
Note that in all files the common statements appears on the same line, in order to make clear how much code is being saved by the considered approaches. Finally, [Charlie's code](https://github.com/gcalderone/ReusePatterns.jl/blob/master/examples/charlie.jl) is identical for all of the above cases, and can be used to produce the final plot:

## Links
The above discussion reflects my personal view of how I understood code reusing patterns in Julia, and **ReusePatterns.jl** is just the framework I use to implement those patterns. But there is a lot of ongoing discussion on these topics, hence I encourage the reader to give a look around to see whether there are better solutions. Below, you will find a (non-exhaustive) list of the links I found very useful to develoip this package.
### Related topics on Discourse and other websites:
The topics mentioned here, or related ones, have been thorougly discussed in many places, e.g.:
- https://discourse.julialang.org/t/how-to-add-metadata-info-to-a-dataframe/11168
- https://discourse.julialang.org/t/composition-and-inheritance-the-julian-way/11231
- https://discourse.julialang.org/t/workaround-for-traditional-inheritance-features-in-object-oriented-languages/1195
- https://github.com/mauro3/SimpleTraits.jl
- http://www.stochasticlifestyle.com/type-dispatch-design-post-object-oriented-programming-julia/
- https://discourse.julialang.org/t/why-doesnt-julia-allow-multiple-inheritance/14342/4
- https://discourse.julialang.org/t/oop-in-julia-inherit-from-parametric-composite-type/1841/
- https://discourse.julialang.org/t/wrap-and-inherit-number/4799
- https://discourse.julialang.org/t/guidelines-to-distinguish-concrete-from-abstract-types/19162
### Pacakges providing similar functionalities:
Also, there are several packages related to the code reuse topic, or which provide similar functionalities as **ReusePatterns.jl** (in no particolar order):
- https://github.com/WschW/StructuralInheritance.jl
- https://github.com/JeffreySarnoff/TypedDelegation.jl
- https://github.com/AleMorales/ModularTypes.jl
- https://github.com/JuliaCollections/DataStructures.jl/blob/master/src/delegate.jl
- https://github.com/rjplevin/Classes.jl
- https://github.com/jasonmorton/Typeclass.jl
- https://github.com/KlausC/TypeEmulator.jl
- https://github.com/MikeInnes/Lazy.jl (`@forward` macro)
- https://github.com/tbreloff/ConcreteAbstractions.jl
| ReusePatterns | https://github.com/gcalderone/ReusePatterns.jl.git |
|
[
"MIT"
] | 0.1.0 | 5fbd28f4de5d850d07adb040790b240190c706dd | code | 533 | module SignalTemporalLogic
const STL = SignalTemporalLogic
export
STL,
¬,
∧,
∨,
⟹,
Formula,
Interval,
eventually,
always,
Atomic,
⊤,
⊥,
Predicate,
FlippedPredicate,
Negation,
Conjunction,
Disjunction,
Implication,
Biconditional,
Eventually,
Always,
Until,
ρ,
ρ̃,
robustness,
smooth_robustness,
TemporalOperator,
smoothmin,
smoothmax,
get_interval,
∇ρ,
∇ρ̃,
@formula
include("stl.jl")
end # module
| SignalTemporalLogic | https://github.com/sisl/SignalTemporalLogic.jl.git |
|
[
"MIT"
] | 0.1.0 | 5fbd28f4de5d850d07adb040790b240190c706dd | code | 38904 | ### A Pluto.jl notebook ###
# v0.19.29
using Markdown
using InteractiveUtils
# ╔═╡ 9adccf3d-1b74-4abb-87c4-cb066c65b3b6
using Zygote
# ╔═╡ 8be19ab0-6d8c-11ec-0e32-fb14ef6c2970
md"""
# Signal Temporal Logic
This notebook defines all of the code for the `SignalTemporalLogic.jl` package.
"""
# ╔═╡ a5d51b71-3685-4e1f-a4be-374623e3702b
md"""
## Propositional Logic
"""
# ╔═╡ ad439cdd-8d94-4c9f-8519-aa4077d11c8e
begin
¬ = ! # \neg
∧(a,b) = a && b # \wedge
∨(a,b) = a || b # \vee
⟹(p,q) = ¬p ∨ q # \implies
⟺(p,q) = (p ⟹ q) ∧ (q ⟹ p) # \iff
end;
# ╔═╡ 3003c9d3-df19-45ba-a37a-3111f473cb1a
md"""
## Formulas
"""
# ╔═╡ 579f207a-7ad6-45de-b4f0-30062ec1c8af
abstract type Formula end
# ╔═╡ 331fa4f8-b02c-4c30-bcc5-4d09c9234f37
const Interval = Union{UnitRange, Missing}
# ╔═╡ bae83d07-50ec-4f03-bd84-36fc41fa44f0
md"""
## Eventually $\lozenge$
$$\lozenge_{[a,b]}\phi = \top \mathcal{U}_{[a,b]} \phi$$
```julia
◊(x, ϕ, I) = any(ϕ(x[i]) for i in I)
any(ϕ(x.[I]))
```
```julia
function eventually(ϕ, x, I=[1,length(x)])
T = xₜ->true
return 𝒰(T, ϕ, x, I)
end
```
"""
# ╔═╡ f0db9fff-59c8-439e-ba03-0a9fb09383a6
md"""
## Always $\square$
$$\square_{[a,b]}\phi = \neg\lozenge_{[a,b]}(\neg\phi)$$
```julia
all(ϕ(x[i]) for i in I)
```
```julia
function always(ϕ, x, I=[1,length(x)])
return ¬◊(¬ϕ, x, I)
end
```
```julia
□(ϕ, x, I=1:length(x)) = all(ϕ(x[t]) for t in I)
```
"""
# ╔═╡ 8c2a500b-8d62-48a3-ac22-b6466858eef9
md"""
## Combining STL formulas
"""
# ╔═╡ dc6bec3c-4ca0-457e-886d-0b2a3f8845e8
begin
∧(ϕ1::Formula, ϕ2::Formula) = xᵢ->ϕ1(xᵢ) ∧ ϕ2(xᵢ)
∨(ϕ1::Formula, ϕ2::Formula) = xᵢ->ϕ1(xᵢ) ∨ ϕ2(xᵢ)
end
# ╔═╡ 50e69922-f07e-48dd-981d-d68c8cd07f7f
md"""
# Robustness
The notion of _robustness_ is defined to be some _quantitative semantics_ (i.e., numerical meaning) that calculates the degree of satisfaction or violation a signal has for a given STL formula. Positive values indicate satisfaction, while negative values indicate violation.
The quantitative semantics of a formula with respect to a signal $x_t$ is defined as:
$$\begin{align}
\rho(x_t, \top) &= \rho_\text{max} \qquad \text{where } \rho_\text{max} > 0\\
\rho(x_t, \mu_c) &= \mu(x_t) - c\\
\rho(x_t, \neg\phi) &= -\rho(x_t, \phi)\\
\rho(x_t, \phi \wedge \psi) &= \min\Bigl(\rho(x_t, \phi), \rho(x_t, \psi)\Bigr)\\
\rho(x_t, \phi \vee \psi) &= \max\Bigl(\rho(x_t, \phi), \rho(x_t, \psi)\Bigr)\\
\rho(x_t, \phi \implies \psi) &= \max\Bigl(-\rho(x_t, \phi), \rho(x_t, \psi)\Bigr)\\
\rho(x_t, \lozenge_{[a,b]}\phi) &= \max_{t^\prime \in [t+a,t+b]} \rho(x_{t^\prime}, \phi)\\
\rho(x_t, \square_{[a,b]}\phi) &= \min_{t^\prime \in [t+a,t+b]} \rho(x_{t^\prime}, \phi)\\
\rho(x_t, \phi\mathcal{U}_{[a,b]}\psi) &= \max_{t^\prime \in [t+a,t+b]} \biggl(\min\Bigl(\rho(x_{t^\prime},\psi), \min_{t^{\prime\prime}\in[0,t^\prime]} \rho(x_{t^{\prime\prime}}, \phi)\Bigr)\biggr)
\end{align}$$
"""
# ╔═╡ 175946fd-9de7-4efb-811d-1b52d6444614
md"""
## Atomic Operator (Truth/False)
"""
# ╔═╡ a7af8bca-1870-4ce5-8cce-9d9d04604f31
md"""
$$\rho(x_t, \top) = \rho_\text{max} \qquad \text{where } \rho_\text{max} > 0$$
$$\rho(x_t, \bot) = -\rho_\text{max} \qquad \text{where } \rho_\text{max} > 0$$
"""
# ╔═╡ 851997de-b0f5-4273-a15b-0e1440c2e6cd
begin
Base.@kwdef struct Atomic <: Formula
value::Bool
ρ_bound = value ? Inf : -Inf
end
(ϕ::Atomic)(x) = ϕ.value
ρ(xₜ, ϕ::Atomic) = ϕ.ρ_bound
ρ̃(xₜ, ϕ::Atomic; kwargs...) = ρ(xₜ, ϕ)
end
# ╔═╡ 296c7321-db0d-4878-a4d9-6e2b6ee76e4e
md"""
## Predicate
"""
# ╔═╡ 0158daf7-bc8d-4764-81b1-b5e73e02dc8a
md"""
$$\rho(x_t, \mu_c) = \mu(x_t) - c \qquad (\text{when}\; \mu(x_t) > c)$$
"""
# ╔═╡ 1ec0bddb-28d8-420b-856d-2c1ed70a77a4
begin
mutable struct Predicate <: Formula
μ::Function # ℝⁿ → ℝ
c::Union{Real, Vector}
end
(ϕ::Predicate)(x) = map(xₜ->all(xₜ .> ϕ.c), ϕ.μ(x))
ρ(x, ϕ::Predicate) = map(xₜ->xₜ - ϕ.c, ϕ.μ(x))
ρ̃(x, ϕ::Predicate; kwargs...) = ρ(x, ϕ)
end
# ╔═╡ 5d2e634f-c483-4707-a53d-aa71e17dd3f5
md"""
$$\rho(x_t, \mu_c) = c - \mu(x_t) \qquad (\text{when}\; \mu(x_t) < c)$$
"""
# ╔═╡ 3ed8b19e-6518-40b6-9320-3ab01d03f8f6
begin
mutable struct FlippedPredicate <: Formula
μ::Function # ℝⁿ → ℝ
c::Union{Real, Vector}
end
(ϕ::FlippedPredicate)(x) = map(xₜ->all(xₜ .< ϕ.c), ϕ.μ(x))
ρ(x, ϕ::FlippedPredicate) = map(xₜ->ϕ.c - xₜ, ϕ.μ(x))
ρ̃(x, ϕ::FlippedPredicate; kwargs...) = ρ(x, ϕ)
end
# ╔═╡ 00189191-c0ec-41c2-85f0-f362c4b8bb69
md"""
## Negation
"""
# ╔═╡ 944e81cc-ef05-4541-bf04-441d2a59af0c
md"""
$$\rho(x_t, \neg\phi) = -\rho(x_t, \phi)$$
"""
# ╔═╡ 9e477ba3-9e0e-42ae-9fe2-97adc7ae8faa
begin
mutable struct Negation <: Formula
ϕ_inner::Formula
end
(ϕ::Negation)(x) = .¬ϕ.ϕ_inner(x)
ρ(xₜ, ϕ::Negation) = -ρ(xₜ, ϕ.ϕ_inner)
ρ̃(xₜ, ϕ::Negation; kwargs...) = -ρ̃(xₜ, ϕ.ϕ_inner; kwargs...)
end
# ╔═╡ 94cb97f7-ddc0-4ab3-bf90-9e38d2a19de0
md"""
## Conjunction
"""
# ╔═╡ b04f0e12-06a0-4955-add4-ae3dcbb5c25a
md"""
$$\rho(x_t, \phi \wedge \psi) = \min\Bigl(\rho(x_t, \phi), \rho(x_t, \psi)\Bigr)$$
"""
# ╔═╡ e75cafd9-1d30-496e-82d5-f7b353036d81
md"""
## Disjunction
"""
# ╔═╡ 8330f2e8-c6a5-45ac-a812-ffc358f06ea6
md"""
$$\rho(x_t, \phi \vee \psi) = \max\Bigl(\rho(x_t, \phi), \rho(x_t, \psi)\Bigr)$$
"""
# ╔═╡ f45fbd6d-f02b-44ca-a846-f8f8792e7c32
md"""
## Implication
"""
# ╔═╡ 413d8927-cae0-4425-ab2b-f22cac074ac6
md"""
$$\rho(x_t, \phi \implies \psi) = \max\Bigl(-\rho(x_t, \phi), \rho(x_t, \psi)\Bigr)$$
"""
# ╔═╡ 4ec409ed-24cd-4b23-93aa-34da33644289
md"""
## Biconditional
"""
# ╔═╡ a0653887-537c-4792-acfc-4849b79d6970
md"""
$$\rho(x_t, \phi \iff \psi) = \rho\bigl(x_t, (\phi \implies \psi) \wedge (\psi \implies \phi)\bigr)$$
"""
# ╔═╡ acbe9641-ac0b-43c6-9cb2-2aea65efb431
md"""
## Eventually
"""
# ╔═╡ 3829b9dc-bbba-48aa-9e95-996589886bfa
md"""
$$\rho(x_t, \lozenge_{[a,b]}\phi) = \max_{t^\prime \in [t+a,t+b]} \rho(x_{t^\prime}, \phi)$$
"""
# ╔═╡ baed163f-b9f6-4c34-9432-529c683ae43e
get_interval(ϕ::Formula, x) = ismissing(ϕ.I) ? (1:length(x)) : ϕ.I
# ╔═╡ 15870045-7238-4e75-9aea-3d6824e21bbe
md"""
## Always
"""
# ╔═╡ 069b6736-bc83-4a9b-8319-bcb6dedadcc6
md"""
$$\rho(x_t, \square_{[a,b]}\phi) = \min_{t^\prime \in [t+a,t+b]} \rho(x_{t^\prime}, \phi)$$
"""
# ╔═╡ fef07e51-227b-4558-b8bd-aa33d7a6c8ce
md"""
## Until
"""
# ╔═╡ 31589b2c-e0ad-478a-9a51-c18d83b67d07
md"""
$$\rho(x_t, \phi\mathcal{U}_{[a,b]}\psi) = \max_{t^\prime \in [t+a,t+b]} \biggl(\min\Bigl(\rho(x_{t^\prime},\psi), \min_{t^{\prime\prime}\in[0,t^\prime]} \rho(x_{t^{\prime\prime}}, \phi)\Bigr)\biggr)$$
"""
# ╔═╡ d72cffdc-60d9-4b0a-a787-89e2ba3ca858
md"""
# Minimum/maximum approximations
"""
# ╔═╡ ba0a977e-3dea-4b87-900d-d7e2e4281f79
global W = 1
# ╔═╡ 053e0902-559f-4ac9-98dc-4b59f11e4056
function logsumexp(x)
m = maximum(x)
return m + log(sum(exp(xᵢ - m) for xᵢ in x))
end
# ╔═╡ 4c07b312-8fa3-48bb-95e7-5005674265aa
md"""
## Smooth minimum
$$\widetilde{\min}(x; w) = \frac{\sum_i^n x_i \exp(-x_i/w)}{\sum_j^n \exp(-x_j/w)}$$
This approximates the $\min$ function and will return the true solution when $w = 0$ and will return the mean of $x$ when $w\to\infty$.
"""
# ╔═╡ 93539199-d2b4-450c-97d2-c1df2ed5cf51
function _smoothmin(x, w; stable=false)
if stable
xw = -x / w
e = exp.(xw .- logsumexp(xw)) # used for numerical stability
return sum(x .* e) / sum(e)
else
return sum(xᵢ*exp(-xᵢ/w) for xᵢ in x) / sum(exp(-xⱼ/w) for xⱼ in x)
end
end
# ╔═╡ 8c9c3777-30f9-4de2-b80d-cc05aaf21ea5
smoothmin(x; w=W) = w == 0 ? minimum(x) : _smoothmin(x, w)
# ╔═╡ f7c4d4a1-c3f4-4196-8a92-50294480555c
smoothmin(x1, x2; w=W) = smoothmin([x1,x2]; w=w)
# ╔═╡ c93b2ad2-1b5c-490e-b7fc-9fc0495fe6fa
begin
mutable struct Conjunction <: Formula
ϕ::Formula
ψ::Formula
end
(q::Conjunction)(x) = all(q.ϕ(x) .∧ q.ψ(x))
ρ(xₜ, q::Conjunction) = min.(ρ(xₜ, q.ϕ), ρ(xₜ, q.ψ))
ρ̃(xₜ, q::Conjunction; w=W) = smoothmin.(ρ̃(xₜ, q.ϕ), ρ̃(xₜ, q.ψ); w)
end
# ╔═╡ 967af87a-d0d7-42ea-871d-492d9406f9c6
begin
mutable struct Always <: Formula
ϕ::Formula
I::Interval
end
(□::Always)(x) = all(□.ϕ(x[t]) for t ∈ get_interval(□, x))
ρ(x, □::Always) = minimum(ρ(x[t′], □.ϕ) for t′ ∈ get_interval(□, x))
ρ̃(x, □::Always; w=W) = smoothmin(ρ̃(x[t′], □.ϕ; w) for t′ ∈ get_interval(□, x); w)
end
# ╔═╡ 980379f9-3544-4363-aa6c-595d0c509124
md"""
## Smooth maximum
$$\widetilde{\max}(x; w) = \frac{\sum_i^n x_i \exp(x_i/w)}{\sum_j^n \exp(x_j/w)}$$
"""
# ╔═╡ b9118811-80aa-4984-8f84-779a89aa94bc
function _smoothmax(x, w; stable=false)
if stable
xw = x / w
e = exp.(xw .- logsumexp(xw)) # used for numerical stability
return sum(x .* e) / sum(e)
else
return sum(xᵢ*exp(xᵢ/w) for xᵢ in x) / sum(exp(xⱼ/w) for xⱼ in x)
end
end
# ╔═╡ 0bbd170b-ef3d-4a4a-99f7-df6cfd16dcc6
smoothmax(x; w=W) = w == 0 ? maximum(x) : _smoothmax(x, w)
# ╔═╡ e5e59d1d-f6ec-4bde-90fe-4715b15239a2
smoothmax(x1, x2; w=W) = smoothmax([x1,x2]; w=w)
# ╔═╡ e4df40fb-dc10-421c-9cab-39ebfc73b320
begin
mutable struct Disjunction <: Formula
ϕ::Formula
ψ::Formula
end
(q::Disjunction)(x) = any(q.ϕ(x) .∨ q.ψ(x))
ρ(xₜ, q::Disjunction) = max.(ρ(xₜ, q.ϕ), ρ(xₜ, q.ψ))
ρ̃(xₜ, q::Disjunction; w=W) = smoothmax.(ρ̃(xₜ, q.ϕ; w), ρ̃(xₜ, q.ψ; w); w)
end
# ╔═╡ b0b10df8-07f0-4317-8f3a-3620a3cb8e8e
begin
mutable struct Implication <: Formula
ϕ::Formula
ψ::Formula
end
(q::Implication)(x) = q.ϕ(x) .⟹ q.ψ(x)
ρ(xₜ, q::Implication) = max.(-ρ(xₜ, q.ϕ), ρ(xₜ, q.ψ))
ρ̃(xₜ, q::Implication; w=W) = smoothmax.(-ρ̃(xₜ, q.ϕ; w), ρ̃(xₜ, q.ψ; w); w)
end
# ╔═╡ f1f170a8-2902-41f7-8c21-99c90d752459
begin
mutable struct Biconditional <: Formula
ϕ::Formula
ψ::Formula
end
(q::Biconditional)(x) = q.ϕ(x) .⟺ q.ψ(x)
ρ(xₜ, q::Biconditional) =
ρ(xₜ, Conjunction(Implication(q.ϕ, q.ψ), Implication(q.ψ, q.ϕ)))
ρ̃(xₜ, q::Biconditional; w=W) =
ρ̃(xₜ, Conjunction(Implication(q.ϕ, q.ψ), Implication(q.ψ, q.ϕ)); w)
end
# ╔═╡ d2e95e25-f1df-4807-bc41-fb7ebb7a3d55
begin
mutable struct Eventually <: Formula
ϕ::Formula
I::Interval
end
(◊::Eventually)(x) = any(◊.ϕ(x[t]) for t ∈ get_interval(◊, x))
ρ(x, ◊::Eventually) = maximum(ρ(x[t′], ◊.ϕ) for t′ ∈ get_interval(◊, x))
ρ̃(x, ◊::Eventually; w=W) = smoothmax(ρ̃(x[t′], ◊.ϕ; w) for t′∈get_interval(◊,x); w)
end
# ╔═╡ b12507a8-1a50-4e88-9271-1fa5413c93a8
begin
mutable struct Until <: Formula
ϕ::Formula
ψ::Formula
I::Interval
end
function (𝒰::Until)(x)
ϕ, ψ, I = 𝒰.ϕ, 𝒰.ψ, get_interval(𝒰, x)
return any(ψ(x[i]) && all(ϕ(x[j]) for j ∈ I[1]:i-1) for i ∈ I)
end
function ρ(x, 𝒰::Until)
ϕ, ψ, I = 𝒰.ϕ, 𝒰.ψ, get_interval(𝒰, x)
return maximum(map(I) do t′
ρ1 = ρ(x[t′], ψ)
ρ2_trace = [ρ(x[t′′], ϕ) for t′′ ∈ 1:t′-1]
ρ2 = isempty(ρ2_trace) ? 10e100 : minimum(ρ2_trace)
min(ρ1, ρ2)
end)
end
function ρ̃(x, 𝒰::Until; w=W)
ϕ, ψ, I = 𝒰.ϕ, 𝒰.ψ, get_interval(𝒰, x)
return smoothmax(map(I) do t′
ρ̃1 = ρ̃(x[t′], ψ; w)
ρ̃2_trace = [ρ̃(x[t′′], ϕ; w) for t′′ ∈ 1:t′-1]
ρ̃2 = isempty(ρ̃2_trace) ? 10e100 : smoothmin(ρ̃2_trace; w)
smoothmin([ρ̃1, ρ̃2]; w)
end; w)
end
end
# ╔═╡ d57941cf-655b-45f8-b5e2-b39d3cfeb9fb
robustness(xₜ, ϕ::Formula; w=0) = w == 0 ? ρ(xₜ, ϕ) : ρ̃(xₜ, ϕ; w)
# ╔═╡ 5c1e16b3-1b3c-4c7a-a484-44b935eaa2a9
smooth_robustness = ρ̃
# ╔═╡ ef7fc726-3a27-463b-8c40-4eb549d983be
const TemporalOperator = Union{Eventually, Always, Until}
# ╔═╡ 182aa82d-302a-4719-9ec2-b8df937acb7b
md"""
# Gradients
"""
# ╔═╡ 80787178-e17d-4066-8544-609a4ed76613
∇ρ(x, ϕ) = first(jacobian(x->ρ(x, ϕ), x))
# ╔═╡ f5b37004-f30b-4a59-8aab-ecc775e856b3
∇ρ̃(x, ϕ; kwargs...) = first(jacobian(x->ρ̃(x, ϕ; kwargs...), x))
# ╔═╡ 067dadb1-1312-4035-930c-65b1068f7013
md"""
# Robustness helpers
"""
# ╔═╡ 2dae8ed0-3bd6-44e1-a762-a75b5cc9f9f0
is_conjunction(head) = head ∈ [:(&&), :∧]
# ╔═╡ 7bc35b0b-fdbe-46d2-83c1-0c056772761e
is_disjunction(head) = head ∈ [:(||), :∨]
# ╔═╡ 512f0bdc-7e4c-4a01-ae68-adbd57d63cb0
is_junction(head) = is_conjunction(head) || is_disjunction(head)
# ╔═╡ 4bba7170-e7b7-4ccf-b6f4-a32b7ee4b809
function split_lambda(λ)
var, body = λ.args
if body.head == :block
body = body.args[1]
end
return var, body
end
# ╔═╡ 15dc4645-b08e-4a5a-a65d-1858b948f324
function split_predicate(ϕ)
var, body = split_lambda(ϕ)
μ_body, c = body.args[2:3]
μ = Expr(:(->), var, μ_body)
return μ, c
end
# ╔═╡ b90947cb-2cbe-4410-abbe-4869b5caa313
function strip_negation(ϕ)
if ϕ.head == :call
# negation outside lambda definition ¬(x->x)
return ϕ.args[2]
else
var, body = split_lambda(ϕ)
formula = body.args[end]
if formula.args[1] ∈ [:(¬), :(!)]
inner = formula.args[end]
else
inner = formula
end
return Expr(:(->), var, inner)
end
end
# ╔═╡ 982ac681-79a0-4c69-a5cc-0546a5ebd3be
function split_junction(ϕ_ψ)
if ϕ_ψ.head == :(->)
var = ϕ_ψ.args[1]
head = ϕ_ψ.args[2].args[1].head
ϕ = Expr(:(->), var, ϕ_ψ.args[2].args[1].args[1])
ψ = Expr(:(->), var, ϕ_ψ.args[2].args[1].args[2])
else
head = ϕ_ψ.head
ϕ, ψ = ϕ_ψ.args[end-1:end]
end
return ϕ, ψ, head
end
# ╔═╡ 84effb59-b744-4bd7-b724-6f3e4056a737
function split_interval(interval_ex)
interval = eval(interval_ex)
a, b = first(interval), last(interval)
a, b = ceil(Int, a), floor(Int, b)
I = a:b
return I
end
# ╔═╡ 78f8ce9c-9563-4ea1-89fc-c5c65ce4bb29
function split_temporal(temporal_ϕ)
if length(temporal_ϕ.args) == 3
interval_ex = temporal_ϕ.args[2]
I = split_interval(interval_ex)
ϕ_ex = temporal_ϕ.args[3]
else
I = missing
ϕ_ex = temporal_ϕ.args[2]
end
return (ϕ_ex, I)
end
# ╔═╡ 460bba5d-ebac-46b1-80fc-72fe845046a7
function split_until(until)
if length(until.args) == 4
interval_ex = until.args[2]
I = split_interval(interval_ex)
ϕ_ex, ψ_ex = until.args[3:4]
else
I = missing
ϕ_ex, ψ_ex = until.args[2:3]
end
return (ϕ_ex, ψ_ex, I)
end
# ╔═╡ e44e21ed-36f6-4d2c-82bd-fa1575cc49f8
function parse_formula(ex)
ex = Base.remove_linenums!(ex)
if ex isa Formula
return ex
elseif ex isa Symbol
local sym = string(ex)
return quote
error("Symbol `$($sym)` needs to be a Formula type.")
end
elseif is_junction(ex.head)
return parse_junction(ex)
else
var, body = ex.args
body = Base.remove_linenums!(body)
if var ∈ [:◊, :□]
ϕ_ex, I = split_temporal(ex)
ϕ = parse_formula(ϕ_ex)
if var == :◊
return :(Eventually($ϕ, $I))
elseif var == :□
return :(Always($ϕ, $I))
end
elseif var == :𝒰
ϕ_ex, ψ_ex, I = split_until(ex)
ϕ = parse_formula(ϕ_ex)
ψ = parse_formula(ψ_ex)
return :(Until($ϕ, $ψ, $I))
else
core = body.head == :block ? body.args[end] : body
if typeof(core) == Bool
return :(Atomic(value=$(esc(core))))
else
if is_junction(core.head)
return parse_junction(ex)
elseif var ∈ (:⟺, :(==), :(!=), :⟹) || is_junction(var)
ϕ_ex, ψ_ex, _ = split_junction(ex)
ϕ = parse_formula(ϕ_ex)
ψ = parse_formula(ψ_ex)
if var ∈ [:⟺, :(==)]
return :(Biconditional($ϕ, $ψ))
elseif var == :(!=)
return :(Negation(Biconditional($ϕ, $ψ)))
elseif var == :⟹
return :(Implication($ϕ, $ψ))
elseif is_conjunction(var)
return :(Conjunction($ϕ, $ψ))
elseif is_disjunction(var)
return :(Disjunction($ϕ, $ψ))
end
elseif var ∈ [:¬, :!]
ϕ_inner = parse_formula(strip_negation(ex))
return :(Negation($ϕ_inner))
else
formula_type = core.args[1]
if formula_type ∈ [:¬, :!]
ϕ_inner = parse_formula(strip_negation(ex))
return :(Negation($ϕ_inner))
elseif formula_type == :>
μ, c = split_predicate(ex)
return :(Predicate($(esc(μ)), $c))
elseif formula_type == :<
μ, c = split_predicate(ex)
return :(FlippedPredicate($(esc(μ)), $c))
elseif formula_type ∈ [:⟺, :(==)]
μ, c = split_predicate(ex)
return :(Conjunction(Negation(Predicate($(esc(μ)), $c)), Negation(FlippedPredicate($(esc(μ)), $c))))
elseif formula_type == :(!=)
μ, c = split_predicate(ex)
return :(Disjunction(FlippedPredicate($(esc(μ)), $c), Predicate($(esc(μ)), $c)))
elseif is_junction(formula_type)
return parse_junction(ex)
else
error("""
No formula parser for:
formula_type = $(formula_type)
var = $var
core = $core
core.head = $(core.head)
core.args = $(core.args)
body = $body
ex = $ex""")
end
end
end
end
end
end
# ╔═╡ 97adec7a-75fd-40b1-9e46-e302c1dd6b9e
macro formula(ex)
return parse_formula(ex)
end
# ╔═╡ 7b96179d-1a55-42b4-a934-74b57a1d0cc6
eventually = @formula 𝒰(xₜ->true, xₜ -> xₜ > 0) # alternate derived form
# ╔═╡ 5c454ece-de05-4cce-9996-037df54024e5
always = @formula ¬◊(¬(xₜ -> xₜ > 0))
# ╔═╡ 916d7fae-6599-41c6-b909-4e1dd66e48f1
⊤ = @formula xₜ -> true
# ╔═╡ c1e17481-91c3-430f-99f3-1b328ec31417
⊥ = @formula xₜ -> false
# ╔═╡ 40603feb-ebd6-47c6-97c4-c27b5211ff9e
function parse_junction(ex)
ϕ_ex, ψ_ex, head = split_junction(ex)
ϕ = parse_formula(ϕ_ex)
ψ = parse_formula(ψ_ex)
if is_conjunction(head)
return :(Conjunction($ϕ, $ψ))
elseif is_disjunction(head)
return :(Disjunction($ϕ, $ψ))
else
error("No junction head for $(head).")
end
end
# ╔═╡ ca6b2f11-e0ef-404b-b487-584bd52fe936
Broadcast.broadcastable(ϕ::Formula) = Ref(ϕ)
# ╔═╡ e16f2079-f028-46c6-b4e7-bf23fe9dcbfb
md"""
# Notebook
"""
# ╔═╡ c66d8ffa-44d0-4550-9456-870aae5db796
IS_NOTEBOOK = @isdefined PlutoRunner
# ╔═╡ eeabb14a-7ca8-4446-b3d6-39a41b5b452c
if IS_NOTEBOOK
using PlutoUI
end
# ╔═╡ 210d23f1-2374-4511-a012-852f1f2dc3be
IS_NOTEBOOK && TableOfContents()
# ╔═╡ 00000000-0000-0000-0000-000000000001
PLUTO_PROJECT_TOML_CONTENTS = """
[deps]
PlutoUI = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
Zygote = "e88e6eb3-aa80-5325-afca-941959d7151f"
[compat]
PlutoUI = "~0.7.54"
Zygote = "~0.6.67"
"""
# ╔═╡ 00000000-0000-0000-0000-000000000002
PLUTO_MANIFEST_TOML_CONTENTS = """
# This file is machine-generated - editing it directly is not advised
julia_version = "1.9.2"
manifest_format = "2.0"
project_hash = "b812503fc48fba4e7cb474f0de7cda4f60f8f461"
[[deps.AbstractFFTs]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "d92ad398961a3ed262d8bf04a1a2b8340f915fef"
uuid = "621f4979-c628-5d54-868e-fcf4e3e8185c"
version = "1.5.0"
weakdeps = ["ChainRulesCore", "Test"]
[deps.AbstractFFTs.extensions]
AbstractFFTsChainRulesCoreExt = "ChainRulesCore"
AbstractFFTsTestExt = "Test"
[[deps.AbstractPlutoDingetjes]]
deps = ["Pkg"]
git-tree-sha1 = "559826a2e9fe0c4434982e0fc72b675fda8028f9"
uuid = "6e696c72-6542-2067-7265-42206c756150"
version = "1.2.1"
[[deps.Adapt]]
deps = ["LinearAlgebra", "Requires"]
git-tree-sha1 = "02f731463748db57cc2ebfbd9fbc9ce8280d3433"
uuid = "79e6a3ab-5dfb-504d-930d-738a2a938a0e"
version = "3.7.1"
[deps.Adapt.extensions]
AdaptStaticArraysExt = "StaticArrays"
[deps.Adapt.weakdeps]
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.ArgTools]]
uuid = "0dad84c5-d112-42e6-8d28-ef12dabb789f"
version = "1.1.1"
[[deps.Artifacts]]
uuid = "56f22d72-fd6d-98f1-02f0-08ddc0907c33"
[[deps.Base64]]
uuid = "2a0f44e3-6c83-55bd-87e4-b1978d98bd5f"
[[deps.CEnum]]
git-tree-sha1 = "eb4cb44a499229b3b8426dcfb5dd85333951ff90"
uuid = "fa961155-64e5-5f13-b03f-caf6b980ea82"
version = "0.4.2"
[[deps.ChainRules]]
deps = ["Adapt", "ChainRulesCore", "Compat", "Distributed", "GPUArraysCore", "IrrationalConstants", "LinearAlgebra", "Random", "RealDot", "SparseArrays", "SparseInverseSubset", "Statistics", "StructArrays", "SuiteSparse"]
git-tree-sha1 = "006cc7170be3e0fa02ccac6d4164a1eee1fc8c27"
uuid = "082447d4-558c-5d27-93f4-14fc19e9eca2"
version = "1.58.0"
[[deps.ChainRulesCore]]
deps = ["Compat", "LinearAlgebra"]
git-tree-sha1 = "e0af648f0692ec1691b5d094b8724ba1346281cf"
uuid = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
version = "1.18.0"
weakdeps = ["SparseArrays"]
[deps.ChainRulesCore.extensions]
ChainRulesCoreSparseArraysExt = "SparseArrays"
[[deps.ColorTypes]]
deps = ["FixedPointNumbers", "Random"]
git-tree-sha1 = "eb7f0f8307f71fac7c606984ea5fb2817275d6e4"
uuid = "3da002f7-5984-5a60-b8a6-cbb66c0b333f"
version = "0.11.4"
[[deps.CommonSubexpressions]]
deps = ["MacroTools", "Test"]
git-tree-sha1 = "7b8a93dba8af7e3b42fecabf646260105ac373f7"
uuid = "bbf7d656-a473-5ed7-a52c-81e309532950"
version = "0.3.0"
[[deps.Compat]]
deps = ["UUIDs"]
git-tree-sha1 = "8a62af3e248a8c4bad6b32cbbe663ae02275e32c"
uuid = "34da2185-b29b-5c13-b0c7-acf172513d20"
version = "4.10.0"
weakdeps = ["Dates", "LinearAlgebra"]
[deps.Compat.extensions]
CompatLinearAlgebraExt = "LinearAlgebra"
[[deps.CompilerSupportLibraries_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "e66e0078-7015-5450-92f7-15fbd957f2ae"
version = "1.0.5+0"
[[deps.ConstructionBase]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "c53fc348ca4d40d7b371e71fd52251839080cbc9"
uuid = "187b0558-2788-49d3-abe0-74a17ed4e7c9"
version = "1.5.4"
[deps.ConstructionBase.extensions]
ConstructionBaseIntervalSetsExt = "IntervalSets"
ConstructionBaseStaticArraysExt = "StaticArrays"
[deps.ConstructionBase.weakdeps]
IntervalSets = "8197267c-284f-5f27-9208-e0e47529a953"
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.DataAPI]]
git-tree-sha1 = "8da84edb865b0b5b0100c0666a9bc9a0b71c553c"
uuid = "9a962f9c-6df0-11e9-0e5d-c546b8b5ee8a"
version = "1.15.0"
[[deps.DataValueInterfaces]]
git-tree-sha1 = "bfc1187b79289637fa0ef6d4436ebdfe6905cbd6"
uuid = "e2d170a0-9d28-54be-80f0-106bbe20a464"
version = "1.0.0"
[[deps.Dates]]
deps = ["Printf"]
uuid = "ade2ca70-3891-5945-98fb-dc099432e06a"
[[deps.DiffResults]]
deps = ["StaticArraysCore"]
git-tree-sha1 = "782dd5f4561f5d267313f23853baaaa4c52ea621"
uuid = "163ba53b-c6d8-5494-b064-1a9d43ac40c5"
version = "1.1.0"
[[deps.DiffRules]]
deps = ["IrrationalConstants", "LogExpFunctions", "NaNMath", "Random", "SpecialFunctions"]
git-tree-sha1 = "23163d55f885173722d1e4cf0f6110cdbaf7e272"
uuid = "b552c78f-8df3-52c6-915a-8e097449b14b"
version = "1.15.1"
[[deps.Distributed]]
deps = ["Random", "Serialization", "Sockets"]
uuid = "8ba89e20-285c-5b6f-9357-94700520ee1b"
[[deps.DocStringExtensions]]
deps = ["LibGit2"]
git-tree-sha1 = "2fb1e02f2b635d0845df5d7c167fec4dd739b00d"
uuid = "ffbed154-4ef7-542d-bbb7-c09d3a79fcae"
version = "0.9.3"
[[deps.Downloads]]
deps = ["ArgTools", "FileWatching", "LibCURL", "NetworkOptions"]
uuid = "f43a241f-c20a-4ad4-852c-f6b1247861c6"
version = "1.6.0"
[[deps.FileWatching]]
uuid = "7b1f6079-737a-58dc-b8bc-7a2ca5c1b5ee"
[[deps.FillArrays]]
deps = ["LinearAlgebra", "Random"]
git-tree-sha1 = "35f0c0f345bff2c6d636f95fdb136323b5a796ef"
uuid = "1a297f60-69ca-5386-bcde-b61e274b549b"
version = "1.7.0"
weakdeps = ["SparseArrays", "Statistics"]
[deps.FillArrays.extensions]
FillArraysSparseArraysExt = "SparseArrays"
FillArraysStatisticsExt = "Statistics"
[[deps.FixedPointNumbers]]
deps = ["Statistics"]
git-tree-sha1 = "335bfdceacc84c5cdf16aadc768aa5ddfc5383cc"
uuid = "53c48c17-4a7d-5ca2-90c5-79b7896eea93"
version = "0.8.4"
[[deps.ForwardDiff]]
deps = ["CommonSubexpressions", "DiffResults", "DiffRules", "LinearAlgebra", "LogExpFunctions", "NaNMath", "Preferences", "Printf", "Random", "SpecialFunctions"]
git-tree-sha1 = "cf0fe81336da9fb90944683b8c41984b08793dad"
uuid = "f6369f11-7733-5829-9624-2563aa707210"
version = "0.10.36"
[deps.ForwardDiff.extensions]
ForwardDiffStaticArraysExt = "StaticArrays"
[deps.ForwardDiff.weakdeps]
StaticArrays = "90137ffa-7385-5640-81b9-e52037218182"
[[deps.GPUArrays]]
deps = ["Adapt", "GPUArraysCore", "LLVM", "LinearAlgebra", "Printf", "Random", "Reexport", "Serialization", "Statistics"]
git-tree-sha1 = "85d7fb51afb3def5dcb85ad31c3707795c8bccc1"
uuid = "0c68f7d7-f131-5f86-a1c3-88cf8149b2d7"
version = "9.1.0"
[[deps.GPUArraysCore]]
deps = ["Adapt"]
git-tree-sha1 = "2d6ca471a6c7b536127afccfa7564b5b39227fe0"
uuid = "46192b85-c4d5-4398-a991-12ede77f4527"
version = "0.1.5"
[[deps.Hyperscript]]
deps = ["Test"]
git-tree-sha1 = "8d511d5b81240fc8e6802386302675bdf47737b9"
uuid = "47d2ed2b-36de-50cf-bf87-49c2cf4b8b91"
version = "0.0.4"
[[deps.HypertextLiteral]]
deps = ["Tricks"]
git-tree-sha1 = "7134810b1afce04bbc1045ca1985fbe81ce17653"
uuid = "ac1192a8-f4b3-4bfe-ba22-af5b92cd3ab2"
version = "0.9.5"
[[deps.IOCapture]]
deps = ["Logging", "Random"]
git-tree-sha1 = "d75853a0bdbfb1ac815478bacd89cd27b550ace6"
uuid = "b5f81e59-6552-4d32-b1f0-c071b021bf89"
version = "0.2.3"
[[deps.IRTools]]
deps = ["InteractiveUtils", "MacroTools", "Test"]
git-tree-sha1 = "8aa91235360659ca7560db43a7d57541120aa31d"
uuid = "7869d1d1-7146-5819-86e3-90919afe41df"
version = "0.4.11"
[[deps.InteractiveUtils]]
deps = ["Markdown"]
uuid = "b77e0a4c-d291-57a0-90e8-8db25a27a240"
[[deps.IrrationalConstants]]
git-tree-sha1 = "630b497eafcc20001bba38a4651b327dcfc491d2"
uuid = "92d709cd-6900-40b7-9082-c6be49f344b6"
version = "0.2.2"
[[deps.IteratorInterfaceExtensions]]
git-tree-sha1 = "a3f24677c21f5bbe9d2a714f95dcd58337fb2856"
uuid = "82899510-4779-5014-852e-03e436cf321d"
version = "1.0.0"
[[deps.JLLWrappers]]
deps = ["Artifacts", "Preferences"]
git-tree-sha1 = "7e5d6779a1e09a36db2a7b6cff50942a0a7d0fca"
uuid = "692b3bcd-3c85-4b1f-b108-f13ce0eb3210"
version = "1.5.0"
[[deps.JSON]]
deps = ["Dates", "Mmap", "Parsers", "Unicode"]
git-tree-sha1 = "31e996f0a15c7b280ba9f76636b3ff9e2ae58c9a"
uuid = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
version = "0.21.4"
[[deps.LLVM]]
deps = ["CEnum", "LLVMExtra_jll", "Libdl", "Preferences", "Printf", "Requires", "Unicode"]
git-tree-sha1 = "c879e47398a7ab671c782e02b51a4456794a7fa3"
uuid = "929cbde3-209d-540e-8aea-75f648917ca0"
version = "6.4.0"
[deps.LLVM.extensions]
BFloat16sExt = "BFloat16s"
[deps.LLVM.weakdeps]
BFloat16s = "ab4f0b2a-ad5b-11e8-123f-65d77653426b"
[[deps.LLVMExtra_jll]]
deps = ["Artifacts", "JLLWrappers", "LazyArtifacts", "Libdl", "TOML"]
git-tree-sha1 = "98eaee04d96d973e79c25d49167668c5c8fb50e2"
uuid = "dad2f222-ce93-54a1-a47d-0025e8a3acab"
version = "0.0.27+1"
[[deps.LazyArtifacts]]
deps = ["Artifacts", "Pkg"]
uuid = "4af54fe1-eca0-43a8-85a7-787d91b784e3"
[[deps.LibCURL]]
deps = ["LibCURL_jll", "MozillaCACerts_jll"]
uuid = "b27032c2-a3e7-50c8-80cd-2d36dbcbfd21"
version = "0.6.3"
[[deps.LibCURL_jll]]
deps = ["Artifacts", "LibSSH2_jll", "Libdl", "MbedTLS_jll", "Zlib_jll", "nghttp2_jll"]
uuid = "deac9b47-8bc7-5906-a0fe-35ac56dc84c0"
version = "7.84.0+0"
[[deps.LibGit2]]
deps = ["Base64", "NetworkOptions", "Printf", "SHA"]
uuid = "76f85450-5226-5b5a-8eaa-529ad045b433"
[[deps.LibSSH2_jll]]
deps = ["Artifacts", "Libdl", "MbedTLS_jll"]
uuid = "29816b5a-b9ab-546f-933c-edad1886dfa8"
version = "1.10.2+0"
[[deps.Libdl]]
uuid = "8f399da3-3557-5675-b5ff-fb832c97cbdb"
[[deps.LinearAlgebra]]
deps = ["Libdl", "OpenBLAS_jll", "libblastrampoline_jll"]
uuid = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
[[deps.LogExpFunctions]]
deps = ["DocStringExtensions", "IrrationalConstants", "LinearAlgebra"]
git-tree-sha1 = "7d6dd4e9212aebaeed356de34ccf262a3cd415aa"
uuid = "2ab3a3ac-af41-5b50-aa03-7779005ae688"
version = "0.3.26"
[deps.LogExpFunctions.extensions]
LogExpFunctionsChainRulesCoreExt = "ChainRulesCore"
LogExpFunctionsChangesOfVariablesExt = "ChangesOfVariables"
LogExpFunctionsInverseFunctionsExt = "InverseFunctions"
[deps.LogExpFunctions.weakdeps]
ChainRulesCore = "d360d2e6-b24c-11e9-a2a3-2a2ae2dbcce4"
ChangesOfVariables = "9e997f8a-9a97-42d5-a9f1-ce6bfc15e2c0"
InverseFunctions = "3587e190-3f89-42d0-90ee-14403ec27112"
[[deps.Logging]]
uuid = "56ddb016-857b-54e1-b83d-db4d58db5568"
[[deps.MIMEs]]
git-tree-sha1 = "65f28ad4b594aebe22157d6fac869786a255b7eb"
uuid = "6c6e2e6c-3030-632d-7369-2d6c69616d65"
version = "0.1.4"
[[deps.MacroTools]]
deps = ["Markdown", "Random"]
git-tree-sha1 = "9ee1618cbf5240e6d4e0371d6f24065083f60c48"
uuid = "1914dd2f-81c6-5fcd-8719-6d5c9610ff09"
version = "0.5.11"
[[deps.Markdown]]
deps = ["Base64"]
uuid = "d6f4376e-aef5-505a-96c1-9c027394607a"
[[deps.MbedTLS_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "c8ffd9c3-330d-5841-b78e-0817d7145fa1"
version = "2.28.2+0"
[[deps.Mmap]]
uuid = "a63ad114-7e13-5084-954f-fe012c677804"
[[deps.MozillaCACerts_jll]]
uuid = "14a3606d-f60d-562e-9121-12d972cd8159"
version = "2022.10.11"
[[deps.NaNMath]]
deps = ["OpenLibm_jll"]
git-tree-sha1 = "0877504529a3e5c3343c6f8b4c0381e57e4387e4"
uuid = "77ba4419-2d1f-58cd-9bb1-8ffee604a2e3"
version = "1.0.2"
[[deps.NetworkOptions]]
uuid = "ca575930-c2e3-43a9-ace4-1e988b2c1908"
version = "1.2.0"
[[deps.OpenBLAS_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "Libdl"]
uuid = "4536629a-c528-5b80-bd46-f80d51c5b363"
version = "0.3.21+4"
[[deps.OpenLibm_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "05823500-19ac-5b8b-9628-191a04bc5112"
version = "0.8.1+0"
[[deps.OpenSpecFun_jll]]
deps = ["Artifacts", "CompilerSupportLibraries_jll", "JLLWrappers", "Libdl", "Pkg"]
git-tree-sha1 = "13652491f6856acfd2db29360e1bbcd4565d04f1"
uuid = "efe28fd5-8261-553b-a9e1-b2916fc3738e"
version = "0.5.5+0"
[[deps.OrderedCollections]]
git-tree-sha1 = "2e73fe17cac3c62ad1aebe70d44c963c3cfdc3e3"
uuid = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
version = "1.6.2"
[[deps.Parsers]]
deps = ["Dates", "PrecompileTools", "UUIDs"]
git-tree-sha1 = "a935806434c9d4c506ba941871b327b96d41f2bf"
uuid = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
version = "2.8.0"
[[deps.Pkg]]
deps = ["Artifacts", "Dates", "Downloads", "FileWatching", "LibGit2", "Libdl", "Logging", "Markdown", "Printf", "REPL", "Random", "SHA", "Serialization", "TOML", "Tar", "UUIDs", "p7zip_jll"]
uuid = "44cfe95a-1eb2-52ea-b672-e2afdf69b78f"
version = "1.9.2"
[[deps.PlutoUI]]
deps = ["AbstractPlutoDingetjes", "Base64", "ColorTypes", "Dates", "FixedPointNumbers", "Hyperscript", "HypertextLiteral", "IOCapture", "InteractiveUtils", "JSON", "Logging", "MIMEs", "Markdown", "Random", "Reexport", "URIs", "UUIDs"]
git-tree-sha1 = "bd7c69c7f7173097e7b5e1be07cee2b8b7447f51"
uuid = "7f904dfe-b85e-4ff6-b463-dae2292396a8"
version = "0.7.54"
[[deps.PrecompileTools]]
deps = ["Preferences"]
git-tree-sha1 = "03b4c25b43cb84cee5c90aa9b5ea0a78fd848d2f"
uuid = "aea7be01-6a6a-4083-8856-8a6e6704d82a"
version = "1.2.0"
[[deps.Preferences]]
deps = ["TOML"]
git-tree-sha1 = "00805cd429dcb4870060ff49ef443486c262e38e"
uuid = "21216c6a-2e73-6563-6e65-726566657250"
version = "1.4.1"
[[deps.Printf]]
deps = ["Unicode"]
uuid = "de0858da-6303-5e67-8744-51eddeeeb8d7"
[[deps.REPL]]
deps = ["InteractiveUtils", "Markdown", "Sockets", "Unicode"]
uuid = "3fa0cd96-eef1-5676-8a61-b3b8758bbffb"
[[deps.Random]]
deps = ["SHA", "Serialization"]
uuid = "9a3f8284-a2c9-5f02-9a11-845980a1fd5c"
[[deps.RealDot]]
deps = ["LinearAlgebra"]
git-tree-sha1 = "9f0a1b71baaf7650f4fa8a1d168c7fb6ee41f0c9"
uuid = "c1ae055f-0cd5-4b69-90a6-9a35b1a98df9"
version = "0.1.0"
[[deps.Reexport]]
git-tree-sha1 = "45e428421666073eab6f2da5c9d310d99bb12f9b"
uuid = "189a3867-3050-52da-a836-e630ba90ab69"
version = "1.2.2"
[[deps.Requires]]
deps = ["UUIDs"]
git-tree-sha1 = "838a3a4188e2ded87a4f9f184b4b0d78a1e91cb7"
uuid = "ae029012-a4dd-5104-9daa-d747884805df"
version = "1.3.0"
[[deps.SHA]]
uuid = "ea8e919c-243c-51af-8825-aaa63cd721ce"
version = "0.7.0"
[[deps.Serialization]]
uuid = "9e88b42a-f829-5b0c-bbe9-9e923198166b"
[[deps.Sockets]]
uuid = "6462fe0b-24de-5631-8697-dd941f90decc"
[[deps.SparseArrays]]
deps = ["Libdl", "LinearAlgebra", "Random", "Serialization", "SuiteSparse_jll"]
uuid = "2f01184e-e22b-5df5-ae63-d93ebab69eaf"
[[deps.SparseInverseSubset]]
deps = ["LinearAlgebra", "SparseArrays", "SuiteSparse"]
git-tree-sha1 = "91402087fd5d13b2d97e3ef29bbdf9d7859e678a"
uuid = "dc90abb0-5640-4711-901d-7e5b23a2fada"
version = "0.1.1"
[[deps.SpecialFunctions]]
deps = ["IrrationalConstants", "LogExpFunctions", "OpenLibm_jll", "OpenSpecFun_jll"]
git-tree-sha1 = "e2cfc4012a19088254b3950b85c3c1d8882d864d"
uuid = "276daf66-3868-5448-9aa4-cd146d93841b"
version = "2.3.1"
weakdeps = ["ChainRulesCore"]
[deps.SpecialFunctions.extensions]
SpecialFunctionsChainRulesCoreExt = "ChainRulesCore"
[[deps.StaticArraysCore]]
git-tree-sha1 = "36b3d696ce6366023a0ea192b4cd442268995a0d"
uuid = "1e83bf80-4336-4d27-bf5d-d5a4f845583c"
version = "1.4.2"
[[deps.Statistics]]
deps = ["LinearAlgebra", "SparseArrays"]
uuid = "10745b16-79ce-11e8-11f9-7d13ad32a3b2"
version = "1.9.0"
[[deps.StructArrays]]
deps = ["Adapt", "ConstructionBase", "DataAPI", "GPUArraysCore", "StaticArraysCore", "Tables"]
git-tree-sha1 = "0a3db38e4cce3c54fe7a71f831cd7b6194a54213"
uuid = "09ab397b-f2b6-538f-b94a-2f83cf4a842a"
version = "0.6.16"
[[deps.SuiteSparse]]
deps = ["Libdl", "LinearAlgebra", "Serialization", "SparseArrays"]
uuid = "4607b0f0-06f3-5cda-b6b1-a6196a1729e9"
[[deps.SuiteSparse_jll]]
deps = ["Artifacts", "Libdl", "Pkg", "libblastrampoline_jll"]
uuid = "bea87d4a-7f5b-5778-9afe-8cc45184846c"
version = "5.10.1+6"
[[deps.TOML]]
deps = ["Dates"]
uuid = "fa267f1f-6049-4f14-aa54-33bafae1ed76"
version = "1.0.3"
[[deps.TableTraits]]
deps = ["IteratorInterfaceExtensions"]
git-tree-sha1 = "c06b2f539df1c6efa794486abfb6ed2022561a39"
uuid = "3783bdb8-4a98-5b6b-af9a-565f29a5fe9c"
version = "1.0.1"
[[deps.Tables]]
deps = ["DataAPI", "DataValueInterfaces", "IteratorInterfaceExtensions", "LinearAlgebra", "OrderedCollections", "TableTraits"]
git-tree-sha1 = "cb76cf677714c095e535e3501ac7954732aeea2d"
uuid = "bd369af6-aec1-5ad0-b16a-f7cc5008161c"
version = "1.11.1"
[[deps.Tar]]
deps = ["ArgTools", "SHA"]
uuid = "a4e569a6-e804-4fa4-b0f3-eef7a1d5b13e"
version = "1.10.0"
[[deps.Test]]
deps = ["InteractiveUtils", "Logging", "Random", "Serialization"]
uuid = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
[[deps.Tricks]]
git-tree-sha1 = "eae1bb484cd63b36999ee58be2de6c178105112f"
uuid = "410a4b4d-49e4-4fbc-ab6d-cb71b17b3775"
version = "0.1.8"
[[deps.URIs]]
git-tree-sha1 = "67db6cc7b3821e19ebe75791a9dd19c9b1188f2b"
uuid = "5c2747f8-b7ea-4ff2-ba2e-563bfd36b1d4"
version = "1.5.1"
[[deps.UUIDs]]
deps = ["Random", "SHA"]
uuid = "cf7118a7-6976-5b1a-9a39-7adc72f591a4"
[[deps.Unicode]]
uuid = "4ec0a83e-493e-50e2-b9ac-8f72acf5a8f5"
[[deps.Zlib_jll]]
deps = ["Libdl"]
uuid = "83775a58-1f1d-513f-b197-d71354ab007a"
version = "1.2.13+0"
[[deps.Zygote]]
deps = ["AbstractFFTs", "ChainRules", "ChainRulesCore", "DiffRules", "Distributed", "FillArrays", "ForwardDiff", "GPUArrays", "GPUArraysCore", "IRTools", "InteractiveUtils", "LinearAlgebra", "LogExpFunctions", "MacroTools", "NaNMath", "PrecompileTools", "Random", "Requires", "SparseArrays", "SpecialFunctions", "Statistics", "ZygoteRules"]
git-tree-sha1 = "5ded212acd815612df112bb895ef3910c5a03f57"
uuid = "e88e6eb3-aa80-5325-afca-941959d7151f"
version = "0.6.67"
[deps.Zygote.extensions]
ZygoteColorsExt = "Colors"
ZygoteDistancesExt = "Distances"
ZygoteTrackerExt = "Tracker"
[deps.Zygote.weakdeps]
Colors = "5ae59095-9a9b-59fe-a467-6f913c188581"
Distances = "b4f34e82-e78d-54a5-968a-f98e89d6e8f7"
Tracker = "9f7883ad-71c0-57eb-9f7f-b5c9e6d3789c"
[[deps.ZygoteRules]]
deps = ["ChainRulesCore", "MacroTools"]
git-tree-sha1 = "9d749cd449fb448aeca4feee9a2f4186dbb5d184"
uuid = "700de1a5-db45-46bc-99cf-38207098b444"
version = "0.2.4"
[[deps.libblastrampoline_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850b90-86db-534c-a0d3-1478176c7d93"
version = "5.8.0+0"
[[deps.nghttp2_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "8e850ede-7688-5339-a07c-302acd2aaf8d"
version = "1.48.0+0"
[[deps.p7zip_jll]]
deps = ["Artifacts", "Libdl"]
uuid = "3f19e933-33d8-53b3-aaab-bd5110c3b7a0"
version = "17.4.0+0"
"""
# ╔═╡ Cell order:
# ╟─8be19ab0-6d8c-11ec-0e32-fb14ef6c2970
# ╠═210d23f1-2374-4511-a012-852f1f2dc3be
# ╟─a5d51b71-3685-4e1f-a4be-374623e3702b
# ╠═ad439cdd-8d94-4c9f-8519-aa4077d11c8e
# ╟─3003c9d3-df19-45ba-a37a-3111f473cb1a
# ╠═579f207a-7ad6-45de-b4f0-30062ec1c8af
# ╠═331fa4f8-b02c-4c30-bcc5-4d09c9234f37
# ╟─bae83d07-50ec-4f03-bd84-36fc41fa44f0
# ╠═7b96179d-1a55-42b4-a934-74b57a1d0cc6
# ╟─f0db9fff-59c8-439e-ba03-0a9fb09383a6
# ╠═5c454ece-de05-4cce-9996-037df54024e5
# ╟─8c2a500b-8d62-48a3-ac22-b6466858eef9
# ╠═dc6bec3c-4ca0-457e-886d-0b2a3f8845e8
# ╟─50e69922-f07e-48dd-981d-d68c8cd07f7f
# ╠═d57941cf-655b-45f8-b5e2-b39d3cfeb9fb
# ╠═5c1e16b3-1b3c-4c7a-a484-44b935eaa2a9
# ╟─175946fd-9de7-4efb-811d-1b52d6444614
# ╟─a7af8bca-1870-4ce5-8cce-9d9d04604f31
# ╠═851997de-b0f5-4273-a15b-0e1440c2e6cd
# ╠═916d7fae-6599-41c6-b909-4e1dd66e48f1
# ╠═c1e17481-91c3-430f-99f3-1b328ec31417
# ╟─296c7321-db0d-4878-a4d9-6e2b6ee76e4e
# ╟─0158daf7-bc8d-4764-81b1-b5e73e02dc8a
# ╠═1ec0bddb-28d8-420b-856d-2c1ed70a77a4
# ╟─5d2e634f-c483-4707-a53d-aa71e17dd3f5
# ╠═3ed8b19e-6518-40b6-9320-3ab01d03f8f6
# ╟─00189191-c0ec-41c2-85f0-f362c4b8bb69
# ╟─944e81cc-ef05-4541-bf04-441d2a59af0c
# ╠═9e477ba3-9e0e-42ae-9fe2-97adc7ae8faa
# ╟─94cb97f7-ddc0-4ab3-bf90-9e38d2a19de0
# ╟─b04f0e12-06a0-4955-add4-ae3dcbb5c25a
# ╠═c93b2ad2-1b5c-490e-b7fc-9fc0495fe6fa
# ╟─e75cafd9-1d30-496e-82d5-f7b353036d81
# ╟─8330f2e8-c6a5-45ac-a812-ffc358f06ea6
# ╠═e4df40fb-dc10-421c-9cab-39ebfc73b320
# ╟─f45fbd6d-f02b-44ca-a846-f8f8792e7c32
# ╟─413d8927-cae0-4425-ab2b-f22cac074ac6
# ╠═b0b10df8-07f0-4317-8f3a-3620a3cb8e8e
# ╟─4ec409ed-24cd-4b23-93aa-34da33644289
# ╟─a0653887-537c-4792-acfc-4849b79d6970
# ╠═f1f170a8-2902-41f7-8c21-99c90d752459
# ╟─acbe9641-ac0b-43c6-9cb2-2aea65efb431
# ╟─3829b9dc-bbba-48aa-9e95-996589886bfa
# ╠═ef7fc726-3a27-463b-8c40-4eb549d983be
# ╠═baed163f-b9f6-4c34-9432-529c683ae43e
# ╠═d2e95e25-f1df-4807-bc41-fb7ebb7a3d55
# ╟─15870045-7238-4e75-9aea-3d6824e21bbe
# ╟─069b6736-bc83-4a9b-8319-bcb6dedadcc6
# ╠═967af87a-d0d7-42ea-871d-492d9406f9c6
# ╟─fef07e51-227b-4558-b8bd-aa33d7a6c8ce
# ╟─31589b2c-e0ad-478a-9a51-c18d83b67d07
# ╠═b12507a8-1a50-4e88-9271-1fa5413c93a8
# ╟─d72cffdc-60d9-4b0a-a787-89e2ba3ca858
# ╠═ba0a977e-3dea-4b87-900d-d7e2e4281f79
# ╠═053e0902-559f-4ac9-98dc-4b59f11e4056
# ╟─4c07b312-8fa3-48bb-95e7-5005674265aa
# ╠═93539199-d2b4-450c-97d2-c1df2ed5cf51
# ╠═8c9c3777-30f9-4de2-b80d-cc05aaf21ea5
# ╠═f7c4d4a1-c3f4-4196-8a92-50294480555c
# ╟─980379f9-3544-4363-aa6c-595d0c509124
# ╠═b9118811-80aa-4984-8f84-779a89aa94bc
# ╠═0bbd170b-ef3d-4a4a-99f7-df6cfd16dcc6
# ╠═e5e59d1d-f6ec-4bde-90fe-4715b15239a2
# ╟─182aa82d-302a-4719-9ec2-b8df937acb7b
# ╠═9adccf3d-1b74-4abb-87c4-cb066c65b3b6
# ╠═80787178-e17d-4066-8544-609a4ed76613
# ╠═f5b37004-f30b-4a59-8aab-ecc775e856b3
# ╟─067dadb1-1312-4035-930c-65b1068f7013
# ╠═97adec7a-75fd-40b1-9e46-e302c1dd6b9e
# ╠═e44e21ed-36f6-4d2c-82bd-fa1575cc49f8
# ╠═2dae8ed0-3bd6-44e1-a762-a75b5cc9f9f0
# ╠═7bc35b0b-fdbe-46d2-83c1-0c056772761e
# ╠═512f0bdc-7e4c-4a01-ae68-adbd57d63cb0
# ╠═40603feb-ebd6-47c6-97c4-c27b5211ff9e
# ╠═4bba7170-e7b7-4ccf-b6f4-a32b7ee4b809
# ╠═15dc4645-b08e-4a5a-a65d-1858b948f324
# ╠═b90947cb-2cbe-4410-abbe-4869b5caa313
# ╠═982ac681-79a0-4c69-a5cc-0546a5ebd3be
# ╠═84effb59-b744-4bd7-b724-6f3e4056a737
# ╠═78f8ce9c-9563-4ea1-89fc-c5c65ce4bb29
# ╠═460bba5d-ebac-46b1-80fc-72fe845046a7
# ╠═ca6b2f11-e0ef-404b-b487-584bd52fe936
# ╟─e16f2079-f028-46c6-b4e7-bf23fe9dcbfb
# ╠═c66d8ffa-44d0-4550-9456-870aae5db796
# ╠═eeabb14a-7ca8-4446-b3d6-39a41b5b452c
# ╟─00000000-0000-0000-0000-000000000001
# ╟─00000000-0000-0000-0000-000000000002
| SignalTemporalLogic | https://github.com/sisl/SignalTemporalLogic.jl.git |
|
[
"MIT"
] | 0.1.0 | 5fbd28f4de5d850d07adb040790b240190c706dd | code | 25631 | ### A Pluto.jl notebook ###
# v0.19.29
using Markdown
using InteractiveUtils
# ╔═╡ 752d2f6b-a2bb-45bc-9fac-299f88d13f00
using Test
# ╔═╡ 39ceaac5-1084-44fa-9388-18593600eb11
using Plots; default(fontfamily="Computer Modern", framestyle=:box) # LaTex-style
# ╔═╡ e74099af-ea14-46d6-a61d-d71d176f5e45
using LaTeXStrings
# ╔═╡ ab57fd9b-9bec-48fc-8530-483a5d4ddb11
using Statistics
# ╔═╡ d06d3ce6-d13b-4ab6-bb66-8a07835e1ce7
using LinearAlgebra
# ╔═╡ d8a7facd-1ad8-413d-9037-054472fdc50f
md"""
# STL Formula Testing
"""
# ╔═╡ d383bf0a-3ff1-46d5-b285-63a803463bc0
x = [-0.25, 0, 0.1, 0.6, 0.75, 1.0]
# ╔═╡ c27ce933-8a2f-4384-bb3f-d843c1112740
t = 1
# ╔═╡ 0259067a-b538-4dd2-8665-d308273c1a21
md"""
## Truth
"""
# ╔═╡ 3846c63f-32e7-4f96-8e7a-ff62a5b5a21c
md"""
## Predicate
"""
# ╔═╡ 0398e51a-7c72-4fd9-8884-387ee256a9cb
md"""
## Negation
"""
# ╔═╡ 016fa961-5f8a-4993-9fdf-a0c2c8d3c540
md"""
## Conjunction
"""
# ╔═╡ 3e02651f-fffd-47d7-956d-5ba405ecbfaa
md"""
## Disjunction
"""
# ╔═╡ 74fabd52-861f-46dd-a509-cb10914ba332
md"""
## Implication
"""
# ╔═╡ e9cad561-10d3-48dd-ac13-090906b7c1e0
md"""
## Eventually
"""
# ╔═╡ d5fb1b62-574f-4025-9cf8-8e62e357f29f
md"""
## Always
"""
# ╔═╡ 00b37481-0a05-4f5a-a6d0-2fdddaa6ee97
md"""
## Until $\mathcal{U}$
> Note, Julia v1.8 will allow `∃` and `∀` as allowable identifiers.
$$\phi\;\mathcal{U}_{[a,b]}\;\psi$$
$\phi$ holds until $\psi$ holds, in interval $I=[a,b]$.
$$\exists i: \psi(x_i) \wedge \bigl(\forall j < i: \phi(x_j)\bigr)$$
"""
# ╔═╡ 1d0e135e-6cc3-422e-ba44-fee53cc1965f
μ(x) = x
# ╔═╡ 2305b206-0c6d-440d-81b7-0f485cc8a6a8
# U = @formula 𝒰(_ϕ, _ψ); NOTE: does not work like this.
# ╔═╡ 2d65db96-f8cf-4ccc-b4f5-1c642249ed7b
md"""
### Plotting Until
"""
# ╔═╡ ef4d7b05-d4b3-4498-9e5f-c26d9b47fb60
miss(ϕₓ) = map(v->v ? v : missing, ϕₓ)
# ╔═╡ d1c3412a-373b-47e2-b3d1-383d4ce1fa61
md"""
### More Until Testing
"""
# ╔═╡ 56d37e18-c978-4757-9ed4-e4bd412af310
x2 = [1, 2, 3, 4, -9, -8]
# ╔═╡ b30d0b1e-493b-48c0-b492-5f7dd2ad872b
md"""
# Extra Testing
"""
# ╔═╡ ce82cf55-0e32-412e-b6c6-f95563796e7e
md"""
## Combining STL Formulas
"""
# ╔═╡ ec6ff814-1179-4525-b138-094ca6bec408
md"""
## Satisfying an STL formula
The notation $x_t \in \phi$ denotes that signal $x_t$ satisfies an STL formula $\phi$.
"""
# ╔═╡ 78c782a1-0db2-4c97-a10d-8df036d1c409
x
# ╔═╡ d68f9268-b807-4a76-a1ba-707938b1a589
md"""
## Other Rules
- $\vee$ disjunction/or
- $\phi \vee \psi = \neg(\neg\phi \wedge \neg\psi)$
- $\implies$ implies
- $\phi \implies \psi = \neg\phi \vee \psi$
- $\lozenge$ eventually
- $\square$ always
"""
# ╔═╡ 31317201-432b-47fa-818d-6690010788b0
md"""
# Min/Max Approximation Testing
"""
# ╔═╡ 86cb96ff-5291-4617-848f-36fc1181d122
md"""
## Smooth Min/Max Testing
"""
# ╔═╡ daac79e3-5f16-49ff-9200-6ef1279eaf0d
sm = [1,2,3,4,0.2]
# ╔═╡ 1681bbe3-0327-495c-a3e4-0fc34cc9f298
md"""
# Gradient Testing
"""
# ╔═╡ cb623b6e-f91a-4dab-95a7-525ed0cf3476
# diagonal(A) = [A[i,i] for i in 1:minimum(size(A))]
# ╔═╡ b70197e9-7cc1-44d0-82d8-96cfe3a5de76
max.([1,2,3,4], [0,1,2,5])
# ╔═╡ 084904b0-1c60-4358-8369-50d56c456b2a
md"""
## Until gradients
"""
# ╔═╡ 9c354e0c-4e11-4611-81db-b87bd4c5854b
md"""
# Multidimensional signals
Where $x_t \in \mathbb{R}^n$ and $\mu:\mathbb{R}^n \to \mathbb{R}$.
"""
# ╔═╡ 8ac3d316-6048-42c5-8c80-a75baa5b32b2
X = [[1,1], [2,2], [3,3], [4,5]]
# ╔═╡ c0e942a5-1c67-403a-abd2-8d9805a304e2
mu3(𝐱) = 𝐱[1] - 𝐱[2] # norm(x)
# ╔═╡ c8084849-b06c-465a-a69d-1051ab4b085e
mu3.(X)
# ╔═╡ 1c5eaf4b-68aa-4ec1-95d0-268cff0bebf6
md"""
## Automatic transmission example
$$\square_{1,10} v < 120 \wedge \square_{1,5} \omega < 4750$$
"""
# ╔═╡ 88403601-59c3-4e67-9e02-90fdf5800e4a
# transmission = @formula □(x -> x[1] < 120) ∧ □(x -> x[2] < 4750)
# ╔═╡ f4ccd76d-fdf8-436a-83d3-5b062e45152e
begin
speeds = Real[114, 117, 100, 96, 92, 88, 108, 101, 118, 119]
rpms = Real[4719, 4747, 4706, 4744, 4701, 4744, 4743, 4753, 4712, 4704]
end
# ╔═╡ 46036c23-797f-4f62-b9fa-64f43950747f
speeds
# ╔═╡ 811f6836-e5c8-447f-aa26-dda644fecc1b
rpms
# ╔═╡ d0b29940-303b-41ac-9313-ee290bde89c5
signals = collect(zip(speeds, rpms))
# ╔═╡ 84496823-db6a-4070-b4e3-c8aff24c54a7
function fill2size(arr, val, n)
while length(arr) < n
push!(arr, val)
end
return arr
end
# ╔═╡ d143a411-7824-411c-be71-a7fb6b9745a5
# with_terminal() do
# T = length(signals)
# ab = I -> (first(I), last(I))
# trans = deepcopy(transmission)
# ϕa, ϕb = ab(trans.ϕ.I)
# ψa, ψb = ab(trans.ψ.I)
# for t in 1:T
# trans.ϕ.I = clamp(max(1,ϕa),1,T):clamp(min(t, ϕb),1,T)
# trans.ψ.I = clamp(max(1,ψa),1,T):clamp(min(t, ψb),1,T)
# @info ρ(signals[1:t], trans)
# end
# end
# ╔═╡ 3903012f-d2d9-4a8a-b246-ec778459a06e
md"""
# Unit Tests
"""
# ╔═╡ bea105c3-14c9-411a-a125-d70f905fdf07
x_stl = [1,2,3,4]
# ╔═╡ 61d62b0c-7ea9-4220-87aa-150d801d2f10
max.([1, 2, 3], [-1, -2, 4]) # broadcasting is important here!
# ╔═╡ 4b8cddcd-b180-4e97-b897-ef47a471d941
neg_ex = Expr(:(->), :xₜ, :(¬(μ(xₜ) > 0.5)))
# ╔═╡ 9ce4cb7e-7ec6-429d-99a8-e5c523c45ba9
non_neg_ex = Expr(:(->), :xₜ, :(μ(xₜ) > 0.5))
# ╔═╡ d0722372-8e7a-409a-abd6-088b9a49ec8b
md"""
# Variable testing
"""
# ╔═╡ fda28f2d-255f-4fd6-b08f-59d61c20eb08
md"""
# Junction testing
"""
# ╔═╡ 41dd7143-8783-45ea-9414-fa80b68b4a6c
md"""
# README Example Tests
Sample tests shown in the README file.
"""
# ╔═╡ cc3e80a3-b3e6-46ab-888c-2b1795d8d3d4
md"""
## Example formula
"""
# ╔═╡ c8441616-025f-4755-9925-2b68ab49f341
md"""
## Example robustness
"""
# ╔═╡ fafeca97-78e5-4a7d-8dd2-ee99b1d41cc3
# ϕ = @formula ◊(xᵢ->xᵢ > 0.5)
# x2 = [1, 2, 3, 4, -9, -8]
# ╔═╡ 319a2bf8-8761-4367-a3f8-c896bd144ee4
md"""
# Notebook
"""
# ╔═╡ bf3977db-5fd3-4440-9c01-39d5268181b9
IS_NOTEBOOK = @isdefined PlutoRunner
# ╔═╡ b04a190f-948f-48d6-a173-f2c8ef5f1280
begin
if IS_NOTEBOOK
using Revise
using PlutoUI
using Pkg
Pkg.develop(path="../.")
end
using SignalTemporalLogic
import SignalTemporalLogic: # Pluto triggers
@formula, ⊤, ⊥, ⟹, smoothmax, smoothmin
end
# ╔═╡ 09e292b6-d253-471b-9985-97485b8be5b6
⊤(x)
# ╔═╡ bfa42119-da7c-492c-ac80-83d9f765645e
ρ(x[t], ⊤)
# ╔═╡ c321f5cc-d35c-4ef9-9411-6bfec0ed4a70
ϕ_predicate = @formula xₜ -> μ(xₜ) > 0.5;
# ╔═╡ 82a6d9d9-6693-4c7e-88b5-3a9776a51df7
ϕ_predicate(x)
# ╔═╡ ac98fe7e-378c-44a2-940e-1acb805b7ad7
ρ(x, ϕ_predicate)
# ╔═╡ 499161ae-ee5b-43ae-b313-203c70318771
ρ(x, @formula xₜ -> xₜ > 0.5) # without μ
# ╔═╡ 745b4f91-2671-4b11-a8af-84f1d98f3c1f
ρ(x, @formula xₜ -> xₜ < 0.5) # flipped
# ╔═╡ 674ff4b6-e832-4c98-bcc9-bf240a9dd45d
ϕ_negation = @formula xₜ -> ¬(xₜ > 0.5)
# ╔═╡ 6cf6b47a-64da-4967-be77-190e192e3771
ϕ_negation(x)
# ╔═╡ 3a212a95-32f2-49f2-9903-114b8da8e4cf
ρ(x, ϕ_negation)
# ╔═╡ e67582ba-ea43-4a78-b49e-dd1bc40ca5d9
ρ(x, @formula xₜ -> !(xₜ > 0.5))
# ╔═╡ 6062be75-cacb-4d7b-90fa-be76a9a3adf0
ϕ_conjunction = @formula (xₜ -> μ(xₜ) > 0.5) && (xₜ -> μ(xₜ) > 0);
# ╔═╡ bfdbe9f2-6288-4c00-923b-6cdd7b865f16
ϕ_conjunction(x)
# ╔═╡ 13a7ce7f-62c7-419f-a961-84257fd087dd
ρ(x, ϕ_conjunction)
# ╔═╡ 9b04cffe-a87e-4b6f-b2ca-e9f158f3767e
ρ̃(x, ϕ_conjunction)
# ╔═╡ 00847a03-890f-4397-b162-607251ecbe70
∇ρ̃(x, ϕ_conjunction)
# ╔═╡ d30a3fd9-4719-426d-b766-01eda690b76d
ρ(x[t], @formula (xₜ -> μ(xₜ) > 0.5) && (xₜ -> μ(xₜ) > 0))
# ╔═╡ 31851f20-4030-404e-9dc2-46c8cb099ed8
ρ(x[t], @formula (xₜ -> μ(xₜ) > 0.5) ∧ (xₜ -> μ(xₜ) > 0))
# ╔═╡ 758e16d1-c2f9-4051-9af1-7270e5794699
ρ(x[t], @formula (xₜ -> ¬(μ(xₜ) > 0.5)) ∧ (xₜ -> μ(xₜ) > 0))
# ╔═╡ 8e4780db-ec27-4db9-a5ab-3360db1a69e6
ϕ_disjunction = @formula (xₜ -> μ(xₜ) > 0.5) || (xₜ -> μ(xₜ) > 0);
# ╔═╡ dba58b15-fcb5-4627-bcce-9225302e1a6c
ϕ_disjunction(x)
# ╔═╡ 8b9ee613-8036-43b1-bb0f-a4c3df72ca55
ρ(x, ϕ_disjunction)
# ╔═╡ c9d104b4-3c07-4994-b652-3fa2fdc5c8fc
ρ̃(x, ϕ_disjunction)
# ╔═╡ f512b6c6-c726-4a3d-8fbe-1177f9105c99
ρ(x, @formula (xₜ -> μ(xₜ) > 0.5) ∨ (xₜ -> μ(xₜ) > 0))
# ╔═╡ 2543584d-28d3-4e3c-bb35-59ffb693c3fb
ϕ_implies = @formula (xₜ -> μ(xₜ) > 0.5) ⟹ (xₜ -> μ(xₜ) > 0)
# ╔═╡ b998a448-b4f7-4cce-8f8f-80e6f4728f78
ϕ_implies(x)
# ╔═╡ 6933b884-ecc0-40ac-851b-5d30d24be2e2
ρ(x, ϕ_implies)
# ╔═╡ 28168ab3-1401-4867-845f-2d6a5df705ec
ρ̃(x, ϕ_implies)
# ╔═╡ f58a9304-aca8-4524-ae7d-f5bf7d556714
ϕ_eventually = @formula ◊([3,5], xₜ -> μ(xₜ) > 0.5)
# ╔═╡ 08d19d11-678f-40a8-86c4-41f5635cd01d
ρ(x, ϕ_eventually)
# ╔═╡ 4519edec-4540-456a-9717-a0434d9b5343
∇ρ(x, ϕ_eventually)
# ╔═╡ f0347915-6f10-4a28-8797-76e13c61481e
∇ρ̃(x, ϕ_eventually)
# ╔═╡ 735b1f6e-278e-4566-8d1b-5222ff203160
ρ(x, @formula ◊(0.1:4.4, xₜ -> μ(xₜ) > 0.5))
# ╔═╡ 40269dfd-c968-431b-a74b-9956cafe6614
ϕ_always = @formula □(xₜ -> xₜ > 0.5)
# ╔═╡ 6da89434-ff90-4aa7-8c75-f578efc12009
ρ(x, ϕ_always)
# ╔═╡ 53ef7008-3c1e-4fb6-9a8d-91796a9ea55e
ρ̃(x, ϕ_always)
# ╔═╡ 0ef85cb2-a2e5-4ebe-a27e-6b6177bf870f
@test ρ(x, ϕ_always) == robustness(x, ϕ_always)
# ╔═╡ 96a1a2f6-294f-4645-a53f-a67c30416aeb
@test ρ̃(x, ϕ_always) == smooth_robustness(x, ϕ_always)
# ╔═╡ 8235f0a4-87fd-4c5c-8d19-eb0e0d2e93a6
smooth_robustness(x, ϕ_always)
# ╔═╡ 52b8d155-dfcf-4f3a-a8e0-93399ef48b5c
∇ρ(x, ϕ_always)
# ╔═╡ d1051f1d-dc34-4e3d-bc85-71e738f1a835
∇ρ̃(x, ϕ_always)
# ╔═╡ 6dd5301b-a641-4343-91d3-3b442bb7c90f
ρ(x, @formula □(5:6, xₜ -> xₜ > 0.5))
# ╔═╡ 0f661852-d1b4-4e48-946f-33c111230047
_ϕ = @formula xₜ -> μ(xₜ) > 0;
# ╔═╡ b74bd2ee-eb33-4c41-b3b0-e2544166a8ae
_ϕ.μ(x)
# ╔═╡ 64e31569-5749-448b-836d-0714d5fd12bd
_ϕ.(x)
# ╔═╡ 66ac721c-2392-4420-943d-cebdc9710d9a
_ϕ(x[1])
# ╔═╡ 14f52f51-ec7b-4a30-af2d-4dfeed8618c0
_ψ = @formula xₜ -> -μ(xₜ) > 0;
# ╔═╡ 2c8c423e-ed23-4be9-90f6-d96e9ca8c3cb
U = @formula 𝒰(xₜ -> μ(xₜ) > 0, xₜ -> -μ(xₜ) > 0);
# ╔═╡ ba9e4d5a-e791-4f04-9be1-bbdd5de09d6c
U([0.1, 1, 2, 3, -10, -9, -8])
# ╔═╡ d79856be-3c2f-4ff7-a9c6-94a3a4bf8ffe
U(x)
# ╔═╡ 4efe597d-a2b3-4a2e-916a-323e4c86a823
begin
x1 = [0.001, 1, 2, 3, 4, 5, 6, 7, -8, -9, -10]
ϕ1 = @formula xᵢ -> xᵢ > 0
ψ1 = @formula xᵢ -> -xᵢ > 0 # xᵢ < 0
end;
# ╔═╡ b9643ca4-58aa-4902-a103-2c8140eb6e74
x1
# ╔═╡ 562d3796-bf48-4260-9683-0999f628b43c
U(x1)
# ╔═╡ 482600d2-e1a7-446c-934d-3234885ba14c
begin
time = 1:length(x1)
steptype = :steppost
plot(time, miss(ϕ1.(x1)) .+ 1, lw=5, c=:blue, lab=false, lt=steptype)
plot!(time, miss(ψ1.(x1)), lw=5, c=:red, lab=false, lt=steptype)
plot!(time, .∨(ϕ1.(x1), ψ1.(x1)) .- 1, lw=5, c=:purple, lab=false, lt=steptype)
plot!(ytickfont=12, xtickfont=12)
yticks!(0:2, [L"\phi \mathcal{U} \psi", L"\psi", L"\phi"])
ylims!(-1.1, 3)
xlabel!("time")
xticks!(time)
title!("Until: $(U(x1))")
end
# ╔═╡ 6af6965b-22a4-44dd-ac6f-2aefca4e3b80
ϕ_until = @formula 𝒰(xₜ -> μ(xₜ) > 0, xₜ -> -μ(xₜ) > 0)
# ╔═╡ 83eda8b3-1cf0-44e1-91af-c2140e8c8f50
ϕ_until(x2)
# ╔═╡ 532cb215-740e-422a-8d36-0ecf8b7a528f
ϕ_until
# ╔═╡ 4a66d029-dfcb-4480-8807-88ce28289722
ρ(x2, ϕ_until)
# ╔═╡ 71cf4068-e617-4604-a2cb-295cbd6d82b8
ρ̃(x2, ϕ_until)
# ╔═╡ fbf26cbf-ec93-478d-8677-f79e1382802e
∇ρ(x2, ϕ_until)
# ╔═╡ d32bf800-51d5-455f-ab50-91bb31f67e83
∇ρ̃(x2, ϕ_until)
# ╔═╡ c738c26d-10a7-488a-976e-cc5f69fc4526
ρ(x, @formula 𝒰(2:4, xₜ -> xₜ > 0, xₜ -> -xₜ > 0))
# ╔═╡ 26a3441c-9128-46c6-8b5a-6858d642509c
begin
plot(1:length(x2), fill(ρ(x2, ϕ_until), length(x2)), label="ρ(x,ϕ)")
plot!(1:length(x2), vec(∇ρ(x2, ϕ_until)), label="∇ρ(x,ϕ)")
plot!(1:length(x2), vec(∇ρ̃(x2, ϕ_until)), label="soft ∇ρ̃(x,ϕ; w=1)")
plot!(1:length(x2), vec(∇ρ̃(x2, ϕ_until; w=2)), label="soft ∇ρ̃(x,ϕ; w=2)")
end
# ╔═╡ ab72fec1-8266-4064-8a58-6de08b318ada
begin
x_comb = [4, 3, 2, 1, 0, -1, -2, -3, -4]
ϕ₁ = @formula xₜ -> xₜ > 0
ϕ₂ = @formula xₜ -> -xₜ > 0
ϕc1 = ϕ₁ ∨ ϕ₂
ϕ₃ = @formula xₜ -> xₜ > 0
ϕ₄ = @formula xₜ -> xₜ > 1
ϕc2 = ϕ₃ ∧ ϕ₄
end
# ╔═╡ e0b079d5-8527-4e81-a8c5-f1e354e21717
ϕc1.(x_comb)
# ╔═╡ 4ee8c66a-394c-4ad1-aa69-7121835611bc
ϕc2.(x_comb)
# ╔═╡ ee8e2823-72bc-420d-8069-767a2c31bdec
begin
@assert (false ⟹ false) == true
@assert (false ⟹ true) == true
@assert (true ⟹ false) == false
@assert (true ⟹ true) == true
end
# ╔═╡ e9910277-56ea-44f0-b36e-a9f7e689b736
@test smoothmin(sm; w=0) == minimum(sm)
# ╔═╡ f7e01cce-635a-4897-923e-f62127e784ef
@test smoothmin(sm; w=Inf) == mean(sm)
# ╔═╡ 8a33e8ee-5ba7-4a00-9c0b-a2722f3d0c39
@test smoothmax(sm; w=0) == maximum(sm)
# ╔═╡ eb2a96f7-7635-49de-a967-604658d4905d
@test smoothmax(sm; w=Inf) == mean(sm)
# ╔═╡ e28af833-ebc3-4767-a5ba-0c2f5dbbc028
@test robustness(x, ϕ_always; w=1) == smooth_robustness(x, ϕ_always)
# ╔═╡ dded9b53-c9d4-47b1-9cd2-ca5a3cd245fb
@test robustness(x, ϕ_always) == ρ(x, ϕ_always)
# ╔═╡ c5101fe8-6617-434e-817e-eeac1caa3170
q = @formula ◊(xᵢ->μ(xᵢ) > 0.5)
# ╔═╡ 7ea907bd-d46e-42dc-8bfa-12264f9935b7
∇ρ(x2, q)
# ╔═╡ e0b47a72-6e21-4751-a441-a49b5bad9175
∇ρ̃(x2, q)
# ╔═╡ af384ae1-a6bc-4f5c-a19d-3b90bf50254f
ρ(x2,q)
# ╔═╡ 9f692e34-ecf1-44ae-8f99-68606e8a1b09
ρ̃(x2,q)
# ╔═╡ ea0be409-4fc6-42a8-a1d9-98aa8db843d6
smoothmax.([1,2,3,4], [0,1,2,5])
# ╔═╡ e2a50d76-07df-40b6-9b82-0fddd3785208
∇ρ(x2, ϕ_until)
# ╔═╡ fe39c9df-ecc3-43ac-aa75-0a4ca704afb7
ρ(x2, ϕ_until)
# ╔═╡ 405f53c4-e273-42f8-9465-e70370d9ec5c
∇ρ̃(x2, ϕ_until)
# ╔═╡ cdbad3c0-375c-486f-86e9-991ce660f76e
ρ̃(x,ϕ_until)
# ╔═╡ 4cce6436-76f7-4b19-831f-b0c63757c16e
ϕ_md = @formula ¬(xₜ->mu3(xₜ) > 0) && ¬(xₜ->-mu3(xₜ) > 0)
# ╔═╡ 53775e8e-c933-4fe1-b23e-28218633ad82
ϕ_md.(X)
# ╔═╡ 0c8e5d02-377c-4e47-98b9-dceeef518e77
map(x->ρ(x, ϕ_md), X) # ρ.(X, ϕ) doesn't work
# ╔═╡ 29b0e762-9b4e-4cde-adc3-9ead18115917
map(x->ρ̃(x, ϕ_md), X) # ρ.(X, ϕ) doesn't work
# ╔═╡ 8ebb7717-7563-4202-ae47-2d6c6646a874
transmission = @formula □(1:10, x -> x[1] < 120) ∧ □(1:5, x -> x[2] < 4750)
# ╔═╡ fb56bf20-317b-41bc-b0ad-33fac8d54dc2
@test transmission(signals)
# ╔═╡ 61a54891-d15d-4747-bd29-ee9d3d24fb2e
# Get the robustness at each time step.
function ρ_overtime(x, ϕ)
return [ρ(fill2size(x[1:t], (-Inf, -Inf), length(x)), ϕ) for t in 1:length(x)]
end
# ╔═╡ 01ea793a-52b4-45a8-b829-4b7acfb5b49d
ρ_overtime(signals, transmission)
# ╔═╡ 67d1440d-42f6-4255-ba27-d041b45fec78
@test ρ(signals, transmission) == 1
# ╔═╡ 324c7c0a-b627-46d3-945d-573c960d57e6
∇ρ(signals, transmission)
# ╔═╡ e0cc216e-8565-4ca5-8ee8-fe9516bc6c1a
∇ρ̃(signals, transmission)
# ╔═╡ 3d155de2-0614-4561-b0f7-b5788c557539
ϕ_stl = @formula □(x->x < 5)
# ╔═╡ c69a2c61-ffe6-47d0-bda7-b12183a96d95
STL.robustness(x_stl, ϕ_stl) == ρ(x_stl, ϕ_stl)
# ╔═╡ 282fa1af-7670-4384-b303-3b5359a31fc0
ρ(x, @formula □(1:3, (xₜ -> xₜ > 0.5) ⟹ ◊(xₜ -> xₜ > 0.5)))
# ╔═╡ 7fe34fde-7a21-44bb-8965-d680cfed8aab
ρ(x, @formula □(1:3, ◊(xₜ -> ¬(xₜ > 0.5)) ⟹ (xₜ -> xₜ > 0.5)))
# ╔═╡ 45e19fc0-5819-4df9-8eea-5460dcc5543b
big_formula = @formula □(1:10, (xᵢ -> xᵢ[1] > 0.5) ⟹ ◊(3:5, xᵢ -> xᵢ[2] > 0.5))
# ╔═╡ 5f18a00a-b7d0-482a-8201-0905b8857d90
get_type = SignalTemporalLogic.parse_formula
# ╔═╡ a5f918e4-81a7-410d-81b0-3a31acdff7ec
@formula(xₜ -> true)
# ╔═╡ f67bfa55-3d82-4783-8f8d-34288b05229c
@test isa(@formula(xₜ -> true), Atomic)
# ╔═╡ fbf51c72-4e21-4918-a928-10defa4832dd
@test isa(@formula(xₜ -> ¬(μ(xₜ) > 0.5)), Negation)
# ╔═╡ 1d6af625-92a5-45bc-ade3-d0a3ace4b9f1
@test isa(@formula(xₜ -> μ(xₜ) > 0.5), Predicate)
# ╔═╡ bc7cca16-207b-4ddc-a204-f1ecacd6985a
@test isa(@formula(xₜ -> ¬(xₜ > 0.5)), Negation)
# ╔═╡ 0bf6dd4c-c750-4e17-9bb3-31436d3dfa67
@test isa(@formula(xₜ -> xₜ > 0.5), Predicate)
# ╔═╡ 3fb98fd1-94f0-4b0f-b721-af0bfc8cacde
@test isa(@formula(xₜ -> xₜ > 0.5), Predicate)
# ╔═╡ ff2b7631-2325-4580-9cf0-1caee91add30
@test isa(@formula((xₜ -> xₜ > 0.5) && (xₜ -> xₜ > 0)), Conjunction)
# ╔═╡ 9874e9ab-4431-45c4-8ece-e2b8f4a4cd43
@test isa(@formula((xₜ -> xₜ > 0.5) || (xₜ -> xₜ > 0)), Disjunction)
# ╔═╡ dd8dc778-e87a-4f62-9041-6be2ba9eb6a9
@test isa(@formula(◊(xₜ -> xₜ > 0.5)), Eventually)
# ╔═╡ b2a24987-1518-4542-9f6c-50e700759e12
@test isa(@formula(□(xₜ -> xₜ > 0.5)), Always)
# ╔═╡ fa5eaecc-e9bd-4d0f-9be5-5515f4e4fd10
@test isa(@formula(𝒰(xₜ -> xₜ > 0.5, xₜ -> xₜ < 0.5)), Until)
# ╔═╡ 71027432-bc47-4de8-bb34-8a3e20e619b0
@test SignalTemporalLogic.strip_negation(neg_ex) == non_neg_ex
# ╔═╡ aea4bd82-6a4f-4347-b8f0-f0e2870c3401
@test (@formula x->¬(x > 0))(x) == (@formula ¬(x->x > 0))(x)
# ╔═╡ 473ef134-f689-4eeb-b4e9-d116cbda4101
@test isa(@formula((xₜ -> xₜ > 0.5) ⟺ (xₜ -> xₜ < 1.0)), Biconditional)
# ╔═╡ a087ed1a-ef52-423e-83c7-9669ff42ccc0
@test begin
local ϕ = @formula(xₜ -> xₜ == 0.5)
ϕ(0.5) && !ϕ(1000)
end
# ╔═╡ 5833958c-53cb-4ed5-8416-97168f6425de
function test_local_variable(λ)
return @eval @formula s->s > $λ # Note to interpolate variable with $
end
# ╔═╡ f725ac4b-d8b7-4955-bea0-f3d3d83265aa
@test test_local_variable(1234).c == 1234
# ╔═╡ 5ccc7a0f-c3b2-4429-9bd5-d7fd9bcb97b5
@test begin
local upright = @formula s -> abs(s[1]) < π / 4
local ψ = @eval @formula □($upright) # input anonymous function MUST be a Formula
ψ([π/10]) && !(ψ([π/3]))
end
# ╔═╡ e2313bcd-dd8f-4ffd-ac1e-7e08304c37b5
@test_throws "Symbol " begin
local variable
local ψ = @formula □(variable)
end
# ╔═╡ aea96bbd-d006-4933-a8cb-5165a0158499
@test begin
local conjunc_test = @formula s->(s[1] < 50) && (s[4] < 1)
conjunc_test([49, 0, 0, 0.9]) == true && conjunc_test([49, 0, 0, 1.1]) == false
end
# ╔═╡ 781e31e0-1688-48e0-9a22-b5aea40ffb87
@test begin
local conjunc_test2 = @formula (s->s[1] < 50) && (s->s[4] < 1)
conjunc_test2([49, 0, 0, 0.9]) == true && conjunc_test2([49, 0, 0, 1.1]) == false
end
# ╔═╡ 6c843d45-4c30-4dcd-a30b-27a12c2e1195
@test begin
local ϕ = @formula □(s->s[1] < 50 && s[4] < 1)
ϕ([[49, 0, 0, 0], [49, 0, 0, -1]]) &&
ϕ([(49, 0, 0, 0), (49, 0, 0, -1)]) &&
ϕ(([49, 0, 0, 0], [49, 0, 0, -1])) &&
ϕ(((49, 0, 0, 0), (49, 0, 0, -1)))
end
# ╔═╡ c4f343f7-8c63-4f71-8f46-668675841de7
@test begin
# Signals (i.e., trace)
# x = [-0.25, 0, 0.1, 0.6, 0.75, 1.0]
# STL formula: "eventually the signal will be greater than 0.5"
ϕ = @formula ◊(xₜ -> xₜ > 0.5)
# Check if formula is satisfied
ϕ(x)
end
# ╔═╡ 0705ce64-9e9d-427e-8cdf-6d958a10c238
∇ρ(x2, q)
# ╔═╡ 38e9a99b-c89c-4973-9538-90d5c4bbb017
∇ρ̃(x2, q)
# ╔═╡ 450f79d5-3393-4aa0-85d6-9bbd8b0b3224
IS_NOTEBOOK && TableOfContents()
# ╔═╡ Cell order:
# ╟─d8a7facd-1ad8-413d-9037-054472fdc50f
# ╠═752d2f6b-a2bb-45bc-9fac-299f88d13f00
# ╠═b04a190f-948f-48d6-a173-f2c8ef5f1280
# ╠═450f79d5-3393-4aa0-85d6-9bbd8b0b3224
# ╠═d383bf0a-3ff1-46d5-b285-63a803463bc0
# ╠═c27ce933-8a2f-4384-bb3f-d843c1112740
# ╟─0259067a-b538-4dd2-8665-d308273c1a21
# ╠═09e292b6-d253-471b-9985-97485b8be5b6
# ╠═bfa42119-da7c-492c-ac80-83d9f765645e
# ╟─3846c63f-32e7-4f96-8e7a-ff62a5b5a21c
# ╠═c321f5cc-d35c-4ef9-9411-6bfec0ed4a70
# ╠═82a6d9d9-6693-4c7e-88b5-3a9776a51df7
# ╠═ac98fe7e-378c-44a2-940e-1acb805b7ad7
# ╠═499161ae-ee5b-43ae-b313-203c70318771
# ╠═745b4f91-2671-4b11-a8af-84f1d98f3c1f
# ╟─0398e51a-7c72-4fd9-8884-387ee256a9cb
# ╠═674ff4b6-e832-4c98-bcc9-bf240a9dd45d
# ╠═b9643ca4-58aa-4902-a103-2c8140eb6e74
# ╠═6cf6b47a-64da-4967-be77-190e192e3771
# ╠═3a212a95-32f2-49f2-9903-114b8da8e4cf
# ╠═e67582ba-ea43-4a78-b49e-dd1bc40ca5d9
# ╟─016fa961-5f8a-4993-9fdf-a0c2c8d3c540
# ╠═6062be75-cacb-4d7b-90fa-be76a9a3adf0
# ╠═bfdbe9f2-6288-4c00-923b-6cdd7b865f16
# ╠═13a7ce7f-62c7-419f-a961-84257fd087dd
# ╠═9b04cffe-a87e-4b6f-b2ca-e9f158f3767e
# ╠═00847a03-890f-4397-b162-607251ecbe70
# ╠═d30a3fd9-4719-426d-b766-01eda690b76d
# ╠═31851f20-4030-404e-9dc2-46c8cb099ed8
# ╠═758e16d1-c2f9-4051-9af1-7270e5794699
# ╟─3e02651f-fffd-47d7-956d-5ba405ecbfaa
# ╠═8e4780db-ec27-4db9-a5ab-3360db1a69e6
# ╠═dba58b15-fcb5-4627-bcce-9225302e1a6c
# ╠═8b9ee613-8036-43b1-bb0f-a4c3df72ca55
# ╠═c9d104b4-3c07-4994-b652-3fa2fdc5c8fc
# ╠═f512b6c6-c726-4a3d-8fbe-1177f9105c99
# ╟─74fabd52-861f-46dd-a509-cb10914ba332
# ╠═2543584d-28d3-4e3c-bb35-59ffb693c3fb
# ╠═b998a448-b4f7-4cce-8f8f-80e6f4728f78
# ╠═6933b884-ecc0-40ac-851b-5d30d24be2e2
# ╠═28168ab3-1401-4867-845f-2d6a5df705ec
# ╟─e9cad561-10d3-48dd-ac13-090906b7c1e0
# ╠═f58a9304-aca8-4524-ae7d-f5bf7d556714
# ╠═08d19d11-678f-40a8-86c4-41f5635cd01d
# ╠═4519edec-4540-456a-9717-a0434d9b5343
# ╠═f0347915-6f10-4a28-8797-76e13c61481e
# ╠═735b1f6e-278e-4566-8d1b-5222ff203160
# ╟─d5fb1b62-574f-4025-9cf8-8e62e357f29f
# ╠═40269dfd-c968-431b-a74b-9956cafe6614
# ╠═6da89434-ff90-4aa7-8c75-f578efc12009
# ╠═53ef7008-3c1e-4fb6-9a8d-91796a9ea55e
# ╠═0ef85cb2-a2e5-4ebe-a27e-6b6177bf870f
# ╠═96a1a2f6-294f-4645-a53f-a67c30416aeb
# ╠═8235f0a4-87fd-4c5c-8d19-eb0e0d2e93a6
# ╠═52b8d155-dfcf-4f3a-a8e0-93399ef48b5c
# ╠═d1051f1d-dc34-4e3d-bc85-71e738f1a835
# ╠═6dd5301b-a641-4343-91d3-3b442bb7c90f
# ╟─00b37481-0a05-4f5a-a6d0-2fdddaa6ee97
# ╠═1d0e135e-6cc3-422e-ba44-fee53cc1965f
# ╠═0f661852-d1b4-4e48-946f-33c111230047
# ╠═14f52f51-ec7b-4a30-af2d-4dfeed8618c0
# ╠═2305b206-0c6d-440d-81b7-0f485cc8a6a8
# ╠═2c8c423e-ed23-4be9-90f6-d96e9ca8c3cb
# ╠═b74bd2ee-eb33-4c41-b3b0-e2544166a8ae
# ╠═ba9e4d5a-e791-4f04-9be1-bbdd5de09d6c
# ╠═d79856be-3c2f-4ff7-a9c6-94a3a4bf8ffe
# ╠═4efe597d-a2b3-4a2e-916a-323e4c86a823
# ╠═562d3796-bf48-4260-9683-0999f628b43c
# ╟─2d65db96-f8cf-4ccc-b4f5-1c642249ed7b
# ╠═39ceaac5-1084-44fa-9388-18593600eb11
# ╠═e74099af-ea14-46d6-a61d-d71d176f5e45
# ╠═ef4d7b05-d4b3-4498-9e5f-c26d9b47fb60
# ╠═482600d2-e1a7-446c-934d-3234885ba14c
# ╟─d1c3412a-373b-47e2-b3d1-383d4ce1fa61
# ╠═6af6965b-22a4-44dd-ac6f-2aefca4e3b80
# ╠═56d37e18-c978-4757-9ed4-e4bd412af310
# ╠═83eda8b3-1cf0-44e1-91af-c2140e8c8f50
# ╠═4a66d029-dfcb-4480-8807-88ce28289722
# ╠═71cf4068-e617-4604-a2cb-295cbd6d82b8
# ╠═fbf26cbf-ec93-478d-8677-f79e1382802e
# ╠═d32bf800-51d5-455f-ab50-91bb31f67e83
# ╠═c738c26d-10a7-488a-976e-cc5f69fc4526
# ╠═26a3441c-9128-46c6-8b5a-6858d642509c
# ╟─b30d0b1e-493b-48c0-b492-5f7dd2ad872b
# ╟─ce82cf55-0e32-412e-b6c6-f95563796e7e
# ╠═ab72fec1-8266-4064-8a58-6de08b318ada
# ╠═e0b079d5-8527-4e81-a8c5-f1e354e21717
# ╠═4ee8c66a-394c-4ad1-aa69-7121835611bc
# ╟─ec6ff814-1179-4525-b138-094ca6bec408
# ╠═78c782a1-0db2-4c97-a10d-8df036d1c409
# ╠═64e31569-5749-448b-836d-0714d5fd12bd
# ╠═66ac721c-2392-4420-943d-cebdc9710d9a
# ╟─d68f9268-b807-4a76-a1ba-707938b1a589
# ╠═ee8e2823-72bc-420d-8069-767a2c31bdec
# ╟─31317201-432b-47fa-818d-6690010788b0
# ╠═ab57fd9b-9bec-48fc-8530-483a5d4ddb11
# ╟─86cb96ff-5291-4617-848f-36fc1181d122
# ╠═daac79e3-5f16-49ff-9200-6ef1279eaf0d
# ╠═e9910277-56ea-44f0-b36e-a9f7e689b736
# ╠═f7e01cce-635a-4897-923e-f62127e784ef
# ╠═8a33e8ee-5ba7-4a00-9c0b-a2722f3d0c39
# ╠═eb2a96f7-7635-49de-a967-604658d4905d
# ╠═e28af833-ebc3-4767-a5ba-0c2f5dbbc028
# ╠═dded9b53-c9d4-47b1-9cd2-ca5a3cd245fb
# ╟─1681bbe3-0327-495c-a3e4-0fc34cc9f298
# ╠═c5101fe8-6617-434e-817e-eeac1caa3170
# ╠═7ea907bd-d46e-42dc-8bfa-12264f9935b7
# ╠═e0b47a72-6e21-4751-a441-a49b5bad9175
# ╠═af384ae1-a6bc-4f5c-a19d-3b90bf50254f
# ╠═9f692e34-ecf1-44ae-8f99-68606e8a1b09
# ╠═cb623b6e-f91a-4dab-95a7-525ed0cf3476
# ╠═b70197e9-7cc1-44d0-82d8-96cfe3a5de76
# ╠═ea0be409-4fc6-42a8-a1d9-98aa8db843d6
# ╟─084904b0-1c60-4358-8369-50d56c456b2a
# ╠═532cb215-740e-422a-8d36-0ecf8b7a528f
# ╠═e2a50d76-07df-40b6-9b82-0fddd3785208
# ╠═fe39c9df-ecc3-43ac-aa75-0a4ca704afb7
# ╠═405f53c4-e273-42f8-9465-e70370d9ec5c
# ╠═cdbad3c0-375c-486f-86e9-991ce660f76e
# ╟─9c354e0c-4e11-4611-81db-b87bd4c5854b
# ╠═d06d3ce6-d13b-4ab6-bb66-8a07835e1ce7
# ╠═8ac3d316-6048-42c5-8c80-a75baa5b32b2
# ╠═c0e942a5-1c67-403a-abd2-8d9805a304e2
# ╠═c8084849-b06c-465a-a69d-1051ab4b085e
# ╠═4cce6436-76f7-4b19-831f-b0c63757c16e
# ╠═53775e8e-c933-4fe1-b23e-28218633ad82
# ╠═0c8e5d02-377c-4e47-98b9-dceeef518e77
# ╠═29b0e762-9b4e-4cde-adc3-9ead18115917
# ╟─1c5eaf4b-68aa-4ec1-95d0-268cff0bebf6
# ╠═8ebb7717-7563-4202-ae47-2d6c6646a874
# ╠═88403601-59c3-4e67-9e02-90fdf5800e4a
# ╠═f4ccd76d-fdf8-436a-83d3-5b062e45152e
# ╠═46036c23-797f-4f62-b9fa-64f43950747f
# ╠═811f6836-e5c8-447f-aa26-dda644fecc1b
# ╠═d0b29940-303b-41ac-9313-ee290bde89c5
# ╠═fb56bf20-317b-41bc-b0ad-33fac8d54dc2
# ╠═84496823-db6a-4070-b4e3-c8aff24c54a7
# ╠═61a54891-d15d-4747-bd29-ee9d3d24fb2e
# ╠═01ea793a-52b4-45a8-b829-4b7acfb5b49d
# ╠═67d1440d-42f6-4255-ba27-d041b45fec78
# ╠═324c7c0a-b627-46d3-945d-573c960d57e6
# ╠═e0cc216e-8565-4ca5-8ee8-fe9516bc6c1a
# ╠═d143a411-7824-411c-be71-a7fb6b9745a5
# ╟─3903012f-d2d9-4a8a-b246-ec778459a06e
# ╠═3d155de2-0614-4561-b0f7-b5788c557539
# ╠═bea105c3-14c9-411a-a125-d70f905fdf07
# ╠═c69a2c61-ffe6-47d0-bda7-b12183a96d95
# ╠═282fa1af-7670-4384-b303-3b5359a31fc0
# ╠═7fe34fde-7a21-44bb-8965-d680cfed8aab
# ╠═61d62b0c-7ea9-4220-87aa-150d801d2f10
# ╠═45e19fc0-5819-4df9-8eea-5460dcc5543b
# ╠═5f18a00a-b7d0-482a-8201-0905b8857d90
# ╠═a5f918e4-81a7-410d-81b0-3a31acdff7ec
# ╠═f67bfa55-3d82-4783-8f8d-34288b05229c
# ╠═fbf51c72-4e21-4918-a928-10defa4832dd
# ╠═1d6af625-92a5-45bc-ade3-d0a3ace4b9f1
# ╠═bc7cca16-207b-4ddc-a204-f1ecacd6985a
# ╠═0bf6dd4c-c750-4e17-9bb3-31436d3dfa67
# ╠═3fb98fd1-94f0-4b0f-b721-af0bfc8cacde
# ╠═ff2b7631-2325-4580-9cf0-1caee91add30
# ╠═9874e9ab-4431-45c4-8ece-e2b8f4a4cd43
# ╠═dd8dc778-e87a-4f62-9041-6be2ba9eb6a9
# ╠═b2a24987-1518-4542-9f6c-50e700759e12
# ╠═fa5eaecc-e9bd-4d0f-9be5-5515f4e4fd10
# ╠═4b8cddcd-b180-4e97-b897-ef47a471d941
# ╠═9ce4cb7e-7ec6-429d-99a8-e5c523c45ba9
# ╠═71027432-bc47-4de8-bb34-8a3e20e619b0
# ╠═aea4bd82-6a4f-4347-b8f0-f0e2870c3401
# ╠═473ef134-f689-4eeb-b4e9-d116cbda4101
# ╠═a087ed1a-ef52-423e-83c7-9669ff42ccc0
# ╟─d0722372-8e7a-409a-abd6-088b9a49ec8b
# ╠═5833958c-53cb-4ed5-8416-97168f6425de
# ╠═f725ac4b-d8b7-4955-bea0-f3d3d83265aa
# ╠═5ccc7a0f-c3b2-4429-9bd5-d7fd9bcb97b5
# ╠═e2313bcd-dd8f-4ffd-ac1e-7e08304c37b5
# ╟─fda28f2d-255f-4fd6-b08f-59d61c20eb08
# ╠═aea96bbd-d006-4933-a8cb-5165a0158499
# ╠═781e31e0-1688-48e0-9a22-b5aea40ffb87
# ╠═6c843d45-4c30-4dcd-a30b-27a12c2e1195
# ╟─41dd7143-8783-45ea-9414-fa80b68b4a6c
# ╟─cc3e80a3-b3e6-46ab-888c-2b1795d8d3d4
# ╠═c4f343f7-8c63-4f71-8f46-668675841de7
# ╟─c8441616-025f-4755-9925-2b68ab49f341
# ╠═fafeca97-78e5-4a7d-8dd2-ee99b1d41cc3
# ╠═0705ce64-9e9d-427e-8cdf-6d958a10c238
# ╠═38e9a99b-c89c-4973-9538-90d5c4bbb017
# ╟─319a2bf8-8761-4367-a3f8-c896bd144ee4
# ╠═bf3977db-5fd3-4440-9c01-39d5268181b9
| SignalTemporalLogic | https://github.com/sisl/SignalTemporalLogic.jl.git |
|
[
"MIT"
] | 0.1.0 | 5fbd28f4de5d850d07adb040790b240190c706dd | docs | 1809 | # SignalTemporalLogic.jl
This package can define _signal temporal logic_ (STL) formulas using the `@formula` macro and then check if the formulas satisfy a signal trace. It can also measure the _robustness_ of a trace through an STL formula and compute the gradient of the robustness (as well as an approximate gradient using smooth min and max functions).
[](https://sisl.github.io/SignalTemporalLogic.jl/notebooks/stl.html)
[](https://github.com/sisl/SignalTemporalLogic.jl/actions/workflows/CI.yml)
<!-- [](https://codecov.io/gh/sisl/SignalTemporalLogic.jl) -->
## Installation
```julia
] add https://github.com/sisl/SignalTemporalLogic.jl
```
## Examples
[](https://sisl.github.io/SignalTemporalLogic.jl/notebooks/runtests.html)
See the tests for more elaborate examples: https://sisl.github.io/SignalTemporalLogic.jl/notebooks/runtests.html
### Example STL formula
```julia
# Signals (i.e., trace)
x = [-0.25, 0, 0.1, 0.6, 0.75, 1.0]
# STL formula: "eventually the signal will be greater than 0.5"
ϕ = @formula ◊(xₜ -> xₜ > 0.5)
# Check if formula is satisfied
ϕ(x)
```
### Example robustness
```julia
# Signals
x = [1, 2, 3, 4, -9, -8]
# STL formula: "eventually the signal will be greater than 0.5"
ϕ = @formula ◊(xₜ -> xₜ > 0.5)
# Robustness
∇ρ(x, ϕ)
# Outputs: [0.0 0.0 0.0 1.0 0.0 0.0]
# Smooth approximate robustness
∇ρ̃(x, ϕ)
# Outputs: [-0.0478501 -0.0429261 0.120196 0.970638 -1.67269e-5 -4.15121e-5]
```
---
[Robert Moss](https://github.com/mossr)
| SignalTemporalLogic | https://github.com/sisl/SignalTemporalLogic.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1108 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1144 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1257 | using BenchmarkTools, FinancialMonteCarlo, Statistics;
S0 = 100.0;
K = 100.0;
r = [0.00, 0.02];
T = 1.0;
d = FinancialMonteCarlo.Curve([0.00, 0.02], T);
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8
rfCurve = FinancialMonteCarlo.ZeroRateCurve(r, T);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
EUBin = BinaryEuropeanOption(T, K)
AMData = AmericanOption(T, K)
AmBin = BinaryEuropeanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1127 | using BenchmarkTools, FinancialMonteCarlo, DualNumbers
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = dual(0.2, 1.0);
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1147 | using BenchmarkTools, FinancialMonteCarlo, ForwardDiff
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = ForwardDiff.Dual{Float64}(0.2, 1.0)
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 970 | using BenchmarkTools, FinancialMonteCarlo, ForwardDiff
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 100000;
Nstep = 30;
sigma = 0.2
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
f__1(x::Vector) = pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, EuropeanOption(x[5], K));
x = Float64[sigma, S0, r, d, T]
g__1 = x -> ForwardDiff.gradient(f__1, x);
y0 = g__1(x);
@btime f__1(x);
@btime g__1(x);
f_(x::Vector) = pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, AmericanOption(x[5], K));
g_ = x -> ForwardDiff.gradient(f_, x);
y0 = g_(x);
@btime f_(x);
@btime g_(x);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 567 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 651 | using BenchmarkTools
@everywhere using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.MultiProcess(FinancialMonteCarlo.SerialMode(), 12));
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 605 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.MultiThreading());
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1162 | using BenchmarkTools, FinancialMonteCarlo, ReverseDiff
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 100000;
Nstep = 30;
sigma = 0.2
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
f(x) = pricer(BlackScholesProcess(x[1], Underlying(x[2], d)), ZeroRate(r), mc, EuropeanOption(x[3], K));
#f(x) = pricer(BlackScholesProcess(x[1]),ZeroRate(x[2],r,d),mc,EuropeanOption(T,K),Underlying(S0,d));
#x=Float64[sigma,S0,r,d,T]
x = Float64[sigma, S0, T]
g = x -> ReverseDiff.gradient(f, x);
y0 = g(x);
@btime f(x);
@btime g(x);
#f1_(x) = pricer(BlackScholesProcess(x[1]),ZeroRate(x[2],x[3],x[4]),mc,AmericanOption(x[5],K),Underlying(S0,d));
f1_(x) = pricer(BlackScholesProcess(x[1], Underlying(x[2], d)), ZeroRate(r), mc, AmericanOption(x[3], K));
g_ = x -> ReverseDiff.gradient(f1_, x);
#y0=g(x);
@btime f1_(x);
#@btime g_(x);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 794 | using BenchmarkTools, FinancialMonteCarlo, DualNumbers
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = dual(0.2, 1.0);
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T * 2.0)
EUData = EuropeanOption(T * 1.1, K)
AMData = AmericanOption(T * 4.0, K)
BarrierData = BarrierOptionDownOut(T * 0.5, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T * 3.3)
AsianFixedStrikeData = AsianFixedStrikeOption(T * 1.2, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1208 | using BenchmarkTools, FinancialMonteCarlo;
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
sigma_zero = 0.2;
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho = 0.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = HestonProcess(sigma, sigma_zero, lambda, kappa, rho, theta, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1232 | using BenchmarkTools, FinancialMonteCarlo, DualNumbers;
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
sigma_zero = dual(0.2, 1.0);
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho = 0.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = HestonProcess(sigma, sigma_zero, lambda, kappa, rho, theta, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1164 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = KouProcess(sigma, lam, p, lamp, lamm, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1238 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = [0.00, 0.02];
T = 1.0;
d = FinancialMonteCarlo.Curve([0.00, 0.02], T);
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = FinancialMonteCarlo.ZeroRateCurve(r, T);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = KouProcess(sigma, lam, p, lamp, lamm, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1201 | using BenchmarkTools, DualNumbers
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = dual(0.2, 1.0);
#sigma=0.2;
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = KouProcess(sigma, lam, p, lamp, lamm, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1326 | using BenchmarkTools, FinancialMonteCarlo, ReverseDiff
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = KouProcess(sigma, lam, p, lamp, lamm, Underlying(S0, d));
Model = KouProcess(x[1], lam, p, lamp, lamm, Underlying(S0, d));
#f(x) = pricer(KouProcess(x[1],lam,p,lamp,lamm,Underlying(S0,d)),ZeroRate(x[2],x[3],x[4]),mc,EuropeanOption(x[5],K));
f(x) = pricer(KouProcess(x[1], lam, p, lamp, lamm, Underlying(S0, d)), ZeroRate(x[2], r, d), mc, EuropeanOption(T, K));
#x=Float64[sigma,S0,r,d,T]
x = Float64[sigma, S0]
g = x -> ReverseDiff.gradient(f, x);
y0 = g(x);
@btime f(x);
@btime g(x);
#f1_(x) = pricer(BlackScholesProcess(x[1],Underlying(S0,d)),ZeroRate(x[2],x[3],x[4]),mc,AmericanOption(x[5],K));
f1_(x) = pricer(KouProcess(x[1], lam, p, lamp, lamm, Underlying(S0, d)), ZeroRate(x[2], r, d), mc, AmericanOption(T, K));
g_ = x -> ReverseDiff.gradient(f1_, x);
#y0=g(x);
@btime f1_(x);
#@btime g_(x);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1157 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
lam = 5.0;
mu1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = MertonProcess(sigma, lam, mu1, sigma1, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1169 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = NormalInverseGaussianProcess(sigma, theta1, k1, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1463 | using Test, FinancialMonteCarlo, DualNumbers, BenchmarkTools;
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
underlying_name = "ENJ"
underlying_name_2 = "ABPL"
underlying_ = underlying_name * "_" * underlying_name_2 * "_TESL"
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc1 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOptionND(T, K)
Model_enj = BlackScholesProcess(sigma, Underlying(S0, d));
Model_enj_2 = BlackScholesProcess(dual(sigma, 1.0), Underlying(S0, d));
Model_abpl = BlackScholesProcess(sigma, Underlying(S0, d));
Model_tesl = BlackScholesProcess(sigma, Underlying(S0, d));
rho_1 = [1.0 0.0 0.0; 0.0 1.0 0.0; 0.0 0.0 1.0];
Model = GaussianCopulaNVariateProcess(rho_1, Model_enj, Model_abpl, Model_tesl)
ModelDual = GaussianCopulaNVariateProcess(rho_1, Model_enj_2, Model_abpl, Model_tesl)
Model2 = GaussianCopulaNVariateProcess([1.0 0.3 0.0; 0.3 1.0 0.0; 0.0 0.0 1.0], Model_enj_2, Model_abpl, Model_tesl)
# display(Model)
mktdataset = underlying_ → Model
mktdataset_dual = underlying_ → ModelDual
mktdataset_aug = underlying_ → Model2
portfolio_ = [EUData];
portfolio = underlying_ → EUData
@btime price_mkt = pricer(mktdataset, rfCurve, mc, portfolio)
@btime price_mkt = pricer(mktdataset_dual, rfCurve, mc, portfolio)
@btime price_mkt = pricer(mktdataset_aug, rfCurve, mc, portfolio)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1161 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1197 | using BenchmarkTools
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1185 | using BenchmarkTools, DualNumbers
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = dual(0.2, 1.0);
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, d));
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime BarrierPrice = pricer(Model, rfCurve, mc, BarrierData);
@btime AsianPrice1 = pricer(Model, rfCurve, mc, AsianFloatingStrikeData);
@btime AsianPrice2 = pricer(Model, rfCurve, mc, AsianFixedStrikeData);
optionDatas = [FwdData, EUData, AMData, BarrierData, AsianFloatingStrikeData, AsianFixedStrikeData]
@btime (FwdPrice, EuPrice, AMPrice, BarrierPrice, AsianPrice1, AsianPrice2) = pricer(Model, rfCurve, mc, optionDatas)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 872 | using Pkg, FinancialMonteCarlo;
#get(ENV, "CI", nothing) == "true" ? Pkg.instantiate() : nothing;
path1 = joinpath(dirname(pathof(FinancialMonteCarlo)), "..", "benchmark")
test_listTmp = readdir(path1);
BlackList = ["Project.toml", "benchmarks.jl", "runner.jl", "cuda", "af", "Manifest.toml", "bench_kou_rev_diff_grad.jl", "bench_black_mp.jl", "bench_black_mn.jl", "bench_black_mt.jl"]
test_list = [test_element for test_element in test_listTmp if !Bool(sum(test_element .== BlackList))]
println("Running tests:\n")
for (current_test, i) in zip(test_list, 1:length(test_list))
println("------------------------------------------------------------")
println(" * $(current_test) *")
include(joinpath(path1, current_test))
println("------------------------------------------------------------")
if (i < length(test_list))
println("")
end
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1036 | using BenchmarkTools
using FinancialMonteCarlo, ArrayFire
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_ = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AFMode());
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
#@show "Fwd"
FwdPrice = pricer(Model, rfCurve, mc_, FwdData);
@show "STD fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@btime FwdPrice = pricer(Model, rfCurve, mc_, FwdData);
@show "std eu"
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@btime EuPrice = pricer(Model, rfCurve, mc_, EUData);
@show "std am"
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@btime AmPrice = pricer(Model, rfCurve, mc_, AMData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1101 | using BenchmarkTools
using FinancialMonteCarlo, CUDA
CUDA.allowscalar(false)
S0 = 100.0f0;
K = 100.0f0;
r = 0.02f0;
T = 1.0f0;
d = 0.01f0;
D = 90.0f0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2f0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@show "STD fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show "CUDA fwd"
@btime (CUDA.@sync FwdPrice = pricer(Model, rfCurve, mc_2, FwdData));
@show "std eu"
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@show "CUDA eu"
@btime (CUDA.@sync EuPrice = pricer(Model, rfCurve, mc_2, EUData));
@show "std am"
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@show "CUDA am"
@btime (CUDA.@sync AmPrice = pricer(Model, rfCurve, mc_2, AMData));
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 788 | using BenchmarkTools
using FinancialMonteCarlo, CUDA
CUDA.allowscalar(false)
S0 = 100.0f0;
K = 100.0f0;
r = 0.02f0;
T = 1.0f0;
d = 0.01f0;
D = 90.0f0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2f0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@show "CUDA_2 fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc_2, FwdData);
@show "CUDA_2 eu"
@btime EuPrice = pricer(Model, rfCurve, mc_2, EUData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1152 | using BenchmarkTools, FinancialMonteCarlo, DualNumbers, CUDA
CUDA.allowscalar(false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 100000;
Nstep = 30;
sigma = dual(0.2, 1.0);
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
@show "CUDA_1 fwd"
@show "STD fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show "CUDA_1 fwd"
@show "CUDA_2 fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc_2, FwdData);
@show "std eu"
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@show "CUDA_1 eu"
@show "CUDA_2 eu"
@btime EuPrice = pricer(Model, rfCurve, mc_2, EUData);
@show "std am"
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@show "CUDA_1 am"
@show "CUDA_2 am"
@btime AmPrice = pricer(Model, rfCurve, mc_2, AMData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1063 | using BenchmarkTools, FinancialMonteCarlo, CUDA, ForwardDiff
CUDA.allowscalar(false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 100000;
Nstep = 30;
sigma = 0.2
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
f(x::Vector) = pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc_2, EuropeanOption(x[5], K));
x = Float64[sigma, S0, r, d, T]
g = x -> ForwardDiff.gradient(f, x);
y0 = g(x);
@btime f(x);
@btime g(x);
f_(x::Vector) = pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc_2, AmericanOption(x[5], K));
g_ = x -> ForwardDiff.gradient(f_, x);
y0 = g_(x);
@btime f_(x);
@btime g_(x);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1091 | using BenchmarkTools, FinancialMonteCarlo, CUDA, ReverseDiff
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 100000;
Nstep = 30;
sigma = 0.2
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
toll = 1e-3;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = BlackScholesProcess(sigma, Underlying(S0, d));
f(x) = pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, EuropeanOption(x[5], K), FinancialMonteCarlo.CudaMode());
x = Float64[sigma, S0, r, d, T]
g = x -> ReverseDiff.gradient(f, x);
y0 = g(x);
@btime f(x);
@btime g(x);
f_(x::Vector) = pricer(BlackScholesProcess(x[1], Underlying(x[2], x[4])), ZeroRate(x[3]), mc, AmericanOption(x[5], K), FinancialMonteCarlo.CudaMode());
g_ = x -> ReverseDiff.gradient(f_, x);
y0 = g(x);
@btime f_(x);
@btime g_(x);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1171 | using BenchmarkTools, FinancialMonteCarlo, DualNumbers, CUDA;
CUDA.allowscalar(false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
sigma_zero = 0.2;
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho = 0.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = HestonProcess(sigma, sigma_zero, lambda, kappa, rho, theta, Underlying(S0, d));
@show "STD fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show "CUDA_2 fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc_2, FwdData);
@show "std eu"
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@show "CUDA_2 eu"
@btime EuPrice = pricer(Model, rfCurve, mc_2, EUData);
@show "std am"
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@show "CUDA_2 am"
@btime AmPrice = pricer(Model, rfCurve, mc_2, AMData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1189 | using BenchmarkTools
using FinancialMonteCarlo, CUDA
CUDA.allowscalar(false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
p = 0.3;
lam = 5.0;
lamp = 30.0;
lamm = 20.0;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = KouProcess(sigma, lam, p, lamp, lamm, Underlying(S0, d));
@show "CUDA_1 fwd"
@show "STD fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show "CUDA_1 fwd"
@show "CUDA_2 fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc_2, FwdData);
@show "std eu"
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@show "CUDA_1 eu"
@show "CUDA_2 eu"
@btime EuPrice = pricer(Model, rfCurve, mc_2, EUData);
@show "std am"
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@show "CUDA_1 am"
@show "CUDA_2 am"
@btime AmPrice = pricer(Model, rfCurve, mc_2, AMData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1183 | using BenchmarkTools
using FinancialMonteCarlo, CUDA
CUDA.allowscalar(false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
lam = 5.0;
mu1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = MertonProcess(sigma, lam, mu1, sigma1, Underlying(S0, d));
@show "CUDA_1 fwd"
@show "STD fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show "CUDA_1 fwd"
@show "CUDA_2 fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc_2, FwdData);
@show "std eu"
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@show "CUDA_1 eu"
@show "CUDA_2 eu"
@btime EuPrice = pricer(Model, rfCurve, mc_2, EUData);
@show "std am"
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@show "CUDA_1 am"
@show "CUDA_2 am"
@btime AmPrice = pricer(Model, rfCurve, mc_2, AMData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1236 | using BenchmarkTools
using FinancialMonteCarlo, CUDA
CUDA.allowscalar(false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
mc = MonteCarloConfiguration(Nsim, Nstep);
mc_2 = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.CudaMode());
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = NormalInverseGaussianProcess(sigma, theta1, k1, Underlying(S0, d));
@show "CUDA_1 fwd"
@show "STD fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show "CUDA_1 fwd"
@show "CUDA_2 fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc_2, FwdData);
@show "std eu"
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@show "CUDA_1 eu"
@show "CUDA_2 eu"
@btime EuPrice = pricer(Model, rfCurve, mc_2, EUData);
@show "std am"
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@show "CUDA_1 am"
@show "CUDA_2 am"
@btime AmPrice = pricer(Model, rfCurve, mc_2, AMData);
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 942 | using BenchmarkTools
using FinancialMonteCarlo, CUDA
CUDA.allowscalar(false)
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
Nsim = 10000;
Nstep = 30;
sigma = 0.2;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
mc = MonteCarloConfiguration(Nsim, Nstep);
toll = 0.8;
rfCurve = ZeroRate(r);
FwdData = Forward(T)
EUData = EuropeanOption(T, K)
AMData = AmericanOption(T, K)
BarrierData = BarrierOptionDownOut(T, K, D)
AsianFloatingStrikeData = AsianFloatingStrikeOption(T)
AsianFixedStrikeData = AsianFixedStrikeOption(T, K)
Model = VarianceGammaProcess(sigma, theta1, k1, Underlying(S0, d));
@show "CUDA_1 fwd"
@show "STD fwd"
@btime FwdPrice = pricer(Model, rfCurve, mc, FwdData);
@show "CUDA_1 fwd"
@show "CUDA_2 fwd"
@show "std eu"
@btime EuPrice = pricer(Model, rfCurve, mc, EUData);
@show "CUDA_1 eu"
@show "CUDA_2 eu"
@show "std am"
@btime AmPrice = pricer(Model, rfCurve, mc, AMData);
@show "CUDA_1 am"
@show "CUDA_2 am"
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2659 | #Number Type (just sigma tested) ---> Model type ----> Mode ---> zero rate type
using BenchmarkTools, DualNumbers, FinancialMonteCarlo, VectorizedRNG, JLD2
rebase = true;
const sigma_dual = dual(0.2, 1.0);
const sigma_no_dual = 0.2;
suite_num = BenchmarkGroup()
const und = Underlying(100.0, 0.01);
const p = 0.3;
const lam = 5.0;
const lamp = 30.0;
const lamm = 20.0;
mu1 = 0.03;
sigma1 = 0.02;
sigma_zero = 0.2;
kappa = 0.01;
theta = 0.03;
lambda = 0.01;
rho = 0.0;
theta1 = 0.01;
k1 = 0.03;
sigma1 = 0.02;
T = 1.0;
K = 100.0;
const Nsim = 10000;
const Nstep = 30;
const std_mc = MonteCarloConfiguration(Nsim, Nstep);
const anti_mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.AntitheticMC());
const sobol_mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SobolMode());
const cv_mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.ControlVariates(Forward(T), MonteCarloConfiguration(100, 3)));
const vect_mc = MonteCarloConfiguration(Nsim, Nstep, FinancialMonteCarlo.SerialMode(), 10, local_rng());
const r = 0.02;
const r_prev = 0.019999;
lam_vec = Float64[0.999999999];
const zr_scalar = ZeroRate(r);
const zr_imp = FinancialMonteCarlo.ImpliedZeroRate([r_prev, r], 2.0);
const opt_ = EuropeanOption(T, K);
bs(sigma) = BlackScholesProcess(sigma, und)
kou(sigma) = KouProcess(sigma, lam, p, lamp, lamm, und);
hest(sigma) = HestonProcess(sigma, sigma_zero, lambda, kappa, rho, theta, und);
vg(sigma) = VarianceGammaProcess(sigma, theta1, k1, und)
merton(sigma) = MertonProcess(sigma, lambda, mu1, sigma1, und)
nig(sigma) = NormalInverseGaussianProcess(sigma, theta1, k1, und);
shift_mixture(sigma) = ShiftedLogNormalMixture([sigma, 0.2], lam_vec, 0.0, und);
for sigma in Number[sigma_no_dual, sigma_dual]
for model_ in [bs(sigma), kou(sigma), hest(sigma), vg(sigma), merton(sigma), nig(sigma), shift_mixture(sigma)]
for mode_ in [std_mc, anti_mc, sobol_mc, cv_mc, vect_mc]
for zero_ in [zr_scalar, zr_imp]
suite_num[string(typeof(sigma)), string(typeof(model_).name), string(typeof(mode_.monteCarloMethod)), string(typeof(mode_.rng)), string(typeof(zero_))] = @benchmarkable pricer($model_, $zero_, $mode_, $opt_)
end
end
end
end
#loadparams!(suite, BenchmarkTools.load("params.json")[1], :evals, :samples);
results = run(suite_num, verbose = true)
median_current = median(results);
if rebase
save_object("median_old.jld2", median_current)
end
median_old = load("median_old.jld2")["single_stored_object"]
judgement_ = judge(median_current, median_old)
[println(judgement_el.first, " ", judgement_el.second) for judgement_el in judgement_]; | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 813 | using Documenter, FinancialMonteCarlo, Literate
EXAMPLE = joinpath(@__DIR__, "..", "examples", "getting_started.jl")
OUTPUT = joinpath(@__DIR__, "src")
Literate.markdown(EXAMPLE, OUTPUT; documenter = true)
makedocs(format = Documenter.HTML(prettyurls = get(ENV, "CI", nothing) == "true", assets = ["assets/favicon.ico"], repolink = "https://gitlab.com/rcalxrc08/FinancialMonteCarlo.jl"), repo = "https://gitlab.com/rcalxrc08/FinancialMonteCarlo.jl.git", sitename = "FinancialMonteCarlo.jl", modules = [FinancialMonteCarlo], pages = ["index.md", "getting_started.md", "types.md", "stochproc.md", "parallel_vr.md", "payoffs.md", "metrics.md", "multivariate.md", "intdiffeq.md", "extends.md"])
get(ENV, "CI", nothing) == "true" ? deploydocs(repo = "https://gitlab.com/rcalxrc08/FinancialMonteCarlo.jl.git") : nothing | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1276 | # # Getting Started
#
# ## Installation
# The FinancialMonteCarlo package is available through the Julia package system
# by running `]add FinancialMonteCarlo`.
# Throughout, we assume that you have installed the package.
# ## Basic syntax
# The basic syntax for FinancialMonteCarlo is simple. Here is an example of pricing a European Option with a Black Scholes model:
using FinancialMonteCarlo
S0 = 100.0;
K = 100.0;
r = 0.02;
T = 1.0;
d = 0.01;
D = 90.0;
# Define FinancialMonteCarlo Parameters:
Nsim = 10000;
Nstep = 30;
# Define Model Parameters.
σ = 0.2;
# Build the MonteCarlo configuration and the zero rate.
mcConfig = MonteCarloConfiguration(Nsim, Nstep);
rfCurve = ZeroRate(r);
# Define The Option
EuOption = EuropeanOption(T, K)
# Define the Model of the Underlying
Model = BlackScholesProcess(σ, Underlying(S0, d));
# Call the pricer metric
@show EuPrice = pricer(Model, rfCurve, mcConfig, EuOption);
# ## Using Other Models and Options
# The package contains a large number of models of three main types:
# * `Ito Process`
# * `Jump-Diffusion Process`
# * `Infinity Activity Process`
# And the following types of options:
# * `European Options`
# * `Asian Options`
# * `Barrier Options`
# * `American Options`
# The usage is analogous to the above example. | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1070 | __precompile__()
module FinancialMonteCarlo
using Requires # for conditional dependencies
using Random # for randn! and related
using LinearAlgebra # for Longstaff Schwartz
using Accessors # setting fields
using ChainRulesCore
function __init__()
@require CUDA = "052768ef-5323-5732-b1bb-66c8b64840ba" include("deps/cuda_dependencies.cujl")
@require DifferentialEquations = "0c46a032-eb83-5123-abaf-570d42b7fbaa" include("deps/diffeq_dependencies.jl")
@require VectorizedRNG = "33b4df10-0173-11e9-2a0c-851a7edac40e" include("deps/vectorizedrng_dependencies.jl")
@require Distributed = "8ba89e20-285c-5b6f-9357-94700520ee1b" include("deps/distributed_dependencies.jl")
@require TaylorSeries = "6aa5eb33-94cf-58f4-a9d0-e4b2c4fc25ea" include("deps/taylorseries_dependencies.jl")
end
include("utils.jl")
include("models.jl")
include("options.jl")
include("io_utils.jl")
include("operations.jl")
include("metrics.jl")
include("output_type.jl")
include("multi_threading.jl")
export pricer, variance, confinter, delta, simulate, payoff, →
end#End Module
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3935 | ############### Display Function
import Base.Multimedia.display;
import Base.Multimedia.print;
function print(p::Union{AbstractMonteCarloProcess, AbstractPayoff})
fldnames = collect(fieldnames(typeof(p)))
Base.print(typeof(p), "(")
if (length(fldnames) > 0)
Base.print(fldnames[1], "=", getfield(p, fldnames[1]))
popfirst!(fldnames)
for name in fldnames
Base.print(",", name, "=", getfield(p, name))
end
end
print(")")
end
function display(p::Union{AbstractMonteCarloProcess, AbstractPayoff})
fldnames = collect(fieldnames(typeof(p)))
Base.print(typeof(p), "(")
if (length(fldnames) > 0)
Base.print(fldnames[1], "=", getfield(p, fldnames[1]))
popfirst!(fldnames)
for name in fldnames
Base.print(",", name, "=", getfield(p, name))
end
end
println(")")
end
# Agnostic getters and setters, useful for testing and calibration
function get_parameters(model::XProcess) where {XProcess <: AbstractPayoff}
fields_ = fieldnames(XProcess)
N1 = length(fields_)
param_ = []
for i = 1:N1
tmp_ = getproperty(model, fields_[i])
append!(param_, tmp_)
end
if (N1 > 0)
typecheck_ = typeof(sum(param_) + prod(param_))
param_ = convert(Array{typecheck_}, param_)
end
return param_
end
function get_parameters(model::XProcess) where {XProcess <: BaseProcess}
fields_ = fieldnames(XProcess)
N1 = length(fields_)
param_ = []
for i = 1:N1
tmp_ = getproperty(model, fields_[i])
typeof(tmp_) <: AbstractUnderlying ? continue : nothing
append!(param_, tmp_)
end
typecheck_ = typeof(sum(param_) + prod(param_))
param_ = convert(Array{typecheck_}, param_)
return param_
end
function get_parameters(model::XProcess) where {XProcess <: VectorialMonteCarloProcess}
fields_ = fieldnames(XProcess)
N1 = length(fields_)
param_ = []
for i = 1:N1
tmp_ = getproperty(model, fields_[i])
typeof(tmp_) <: Tuple ? continue : nothing
append!(param_, tmp_)
end
typecheck_ = typeof(sum(param_) + prod(param_))
param_ = convert(Array{typecheck_}, param_)
return param_
end
function set_parameters!(model::XProcess, param::Array{num}) where {XProcess <: BaseProcess, num <: Number}
fields_ = fieldnames(XProcess)
N1 = length(fields_) - 1
ChainRulesCore.@ignore_derivatives @assert N1 == length(param) "Check number of parameters of the model"
for (symb, nval) in zip(fields_, param)
if (symb != :underlying)
new_lens = PropertyLens{symb}()
model = Accessors.set(model, new_lens, nval)
end
end
return model
end
function set_parameters!(model::LogNormalMixture, param::Array{num}) where {num <: Number}
N1 = div(length(param) + 1, 2)
ChainRulesCore.@ignore_derivatives @assert !(N1 * 2 != length(param) + 1 || N1 < 2) "Check number of parameters of the model"
eta = param[1:N1]
lam = param[(N1+1):end]
fields_ = fieldnames(LogNormalMixture)
# setproperty!(model, fields_[1], eta)
model = Accessors.set(model, PropertyLens{fields_[1]}(), eta)
model = Accessors.set(model, PropertyLens{fields_[2]}(), lam)
# setproperty!(model, fields_[2], lam)
return model
end
function set_parameters!(model::ShiftedLogNormalMixture, param::Array{num}) where {num <: Number}
N1 = div(length(param), 2)
ChainRulesCore.@ignore_derivatives @assert !(N1 * 2 != length(param) || N1 < 2) "Check number of parameters of the model"
eta = param[1:N1]
lam = param[(N1+1):(2*N1-1)]
alfa = param[end]
fields_ = fieldnames(ShiftedLogNormalMixture)
model = Accessors.set(model, PropertyLens{fields_[1]}(), eta)
model = Accessors.set(model, PropertyLens{fields_[2]}(), lam)
model = Accessors.set(model, PropertyLens{fields_[3]}(), alfa)
return model
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 243 | include("metrics/seed.jl")
include("metrics/pricer.jl")
include("metrics/pricer_cv.jl")
include("metrics/distribution.jl")
include("metrics/delta.jl")
include("metrics/rho.jl")
include("metrics/confinterval.jl")
include("metrics/variance.jl")
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 61 | include("models/base_models.jl")
include("models/models.jl")
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2944 | abstract type AbstractMultiThreading <: ParallelMode end
struct MultiThreading{abstractMode <: BaseMode} <: AbstractMultiThreading
numberOfBatch::Int64
sub_mod::abstractMode
seeds::Array{Int64}
function MultiThreading(sub_mod::abstractMode = SerialMode(), numberOfBatch::Int64 = Int64(Threads.nthreads()), seeds::Array{Int64} = collect(1:Threads.nthreads())) where {abstractMode <: BaseMode}
ChainRulesCore.@ignore_derivatives @assert length(seeds) == numberOfBatch
return new{abstractMode}(numberOfBatch, sub_mod, seeds)
end
end
function pricer_macro_multithreading(model_type, payoff_type)
@eval begin
function pricer(mcProcess::$model_type, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:AbstractMultiThreading}, abstractPayoff::$payoff_type)
zero_typed = predict_output_type_zero(mcProcess, rfCurve, mcConfig, abstractPayoff)
numberOfBatch = mcConfig.parallelMode.numberOfBatch
price = zeros(typeof(zero_typed), numberOfBatch)
Threads.@threads for i = 1:numberOfBatch
mc_config_i = MonteCarloConfiguration(div(mcConfig.Nsim, numberOfBatch), mcConfig.Nstep, mcConfig.monteCarloMethod, mcConfig.parallelMode.sub_mod)
mc_config_i = @views @set mc_config_i.parallelMode.seed = mcConfig.parallelMode.seeds[i]
@views price[i] = pricer(mcProcess, rfCurve, mc_config_i, abstractPayoff)
end
Out = sum(price) / numberOfBatch
return Out
end
end
end
pricer_macro_multithreading(BaseProcess, AbstractPayoff)
pricer_macro_multithreading(BaseProcess, Dict{AbstractPayoff, Number})
pricer_macro_multithreading(Dict{String, AbstractMonteCarloProcess}, Dict{String, Dict{AbstractPayoff, Number}})
pricer_macro_multithreading(VectorialMonteCarloProcess, Array{Dict{AbstractPayoff, Number}})
function pricer(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:AbstractMultiThreading}, abstractPayoffs::Array{abstractPayoff_}) where {abstractPayoff_ <: AbstractPayoff}
zero_typed = predict_output_type_zero(mcProcess, rfCurve, mcConfig, abstractPayoffs)
numberOfBatch = mcConfig.parallelMode.numberOfBatch
price = zeros(typeof(zero_typed), length(abstractPayoffs), numberOfBatch)
mc_configs = [MonteCarloConfiguration(div(mcConfig.Nsim, numberOfBatch), mcConfig.Nstep, mcConfig.monteCarloMethod, mcConfig.parallelMode.sub_mod) for _ = 1:numberOfBatch]
for i = 1:numberOfBatch
mc_configs[i] = @views @set mc_configs[i].parallelMode.seed = mcConfig.parallelMode.seeds[i]
end
Threads.@threads for i = 1:numberOfBatch
price[:, i] = pricer(mcProcess, rfCurve, mc_configs[i], abstractPayoffs)
end
Out = sum(price, dims = 2) / numberOfBatch
return Out
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 131 | ### Operations and Strategies
include("operations/models.jl")
include("operations/options.jl")
include("operations/portfolios.jl")
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 124 | ### Operations and Strategies
include("options/payoff_base.jl")
include("options/engines.jl")
include("options/payoffs.jl")
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1765 |
function predict_output_type_zero(x...)::Number
zero_out_ = sum(y -> predict_output_type_zero(y), x)
return zero_out_
end
function predict_output_type_zero(x::abstractArray)::Number where {abstractArray <: AbstractArray{T}} where {T}
zero_out_ = sum(y -> predict_output_type_zero(y), x)
return zero_out_
end
function predict_output_type_zero(::num)::num where {num <: Number}
return zero(num)
end
function predict_output_type_zero(und::AbstractUnderlying)::Number
return predict_output_type_zero(und.S0) + predict_output_type_zero(und.d)
end
function predict_output_type_zero(::CurveType{num1, num2})::Number where {num1 <: Number, num2 <: Number}
return zero(num1) + zero(num2)
end
function predict_output_type_zero(rfCurve::AbstractZeroRateCurve)::Number
return predict_output_type_zero(rfCurve.r)
end
function predict_output_type_zero(::Any)::Int8
zero(Int8)
end
function predict_output_type_zero(::Spot)::Int8
return zero(Int8)
end
function predict_output_type_zero(::basePayoff) where {basePayoff <: AbstractPayoff{num}} where {num <: Number}
return zero(num)
end
function predict_output_type_zero(x::baseProcess) where {baseProcess <: ScalarMonteCarloProcess{num}} where {num <: Number}
return zero(num) + predict_output_type_zero(x.underlying)
end
function predict_output_type_zero(::baseProcess) where {baseProcess <: AbstractMonteCarloEngine{num}} where {num <: Number}
return zero(num)
end
function predict_output_type_zero(::baseProcess) where {baseProcess <: VectorialMonteCarloProcess{num}} where {num <: Number}
return zero(num)
end
##Vectorization "utils"
Base.broadcastable(x::Union{BaseProcess, AbstractZeroRateCurve, AbstractPayoff, AbstractMonteCarloConfiguration}) = Ref(x)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 242 | include("utils/curves.jl")
include("utils/dict_utils.jl")
include("utils/rng_number.jl")
include("utils/zero_rates.jl")
include("utils/mc_mode.jl")
include("utils/mc_config.jl")
include("utils/sim_result.jl")
include("utils/underlying.jl")
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2246 | abstract type AbstractCudaMode <: ParallelMode end
# struct CudaMode <: AbstractCudaMode end
struct CudaMode{rngType <: Random.AbstractRNG} <: AbstractCudaMode
seed_cpu::Int64
seed_gpu::Int64
rng::rngType
function CudaMode(seed_cpu::num = 0, seed_gpu::num2 = 0, rng::rngType = MersenneTwister()) where {num <: Integer, num2 <: Integer, rngType <: Random.AbstractRNG}
return new{rngType}(Int64(seed_cpu), Int64(seed_gpu), rng)
end
end
CudaMonteCarloConfig = MonteCarloConfiguration{num1, num2, num3, ser_mode} where {num1 <: Integer, num2 <: Integer, num3 <: FinancialMonteCarlo.StandardMC, ser_mode <: FinancialMonteCarlo.CudaMode{rng_}} where {rng_ <: Random.AbstractRNG}
CudaAntitheticMonteCarloConfig = MonteCarloConfiguration{num1, num2, num3, ser_mode} where {num1 <: Integer, num2 <: Integer, num3 <: FinancialMonteCarlo.AntitheticMC, ser_mode <: FinancialMonteCarlo.CudaMode{rng_}} where {rng_ <: Random.AbstractRNG}
using .CUDA
include("../models/cuda/cuda_models.jl")
function set_seed!(mcConfig::MonteCarloConfiguration{type1, type2, type3, type4}) where {type1 <: Integer, type2 <: Integer, type3 <: AbstractMonteCarloMethod, type4 <: AbstractCudaMode}
if mcConfig.init_rng
inner_seed!(mcConfig.parallelMode.rng, mcConfig.parallelMode.seed_cpu)
CUDA.CURAND.seed!(mcConfig.parallelMode.seed_gpu)
end
end
get_matrix_type(mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:AbstractCudaMode}, ::BaseProcess, price) = CuMatrix{typeof(price)}(undef, mcConfig.Nsim, mcConfig.Nstep + 1);
get_array_type(mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:AbstractCudaMode}, ::BaseProcess, price) = CuArray{typeof(price)}(undef, mcConfig.Nsim);
get_matrix_type(::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:AbstractCudaMode}, ::VectorialMonteCarloProcess, price) = Array{CuMatrix{typeof(price)}};
function payoff(S::CuMatrix{num}, payoff_::PathDependentPayoff, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T1::num2 = maturity(payoff_)) where {num <: Number, num2 <: Number}
S_ = collect(S)
return payoff(S_, payoff_, rfCurve, mcBaseData, T1)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 204 | using .DifferentialEquations
include("../models/diff_eq_monte_carlo.jl")
function predict_output_type_zero(::absdiffeqmodel) where {absdiffeqmodel <: MonteCarloDiffEqModel}
return zero(Float64)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2643 | using .Distributed
abstract type AbstractMultiProcess <: ParallelMode end
struct MultiProcess{abstractMode <: BaseMode} <: AbstractMultiProcess
nbatches::Int64
sub_mod::abstractMode
seeds::Array{Int64}
function MultiProcess(sub_mod::abstractMode = SerialMode(), nbatches::Int64 = Int64(nworkers()), seeds::Array{Int64} = collect(1:nbatches)) where {abstractMode <: BaseMode}
ChainRulesCore.@ignore_derivatives @assert length(seeds) == nbatches
return new{abstractMode}(nbatches, sub_mod, seeds)
end
end
function pricer_macro_multiprocesses(model_type, payoff_type)
@eval begin
function pricer(mcProcess::$model_type, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:MultiProcess}, abstractPayoff::$payoff_type)
zero_typed = predict_output_type_zero(mcProcess, rfCurve, mcConfig, abstractPayoff)
nbatches = mcConfig.parallelMode.nbatches
mc_configs = [MonteCarloConfiguration(div(mcConfig.Nsim, nbatches), mcConfig.Nstep, mcConfig.monteCarloMethod, mcConfig.parallelMode.sub_mod) for _ = 1:nbatches]
for i = 1:nbatches
@set mc_configs[i].parallelMode.seed = mcConfig.parallelMode.seeds[i]
end
price::typeof(zero_typed) = @sync @distributed (+) for i = 1:nbatches
pricer(mcProcess, rfCurve, mc_configs[i], abstractPayoff)::typeof(zero_typed)
end
Out = price / nbatches
return Out
end
end
end
pricer_macro_multiprocesses(BaseProcess, AbstractPayoff)
pricer_macro_multiprocesses(BaseProcess, Dict{AbstractPayoff, Number})
pricer_macro_multiprocesses(Dict{String, AbstractMonteCarloProcess}, Dict{String, Dict{AbstractPayoff, Number}})
pricer_macro_multiprocesses(VectorialMonteCarloProcess, Array{Dict{AbstractPayoff, Number}})
function pricer(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:MultiProcess}, abstractPayoffs::Array{abstractPayoff_}) where {abstractPayoff_ <: AbstractPayoff}
nbatches = mcConfig.parallelMode.nbatches
mc_configs = [MonteCarloConfiguration(div(mcConfig.Nsim, nbatches), mcConfig.Nstep, mcConfig.monteCarloMethod, mcConfig.parallelMode.sub_mod) for _ = 1:nbatches]
for i = 1:nbatches
@set mc_configs[i].parallelMode.seed = mcConfig.parallelMode.seeds[i]
end
price = @distributed (+) for i = 1:nbatches
pricer(mcProcess, rfCurve, mc_configs[i], abstractPayoffs)
end
Out = price ./ nbatches
return Out
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1274 | using .TaylorSeries
import Base.max,Base.min,Base.isless
value_taylor(x::Taylor1)=@inbounds @views x[0];
value_taylor(x::AbstractSeries)=@inbounds @views x[0][1];
!hasmethod(max,(AbstractSeries,Number)) ? (max(x::AbstractSeries,t::Number)=ifelse(value_taylor(x)>=t,x,t)) : nothing
!hasmethod(max,(Number,AbstractSeries)) ? (max(t::Number,x::AbstractSeries)=max(x,t)) : nothing
!hasmethod(max,(AbstractSeries,AbstractSeries)) ? (max(x::AbstractSeries,t::AbstractSeries)=ifelse(value_taylor(x)>value_taylor(t),x,t)) : nothing
!hasmethod(min,(AbstractSeries,Number)) ? (max(x::AbstractSeries,t::Number)=ifelse(value_taylor(x)<=t,x,t)) : nothing
!hasmethod(min,(Number,AbstractSeries)) ? (max(t::Number,x::AbstractSeries)=min(x,t)) : nothing
!hasmethod(min,(AbstractSeries,AbstractSeries)) ? (max(x::AbstractSeries,t::AbstractSeries)=ifelse(value_taylor(x)<value_taylor(t),x,t)) : nothing
!hasmethod(isless,(AbstractSeries,Number)) ? (isless(x::AbstractSeries,t::Number)=isless(value_taylor(x),t)) : nothing
!hasmethod(isless,(Number,AbstractSeries)) ? (isless(t::Number, x::AbstractSeries)=isless(t,value_taylor(x))) : nothing
!hasmethod(isless,(AbstractSeries,AbstractSeries)) ? (isless(x::AbstractSeries,t::AbstractSeries)=isless(value_taylor(x),value_taylor(t))) : nothing
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 102 | using .VectorizedRNG
inner_seed!(tmp_rng::VectorizedRNG.AbstractVRNG,seed)= VectorizedRNG.seed!(seed); | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1928 | using Distributions
"""
General Interface for Computation of confidence interval of price
IC=confinter(mcProcess,rfCurve,mcConfig,abstractPayoff,alpha)
Where:\n
mcProcess = Process to be simulated.
rfCurve = Zero Rate Data.
mcConfig = Basic properties of MonteCarlo simulation
abstractPayoff = Payoff(s) to be priced
alpha = confidence level [Optional, default to 99%]
Price = Price of the derivative
"""
function confinter(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoff::AbstractPayoff, alpha::Real = 0.99)
set_seed!(mcConfig)
T = maturity(abstractPayoff)
Nsim = mcConfig.Nsim
S = simulate(mcProcess, rfCurve, mcConfig, T)
Payoff = payoff(S, abstractPayoff, rfCurve, mcConfig)
mean1 = mean(Payoff)
var1 = var(Payoff)
alpha_ = 1 - alpha
dist1 = Distributions.TDist(Nsim)
tstar = quantile(dist1, 1 - alpha_ / 2.0)
IC = (mean1 - tstar * sqrt(var1) / Nsim, mean1 + tstar * sqrt(var1) / Nsim)
return IC
end
function confinter(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoffs::Array{abstractPayoff_}, alpha::Real = 0.99) where {abstractPayoff_ <: AbstractPayoff}
set_seed!(mcConfig)
maxT = maximum([maturity(abstractPayoff) for abstractPayoff in abstractPayoffs])
Nsim = mcConfig.Nsim
S = simulate(mcProcess, rfCurve, mcConfig, maxT)
Means = [mean(payoff(S, abstractPayoff, rfCurve, mcConfig, maxT)) for abstractPayoff in abstractPayoffs]
Vars = [var(payoff(S, abstractPayoff, rfCurve, mcConfig, maxT)) for abstractPayoff in abstractPayoffs]
alpha_ = 1 - alpha
dist1 = Distributions.TDist(Nsim)
tstar = quantile(dist1, 1 - alpha_ / 2.0)
IC = [(mean1 - tstar * sqrt(var1) / Nsim, mean1 + tstar * sqrt(var1) / Nsim) for (mean1, var1) in zip(Means, Vars)]
return IC
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3521 | """
General Interface for Delta
Delta=delta(mcProcess,rfCurve,mcConfig,abstractPayoff,dS0)
Where:\n
mcProcess = Process to be simulated.
rfCurve = Zero Rate Data.
mcConfig = Basic properties of MonteCarlo simulation
abstractPayoff = Payoff(s) to be priced
dS0 = increment [optional, default to 1e-7]
Delta = Delta of the derivative
"""
function delta(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoff::AbstractPayoff, dS0::Real = 1e-7)
Price = pricer(mcProcess, rfCurve, mcConfig, abstractPayoff)
mcProcess_up = @set mcProcess.underlying.S0 += dS0
set_seed!(mcConfig)
PriceUp = pricer(mcProcess_up, rfCurve, mcConfig, abstractPayoff)
Delta = (PriceUp - Price) / dS0
return Delta
end
function delta(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoffs::Array{abstractPayoff}, dS0::Real = 1e-7) where {abstractPayoff <: AbstractPayoff}
Prices = pricer(mcProcess, rfCurve, mcConfig, abstractPayoffs)
mcProcess_up = @set mcProcess.underlying.S0 += dS0
PricesUp = pricer(mcProcess_up, rfCurve, mcConfig, abstractPayoffs)
Delta = @. (PricesUp - Prices) / dS0
return Delta
end
function delta(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoffs::Dict{AbstractPayoff, Number}, dS0::Real = 1e-7)
Prices = pricer(mcProcess, rfCurve, mcConfig, abstractPayoffs)
mcProcess_up = @set mcProcess.underlying.S0 += dS0
set_seed!(mcConfig)
PricesUp = pricer(mcProcess_up, rfCurve, mcConfig, abstractPayoffs)
Delta = @. (PricesUp - Prices) / dS0
return Delta
end
function delta(mcProcess::Dict{String, AbstractMonteCarloProcess}, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, dict_::Dict{String, Dict{AbstractPayoff, Number}}, underl_::String, dS::Real = 1e-7)
ChainRulesCore.@ignore_derivatives @assert isnothing(findfirst("_", underl_)) "deltas are defined on single name"
set_seed!(mcConfig)
price0 = pricer(mcProcess, rfCurve, mcConfig, dict_)
price2 = 0.0
set_seed!(mcConfig)
mcProcess_up = deepcopy(mcProcess)
keys_mkt = collect(keys(mcProcess_up))
idx_supp = 0
idx_1 = findfirst(y -> y == underl_, keys_mkt)
if (isnothing(idx_1))
idx_1 = findfirst(out_el -> any(out_el_sub -> out_el_sub == underl_, split(out_el, "_")), keys_mkt)
if (isnothing(idx_1))
return 0.0
end
multi_name = keys_mkt[idx_1]
idx_supp = findfirst(x_ -> x_ == underl_, split(multi_name, "_"))
model_ = mcProcess_up[multi_name]
ok_m = model_.models[idx_supp]
ok_m = @set ok_m.underlying.S0 += dS
# model_.models[idx_supp].underlying.S0 += dS
models_ = model_.models
new_models = @set models_[idx_supp] = ok_m
new_model = @set model_.models = new_models
delete!(mcProcess_up, multi_name)
tmp_mkt = multi_name → new_model
mcProcess_up = mcProcess_up + tmp_mkt
price2 = pricer(mcProcess_up, rfCurve, mcConfig, dict_)
else
model = mcProcess_up[keys_mkt[idx_1]]
model_up = @set model.underlying.S0 += dS
delete!(mcProcess_up, keys_mkt[idx_1])
tmp_mkt = keys_mkt[idx_1] → model_up
mcProcess_up = mcProcess_up + tmp_mkt
price2 = pricer(mcProcess_up, rfCurve, mcConfig, dict_)
end
return (price2 - price0) / dS
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 540 | """
General Interface for distribution
S=distribution(mcProcess,rfCurve,mcConfig,payoff_)
Where:\n
mcProcess = Process to be simulated.
rfCurve = Zero Rate Data.
mcConfig = Basic properties of MonteCarlo simulation
T = Time of simulation
S = distribution
"""
function distribution(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, T::num_) where {num_ <: Number}
set_seed!(mcConfig)
S = simulate(mcProcess, rfCurve, mcConfig, T)
return S[:, end]
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3813 | include("utils.jl")
"""
Low Level Interface for Pricing
Price=pricer(mcProcess,rfCurve,mcConfig,abstractPayoff)
Where:
mcProcess = Process to be simulated.
rfCurve = Zero Rate Data.
mcConfig = Basic properties of MonteCarlo simulation
abstractPayoff = Payoff(s) to be priced
Price = Price of the derivative
"""
function pricer(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::AbstractMonteCarloConfiguration, abstractPayoff::AbstractPayoff)
set_seed!(mcConfig)
T = maturity(abstractPayoff)
S = simulate(mcProcess, rfCurve, mcConfig, T)
Payoff = payoff(S, abstractPayoff, rfCurve, mcConfig)
Price = mean(Payoff)
return Price
end
get_matrix_type(mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:BaseMode}, ::BaseProcess, price) = Matrix{typeof(price)}(undef, mcConfig.Nsim, mcConfig.Nstep + 1);
get_array_type(mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:BaseMode}, ::BaseProcess, price) = Array{typeof(price)}(undef, mcConfig.Nstep);
get_matrix_type(::MonteCarloConfiguration{<:Integer, <:Integer, <:AbstractMonteCarloMethod, <:BaseMode}, ::VectorialMonteCarloProcess, price) = Array{Matrix{typeof(price)}};
function pricer(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoffs::Array{abstractPayoff_}) where {abstractPayoff_ <: AbstractPayoff}
set_seed!(mcConfig)
maxT = maximum(maturity.(abstractPayoffs))
S = simulate(mcProcess, rfCurve, mcConfig, maxT)
zero_typed = predict_output_type_zero(mcProcess, rfCurve, mcConfig, abstractPayoffs)
Prices::Array{typeof(zero_typed)} = [mean(payoff(S, abstractPayoff, rfCurve, mcConfig, maxT)) for abstractPayoff in abstractPayoffs]
return Prices
end
function pricer(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, dict_::Position)
set_seed!(mcConfig)
abstractPayoffs = keys(dict_)
maxT = maximum([maturity(abstractPayoff) for abstractPayoff in abstractPayoffs])
S = simulate(mcProcess, rfCurve, mcConfig, maxT)
price = sum(weight_ * mean(payoff(S, abstractPayoff, rfCurve, mcConfig, maxT)) for (abstractPayoff, weight_) in dict_)
return price
end
#####Pricer for multivariate
function pricer(mcProcess::VectorialMonteCarloProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, special_array_payoff::Array{Position})
set_seed!(mcConfig)
N_ = length(mcProcess.models)
idx_ = compute_indices(N_)
## Filter special_array_payoff for undef
IND_ = collect(1:length(special_array_payoff))
filter!(i -> isassigned(special_array_payoff, i), IND_)
dict_cl = special_array_payoff[IND_]
#Compute Maximum time to maturity, all of the underlyings will be simulated till maxT.
maxT = maximum([maximum(maturity.(collect(keys(ar_el)))) for ar_el in dict_cl])
S = simulate(mcProcess, rfCurve, mcConfig, maxT)
price = sum(sum(weight_ * mean(payoff(S[idx_[i]], abstractPayoff, rfCurve, mcConfig, maxT)) for (abstractPayoff, weight_) in special_array_payoff[i]) for i in IND_)
return price
end
function pricer(mcProcess::MarketDataSet, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, dict_::Portfolio)
set_seed!(mcConfig)
underlyings_payoff = keys(dict_)
underlyings_payoff_cpl = get_underlyings_identifier(underlyings_payoff, keys(mcProcess))
zero_typed = predict_output_type_zero(rfCurve, mcConfig, collect(keys(collect(values(dict_)))), collect(values(mcProcess)))
price::typeof(zero_typed) = sum(pricer(mcProcess[under_cpl], rfCurve, mcConfig, extract_option_from_portfolio(under_cpl, dict_)) for under_cpl in unique(underlyings_payoff_cpl))
return price
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2401 | function pricer(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:ControlVariates, <:BaseMode}, abstractPayoff::AbstractPayoff)
set_seed!(mcConfig)
variate_handl = mcConfig.monteCarloMethod
variate_conf = variate_handl.conf_variate
variate_payoff = variate_handl.variate
ChainRulesCore.@ignore_derivatives @assert maturity(abstractPayoff) == variate_payoff.T
T = maturity(abstractPayoff)
S_var = simulate(mcProcess, rfCurve, variate_conf, T)
Payoff_var = payoff(S_var, variate_payoff, rfCurve, variate_conf)
Payoff_opt_var = payoff(S_var, abstractPayoff, rfCurve, variate_conf)
#c=-cov(Payoff_var,Payoff_opt_var)/var(Payoff_var)[1];
c = -collect(cov(Payoff_var, Payoff_opt_var) / var(Payoff_var))[1]
price_var = mean(Payoff_var)
mcConfig_mod = MonteCarloConfiguration(mcConfig.Nsim, mcConfig.Nstep, variate_handl.curr_method, mcConfig.parallelMode)
#END OF VARIATE SECTION
Prices = pricer(mcProcess, rfCurve, mcConfig_mod, [abstractPayoff, variate_payoff])
Price = Prices[1] + c * (Prices[2] - price_var)
return Price
end
function pricer(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration{<:Integer, <:Integer, <:ControlVariates{Forward{num}, <:AbstractMonteCarloConfiguration, <:AbstractMonteCarloMethod}, <:BaseMode}, abstractPayoff::AbstractPayoff) where {num <: Number}
set_seed!(mcConfig)
variate_handl = mcConfig.monteCarloMethod
variate_conf = variate_handl.conf_variate
variate_payoff = variate_handl.variate
ChainRulesCore.@ignore_derivatives @assert maturity(abstractPayoff) == variate_payoff.T
T = maturity(abstractPayoff)
S_var = simulate(mcProcess, rfCurve, variate_conf, T)
Payoff_var = payoff(S_var, variate_payoff, rfCurve, variate_conf)
Payoff_opt_var = payoff(S_var, abstractPayoff, rfCurve, variate_conf)
c = -collect(cov(Payoff_var, Payoff_opt_var) / var(Payoff_var))[1]
price_var = mcProcess.underlying.S0 * exp(-integral(mcProcess.underlying.d, T))
mcConfig_mod = MonteCarloConfiguration(mcConfig.Nsim, mcConfig.Nstep, variate_handl.curr_method, mcConfig.parallelMode)
#END OF VARIATE SECTION
Prices = pricer(mcProcess, rfCurve, mcConfig_mod, [abstractPayoff, variate_payoff])
Price = Prices[1] - c * (Prices[2] - price_var)
return Price
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1231 | """
General Interface for Rho computation
Rho=rho(mcProcess,rfCurve,mcConfig,abstractPayoff,dr)
Where:
mcProcess = Process to be simulated.
rfCurve = Zero Rate Data.
mcConfig = Basic properties of MonteCarlo simulation
abstractPayoff = Payoff(s) to be priced
dr = increment [optional, default to 1e-7]
Rho = Rho of the derivative
"""
function rho(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoff::AbstractPayoff, dr::Real = 1e-7)
Price = pricer(mcProcess, rfCurve, mcConfig, abstractPayoff)
rfCurve_1 = ZeroRate(rfCurve.r + dr)
PriceUp = pricer(mcProcess, rfCurve_1, mcConfig, abstractPayoff)
rho = (PriceUp - Price) / dr
return rho
end
function rho(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoffs::Array{abstractPayoff_}, dr::Real = 1e-7) where {abstractPayoff_ <: AbstractPayoff}
Prices = pricer(mcProcess, rfCurve, mcConfig, abstractPayoffs)
rfCurve_1 = ZeroRate(rfCurve.r + dr)
PricesUp = pricer(mcProcess, rfCurve_1, mcConfig, abstractPayoffs)
rho = @. (PricesUp - Prices) / dr
return rho
end
export rho;
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 343 | inner_seed!(rng, seed) = Random.seed!(rng, seed)
function set_seed!(mcConfig::MonteCarloConfiguration{type1, type2, type3, type4}) where {type1 <: Integer, type2 <: Integer, type3 <: AbstractMonteCarloMethod, type4 <: SerialMode}
if mcConfig.init_rng
inner_seed!(mcConfig.parallelMode.rng, mcConfig.parallelMode.seed)
end
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2052 | using IterTools
#My implementation of lexicographic less function, not sure if it is the most performant but it works
function lex_less(x, y)
if (length(x) != length(y))
return length(y) > length(x)
else
x_s = sort(x)
y_s = sort(y)
for i = 1:length(x)
if (x_s[i] != y_s[i])
return y_s[i] > x_s[i]
end
end
end
end
#This function solves the vectorial problem:
#Multi dimensional models have no clue of the name of the underlying process and no clue of the name of themselves,
#A pricer implemented for a multidimensional model with a single name option makes little sense since there his no
#way to map the option to the right underlying.
#In order to solve this problem the pricer is implemented in a strange way:
#A vector of integer is computed in the following way:
#Assuming 3 underlyings
#1st element ---> option referred to model[1]
#2nd element ---> option referred to model[2]
#3rd element ---> option referred to model[3]
#4th element ---> option referred to (model[1],model[2])
#5th element ---> option referred to (model[1],model[3])
#6th element ---> option referred to (model[2],model[3])
#7th element ---> option referred to (model[1],model[2],model[3])
function compute_indices(x::Integer)
X = collect(1:x)
#Subsets will return the empty set as well
f(y) = filter(x -> !(length(x) == 0), y)
k = subsets(X) |> collect |> f
out = sort(k, lt = (x, y) -> lex_less(x, y))
return out
end
#Following function returns the names (duplicated as well) of the underlying names that must simulate.
#An underlying to be simulated must have an option in the portfolio that is referred to it (directly or in a basket).
function get_underlyings_identifier(payoffs_underlyings, models_underlyings)
out = String[]
for x_ in payoffs_underlyings
for y_ in models_underlyings
if (any(z -> z == x_, split(y_, "_")) || y_ == x_)
push!(out, y_)
end
end
end
return out
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1244 | """
General Interface for Computation of variance interval of price
variance_=variance(mcProcess,rfCurve,mcConfig,abstractPayoff)
Where:\n
mcProcess = Process to be simulated.
rfCurve = Zero Rate Data.
mcConfig = Basic properties of MonteCarlo simulation
abstractPayoff = Payoff(s) to be priced
variance_ = variance of the payoff of the derivative
"""
function variance(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoff::AbstractPayoff)
set_seed!(mcConfig)
T = maturity(abstractPayoff)
S = simulate(mcProcess, rfCurve, mcConfig, T)
Payoff = payoff(S, abstractPayoff, rfCurve, mcConfig)
variance_ = var(Payoff)
return variance_
end
function variance(mcProcess::BaseProcess, rfCurve::AbstractZeroRateCurve, mcConfig::MonteCarloConfiguration, abstractPayoffs::Array{abstractPayoff_}) where {abstractPayoff_ <: AbstractPayoff}
set_seed!(mcConfig)
maxT = maximum([maturity(abstractPayoff) for abstractPayoff in abstractPayoffs])
S = simulate(mcProcess, rfCurve, mcConfig, maxT)
variance_ = [var(payoff(S, abstractPayoff, rfCurve, mcConfig, maxT)) for abstractPayoff in abstractPayoffs]
return variance_
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 4130 | # The following contains just abstract types regarding models and "virtual" method
#The most basic type, needed in order to support DifferentialEquations.jl
abstract type BaseProcess{T <: Number} end
# There will inherit from this type just processes, i.e. models that know what is a zeroCurve and a divided
abstract type AbstractMonteCarloProcess{T <: Number} <: BaseProcess{T} end
# Just engines will inherit from this, Brownian Motion et al.
abstract type AbstractMonteCarloEngine{T <: Number} <: BaseProcess{T} end
# Abstract type representing scalar montecarlo processes
abstract type ScalarMonteCarloProcess{T <: Number} <: AbstractMonteCarloProcess{T} end
# Abstract type representing multi dimensional montecarlo processes
abstract type VectorialMonteCarloProcess{T <: Number} <: AbstractMonteCarloProcess{T} end
# Abstract type representing N dimensional montecarlo processes (??)
abstract type NDimensionalMonteCarloProcess{T <: Number} <: VectorialMonteCarloProcess{T} end
# Abstract type for Levy (useful in FinancialFFT.jl)
abstract type LevyProcess{T <: Number} <: ScalarMonteCarloProcess{T} end
# Abstract type for Ito, an Ito process is always a Levy
abstract type ItoProcess{T <: Number} <: LevyProcess{T} end
# Abstract type for FA processes
abstract type FiniteActivityProcess{T <: Number} <: LevyProcess{T} end
# Abstract type for IA processes
abstract type InfiniteActivityProcess{T <: Number} <: LevyProcess{T} end
# Utility for dividends (implemented just for mono dimensional processes)
dividend(x::mc) where {mc <: ScalarMonteCarloProcess} = x.underlying.d;
"""
General Interface for Stochastic Process simulation
S=simulate(mcProcess,zeroCurve,mcBaseData,T)
Where:
mcProcess = Process to be simulated.
zeroCurve = Datas of the Zero Rate Curve.
mcBaseData = Basic properties of MonteCarlo simulation
T = Final time of the process
S = Matrix with path of underlying.
"""
function simulate(mcProcess::AbstractMonteCarloProcess, zeroCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
price_type = predict_output_type_zero(mcProcess, zeroCurve, mcBaseData, T)
S = get_matrix_type(mcBaseData, mcProcess, price_type)
simulate!(S, mcProcess, zeroCurve, mcBaseData, T)
return S
end
function simulate(mcProcess::VectorialMonteCarloProcess, zeroCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
price_type = predict_output_type_zero(mcProcess, zeroCurve, mcBaseData, T)
matrix_type = get_matrix_type(mcBaseData, mcProcess, price_type)
S = matrix_type(undef, length(mcProcess.models))
for i = 1:length(mcProcess.models)
S[i] = eltype(S)(undef, mcBaseData.Nsim, mcBaseData.Nstep + 1)
end
simulate!(S, mcProcess, zeroCurve, mcBaseData, T)
return S
end
"""
General Interface for Stochastic Engine simulation
S=simulate(mcProcess,mcBaseData,T)
Where:
mcProcess = Process to be simulated.
mcBaseData = Basic properties of MonteCarlo simulation
T = Final time of the process
S = Matrix with path of underlying.
"""
function simulate(mcProcess::AbstractMonteCarloEngine, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
price_type = predict_output_type_zero(mcProcess, mcBaseData, T)
S = get_matrix_type(mcBaseData, mcProcess, price_type)
simulate!(S, mcProcess, mcBaseData, T)
return S
end
# function simulate_per_path(Nsim,Nstep,rn)
# S0=100.0;
# X=Matrix{Float64}(undef,Nsim,Nstep+1);
# for i=1:Nsim
# @views simulate_path!(X[i,:],rn)
# end
# return X;
# end
# function simulate_per_path(mcProcess::AbstractMonteCarloProcess, zeroCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
# price_type = predict_output_type_zero(mcProcess, zeroCurve, mcBaseData, T)
# S = get_matrix_type(mcBaseData, mcProcess, price_type)
# #simulate!(S, mcProcess, zeroCurve, mcBaseData, T)
# for i=1:mcBaseData.Nsim
# # @views simulate_path!(X[i,:],rn)
# @views simulate_path!(S[i,:], mcProcess, zeroCurve, mcBaseData, T)
# end
# return S
# end | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1399 | """
Struct for Black Scholes Process
bsProcess=BlackScholesProcess(σ::num1) where {num1 <: Number}
Where:
σ = volatility of the process.
"""
struct BlackScholesProcess{num <: Number, abstrUnderlying <: AbstractUnderlying} <: ItoProcess{num}
σ::num
underlying::abstrUnderlying
function BlackScholesProcess(σ::num, underlying::abstrUnderlying) where {num <: Number, abstrUnderlying <: AbstractUnderlying}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "Volatility must be positive"
return new{num, abstrUnderlying}(σ, underlying)
end
end
export BlackScholesProcess;
function simulate!(S, mcProcess::BlackScholesProcess, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
ChainRulesCore.@ignore_derivatives @assert T > 0.0
r = rfCurve.r
d = dividend(mcProcess)
σ = mcProcess.σ
μ = r - d
simulate!(S, GeometricBrownianMotion(σ, μ, mcProcess.underlying.S0), mcBaseData, T)
nothing
end
# function simulate_path!(S, mcProcess::BlackScholesProcess, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
# ChainRulesCore.@ignore_derivatives @assert T > 0.0
# r = rfCurve.r
# d = dividend(mcProcess)
# σ = mcProcess.σ
# μ = r - d
# simulate_path!(S, GeometricBrownianMotion(σ, μ, mcProcess.underlying.S0), mcBaseData, T)
# nothing
# end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2695 | """
Struct for Brownian Motion
bmProcess=BrownianMotion(σ::num1,μ::num2) where {num1,num2 <: Number}
Where:
σ = volatility of the process.
μ = drift of the process.
"""
struct BrownianMotion{num <: Number, num1 <: Number, numtype <: Number} <: AbstractMonteCarloEngine{numtype}
σ::num
μ::num1
function BrownianMotion(σ::num, μ::num1) where {num <: Number, num1 <: Number}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "Volatility must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1)
return new{num, num1, typeof(zero_typed)}(σ, μ)
end
end
export BrownianMotion;
# function simulate_path!(X, mcProcess::BrownianMotion, mcBaseData::SerialMonteCarloConfig, T::numb) where {numb <: Number}
# Nstep = mcBaseData.Nstep
# σ = mcProcess.σ
# μ = mcProcess.μ
# ChainRulesCore.@ignore_derivatives @assert T > 0
# dt = T / Nstep
# mean_bm = μ * dt
# stddev_bm = σ * sqrt(dt)
# isDualZero = mean_bm * stddev_bm * 0
# @views X[1] = isDualZero
# @inbounds for j = 1:Nstep
# @views X[j+1] = X[j] + mean_bm + stddev_bm * randn(mcBaseData.parallelMode.rng)
# end
# return
# end
function simulate!(X, mcProcess::BrownianMotion, mcBaseData::SerialMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
mean_bm = μ * dt
stddev_bm = σ * sqrt(dt)
isDualZero = mean_bm * stddev_bm * 0
view(X, :, 1) .= isDualZero
Z = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
@inbounds for j = 1:Nstep
randn!(mcBaseData.parallelMode.rng, Z)
@views @. X[:, j+1] = X[:, j] + mean_bm + stddev_bm * Z
end
return
end
function simulate!(X, mcProcess::BrownianMotion, mcBaseData::SerialAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
mean_bm = μ * dt
stddev_bm = σ * sqrt(dt)
isDualZero = mean_bm * stddev_bm * 0
view(X, :, 1) .= isDualZero
Nsim_2 = div(Nsim, 2)
zero_typed = predict_output_type_zero(σ, μ)
Z = Array{typeof(get_rng_type(zero_typed))}(undef, Nsim_2)
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
@inbounds for j = 1:Nstep
randn!(mcBaseData.parallelMode.rng, Z)
@. @views Xp[:, j+1] = Xp[:, j] + mean_bm + stddev_bm * Z
@. @views Xm[:, j+1] = Xm[:, j] + mean_bm - stddev_bm * Z
end
nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2501 | """
Struct for Brownian Motion
bmProcess=BrownianMotionVec(σ::num1,μ::num2) where {num1,num2 <: Number}
Where:
σ = volatility of the process.
μ = drift of the process.
"""
struct BrownianMotionVec{num <: Number, num1 <: Number, num4 <: Number, numtype <: Number} <: AbstractMonteCarloEngine{numtype}
σ::num
μ::CurveType{num1, num4}
function BrownianMotionVec(σ::num, μ::CurveType{num1, num4}) where {num <: Number, num1 <: Number, num4 <: Number}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "Volatility must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1) + zero(num4)
return new{num, num1, num4, typeof(zero_typed)}(σ, μ)
end
end
function BrownianMotion(σ::num, μ::CurveType{num1, num4}) where {num <: Number, num1 <: Number, num4 <: Number}
return BrownianMotionVec(σ, μ)
end
function simulate!(X, mcProcess::BrownianMotionVec, mcBaseData::SerialMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
stddev_bm = σ * sqrt(dt)
zero_drift = incremental_integral(μ, dt * 0, dt)
isDualZero = stddev_bm * 0 * zero_drift
view(X, :, 1) .= isDualZero
Z = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
@inbounds for j = 1:Nstep
tmp_ = incremental_integral(μ, (j - 1) * dt, dt)
randn!(mcBaseData.parallelMode.rng, Z)
@views @. X[:, j+1] = X[:, j] + tmp_ + stddev_bm * Z
end
nothing
end
function simulate!(X, mcProcess::BrownianMotionVec, mcBaseData::SerialAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
stddev_bm = σ * sqrt(dt)
zero_drift = incremental_integral(μ, dt * 0, dt)
isDualZero = stddev_bm * 0 * zero_drift
view(X, :, 1) .= isDualZero
Nsim_2 = div(Nsim, 2)
Z = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
@inbounds for j = 1:Nstep
tmp_ = incremental_integral(μ, (j - 1) * dt, dt)
randn!(mcBaseData.parallelMode.rng, Z)
@views @. Xp[:, j+1] = Xp[:, j] + tmp_ + stddev_bm * Z
@views @. Xm[:, j+1] = Xm[:, j] + tmp_ - stddev_bm * Z
end
nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1649 | using Sobol, StatsFuns
function simulate!(X, mcProcess::BrownianMotion, mcBaseData::SerialSobolMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
mean_bm = μ * dt
stddev_bm = σ * sqrt(dt)
isDualZero = mean_bm * stddev_bm * 0
view(X, :, 1) .= isDualZero
seq = SobolSeq(Nstep)
skip(seq, Nstep * Nsim)
vec = Array{typeof(get_rng_type(isDualZero))}(undef, Nstep)
@inbounds for i = 1:Nsim
next!(seq, vec)
@. vec = norminvcdf(vec)
@inbounds for j = 1:Nstep
@views X[i, j+1] = X[i, j] + mean_bm + stddev_bm * vec[j]
end
end
nothing
end
function simulate!(X, mcProcess::BrownianMotionVec, mcBaseData::SerialSobolMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
stddev_bm = σ * sqrt(dt)
zero_drift = incremental_integral(μ, dt * 0, dt)
isDualZero = stddev_bm * 0 * zero_drift
view(X, :, 1) .= isDualZero
seq = SobolSeq(Nstep)
skip(seq, Nstep * Nsim)
vec = Array{typeof(get_rng_type(isDualZero))}(undef, Nstep)
tmp_ = [incremental_integral(μ, (j - 1) * dt, dt) for j = 1:Nstep]
@inbounds for i = 1:Nsim
next!(seq, vec)
@. vec = norminvcdf(vec)
@inbounds for j = 1:Nstep
@views X[i, j+1] = X[i, j] + tmp_[j] + stddev_bm * vec[j]
end
end
nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1406 | struct MonteCarloDiffEqModel{absdiffeqmodel <: DiffEqBase.AbstractEnsembleProblem} <: ScalarMonteCarloProcess{Float64}
model::absdiffeqmodel
final_trasform::Function
underlying::AbstractUnderlying
function MonteCarloDiffEqModel(model::absdiffeqmodel, final_trasform::Function, underlying::AbstractUnderlying) where {absdiffeqmodel <: DiffEqBase.AbstractEnsembleProblem}
return new{absdiffeqmodel}(model, final_trasform, underlying)
end
function MonteCarloDiffEqModel(model::absdiffeqmodel, underlying::AbstractUnderlying) where {absdiffeqmodel <: DiffEqBase.AbstractEnsembleProblem}
func(x) = identity(x)
return new{absdiffeqmodel}(model, func, underlying)
end
end
export MonteCarloDiffeEqModel;
function simulate!(X, mcProcess::MonteCarloDiffEqModel, rfCurve::ZeroRate, mcBaseData::MonteCarloConfiguration{type1, type2, type3, type4}, T::numb) where {numb <: Number, type1 <: Number, type2 <: Number, type3 <: AbstractMonteCarloMethod, type4 <: BaseMode}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
Dt = T / Nstep
ChainRulesCore.@ignore_derivatives @assert T > 0.0
diffeqmodel = mcProcess.model
sol = solve(diffeqmodel, SOSRI(), EnsembleThreads(), trajectories = Nsim, dt = Dt, adaptive = false)
X .= [path.u[j] for path in sol.u, j = 1:(Nstep+1)]
f(x) = mcProcess.final_trasform(x)
@. X = f(X)
nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1336 |
function add_jump_matrix!(X, mcProcess::finiteActivityProcess, mcBaseData::AbstractMonteCarloConfiguration, T::numb) where {finiteActivityProcess <: FiniteActivityProcess, numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
λ = mcProcess.λ
dt = T / Nstep
@inbounds for i = 1:Nsim
t_i = randexp(mcBaseData.parallelMode.rng) / λ
while t_i < T
jump_size = compute_jump_size(mcProcess, mcBaseData)
jump_idx = ceil(UInt32, t_i / dt) + 1
@views @. X[i, jump_idx:end] += jump_size #add jump component
t_i += randexp(mcBaseData.parallelMode.rng) / λ
end
end
end
function simulate!(X, mcProcess::finiteActivityProcess, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::numb) where {finiteActivityProcess <: FiniteActivityProcess, numb <: Number}
r = rfCurve.r
d = dividend(mcProcess)
σ = mcProcess.σ
λ = mcProcess.λ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
####Simulation
## Simulate
# r-d-psi(-i)
drift_rn = (r - d) - σ^2 / 2 - λ * compute_drift(mcProcess)
simulate!(X, BrownianMotion(σ, drift_rn), mcBaseData, T)
add_jump_matrix!(X, mcProcess, mcBaseData, T)
## Conclude
S0 = mcProcess.underlying.S0
@. X = S0 * exp(X)
nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1671 | # Abstract type for GeometricBrownianMotion, an Ito process is always a Levy
abstract type AbstractGeometricBrownianMotion{T <: Number} <: AbstractMonteCarloEngine{T} end
"""
Struct for Geometric Brownian Motion
gbmProcess=GeometricBrownianMotion(σ::num1,μ::num2) where {num1,num2 <: Number}
Where:
σ = volatility of the process.
μ = drift of the process.
x0 = initial value.
"""
struct GeometricBrownianMotion{num <: Number, num1 <: Number, num2 <: Number, numtype <: Number} <: AbstractGeometricBrownianMotion{numtype}
σ::num
μ::num1
x0::num2
function GeometricBrownianMotion(σ::num, μ::num1, x0::num2) where {num <: Number, num1 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "Volatility must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1)
return new{num, num1, num2, typeof(zero_typed)}(σ, μ, x0)
end
end
export GeometricBrownianMotion;
function simulate!(X, mcProcess::AbstractGeometricBrownianMotion, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
ChainRulesCore.@ignore_derivatives @assert T > 0
σ = mcProcess.σ
μ = mcProcess.μ - σ^2 / 2
simulate!(X, BrownianMotion(σ, μ), mcBaseData, T)
S0 = mcProcess.x0
@. X = S0 * exp(X)
nothing
end
# function simulate_path!(X, mcProcess::AbstractGeometricBrownianMotion, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
# ChainRulesCore.@ignore_derivatives @assert T > 0
# σ = mcProcess.σ
# μ = mcProcess.μ - σ^2 / 2
# simulate_path!(X, BrownianMotion(σ, μ), mcBaseData, T)
# S0 = mcProcess.x0
# @. X = S0 * exp(X)
# nothing
# end | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1080 | """
Struct for Geometric Brownian Motion
gbmProcess=GeometricBrownianMotionVec(σ::num1,μ::num2) where {num1,num2 <: Number}
Where:
σ = volatility of the process.
μ = drift of the process.
"""
struct GeometricBrownianMotionVec{num <: Number, num1 <: Number, num4 <: Number, num2 <: Number, numtype <: Number} <: AbstractGeometricBrownianMotion{numtype}
σ::num
μ::CurveType{num1, num4}
x0::num2
function GeometricBrownianMotionVec(σ::num, μ::CurveType{num1, num4}, x0::num2) where {num <: Number, num1 <: Number, num4 <: Number, num2 <: Number}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "Volatility must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1) + zero(num4) + zero(num2)
return new{num, num1, num4, num2, typeof(zero_typed)}(σ, μ, x0)
end
end
function GeometricBrownianMotion(σ::num, μ::CurveType{num1, num4}, x0::num2) where {num <: Number, num1 <: Number, num4 <: Number, num2 <: Number}
return GeometricBrownianMotionVec(σ, μ, x0)
end
export GeometricBrownianMotionVec; | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 5009 | """
Struct for Heston Process
hstProcess=HestonProcess(σ::num1,σ₀::num2,λ::num3,κ::num4,ρ::num5,θ::num6) where {num1,num2,num3,num4,num5,num6 <: Number}
Where:
σ = volatility of volatility of the process.
σ₀ = initial volatility of the process.
λ = shift value of the process.
κ = mean reversion of the process.
ρ = correlation between brownian motions.
θ = long value of square of volatility of the process.
"""
struct HestonProcess{num <: Number, num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, abstrUnderlying <: AbstractUnderlying, numtype <: Number} <: ItoProcess{numtype}
σ::num
σ₀::num1
λ::num2
κ::num3
ρ::num4
θ::num5
underlying::abstrUnderlying
function HestonProcess(σ::num, σ₀::num1, λ::num2, κ::num3, ρ::num4, θ::num5, underlying::abstrUnderlying) where {num <: Number, num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, num5 <: Number, abstrUnderlying <: AbstractUnderlying}
ChainRulesCore.@ignore_derivatives @assert σ₀ > 0.0 "initial volatility must be positive"
ChainRulesCore.@ignore_derivatives @assert σ > 0.0 "volatility of volatility must be positive"
ChainRulesCore.@ignore_derivatives @assert abs(κ + λ) > 1e-14 "unfeasible parameters"
ChainRulesCore.@ignore_derivatives @assert (-1.0 <= ρ <= 1.0) "ρ must be a correlation"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1) + zero(num2) + zero(num3) + zero(num4) + zero(num5)
return new{num, num1, num2, num3, num4, num5, abstrUnderlying, typeof(zero_typed)}(σ, σ₀, λ, κ, ρ, θ, underlying)
end
end
export HestonProcess;
function simulate!(X, mcProcess::HestonProcess, rfCurve::ZeroRate, mcBaseData::SerialMonteCarloConfig, T::numb) where {numb <: Number}
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ₀ = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / κ_s
dt = T / Nstep
isDualZeroVol = zero(T * r * σ₀ * θ_s * κ_s * σ * ρ)
isDualZero = isDualZeroVol * S0
view(X, :, 1) .= isDualZero
v_m = [σ₀^2 + isDualZero for _ = 1:Nsim]
isDualZero_eps = isDualZeroVol + eps(isDualZeroVol)
e1 = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
#Wrong, is dual zero shouldn't have rho
e2_rho = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
e2 = Array{typeof(get_rng_type(isDualZero) + zero(ρ))}(undef, Nsim)
tmp_cost = sqrt(1 - ρ * ρ)
#TODO: acnaoicna
for j = 1:Nstep
randn!(mcBaseData.parallelMode.rng, e1)
randn!(mcBaseData.parallelMode.rng, e2_rho)
@. e2 = e1 * ρ + e2_rho * tmp_cost
@views @. X[:, j+1] = X[:, j] + ((r - d) - 0.5 * v_m) * dt + sqrt(v_m) * sqrt(dt) * e1
@. v_m += κ_s * (θ_s - v_m) * dt + σ * sqrt(v_m) * sqrt(dt) * e2
#when v_m = 0.0, the derivative becomes NaN
@. v_m = max(v_m, isDualZero_eps)
end
## Conclude
@. X = S0 * exp(X)
return
end
function simulate!(X, mcProcess::HestonProcess, rfCurve::ZeroRate, mcBaseData::SerialAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ₀ = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
####Simulation
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / κ_s
dt = T / Nstep
isDualZeroVol = zero(T * r * σ₀ * κ * θ * λ1 * σ * ρ)
isDualZero = isDualZeroVol * S0
view(X, :, 1) .= isDualZero
isDualZero_eps = isDualZeroVol + eps(isDualZeroVol)
Nsim_2 = div(Nsim, 2)
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
v_m_1 = [σ₀^2 + isDualZero for _ = 1:Nsim_2]
v_m_2 = [σ₀^2 + isDualZero for _ = 1:Nsim_2]
e1 = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
e2_rho = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
e2 = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
for j = 1:Nstep
randn!(mcBaseData.parallelMode.rng, e1)
randn!(mcBaseData.parallelMode.rng, e2_rho)
@. e2 = -(e1 * ρ + e2_rho * sqrt(1 - ρ * ρ))
@views @. Xp[:, j+1] = Xp[:, j] + ((r - d) - 0.5 * v_m_1) * dt + sqrt(v_m_1) * sqrt(dt) * e1
@views @. Xm[:, j+1] = Xm[:, j] + ((r - d) - 0.5 * v_m_2) * dt - sqrt(v_m_2) * sqrt(dt) * e1
@. v_m_1 += κ_s * (θ_s - v_m_1) * dt + σ * sqrt(v_m_1) * sqrt(dt) * e2
@. v_m_2 += κ_s * (θ_s - v_m_2) * dt - σ * sqrt(v_m_2) * sqrt(dt) * e2
@. v_m_1 = max(v_m_1, isDualZero_eps)
@. v_m_2 = max(v_m_2, isDualZero_eps)
end
## Conclude
@. X = S0 * exp(X)
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3417 |
function simulate!(X, mcProcess::HestonProcess, rfCurve::ZeroRateCurve, mcBaseData::SerialMonteCarloConfig, T::numb) where {numb <: Number}
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ₀ = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / (κ + λ1)
r_d = r - d
dt = T / Nstep
zero_drift = incremental_integral(r_d, dt * 0.0, dt)
isDualZeroVol = zero(T * σ₀ * κ * θ * λ1 * σ * ρ * zero_drift)
isDualZero = S0 * isDualZeroVol
X[:, 1] .= isDualZero
v_m = [σ₀^2 + isDualZero for _ = 1:Nsim]
isDualZeroVol_eps = isDualZeroVol + eps(isDualZeroVol)
e1 = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
e2_rho = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
e2 = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
@inbounds for j = 1:Nstep
randn!(mcBaseData.parallelMode.rng, e1)
randn!(mcBaseData.parallelMode.rng, e2_rho)
@. e2 = e1 * ρ + e2_rho * sqrt(1 - ρ * ρ)
tmp_ = incremental_integral(r_d, (j - 1) * dt, dt)
@. @views X[:, j+1] = X[:, j] + (tmp_ - 0.5 * v_m * dt) + sqrt(v_m) * sqrt(dt) * e1
@. v_m += κ_s * (θ_s - v_m) * dt + σ * sqrt(v_m) * sqrt(dt) * e2
@. v_m = max(v_m, isDualZeroVol_eps)
end
## Conclude
@. X = S0 * exp(X)
return
end
function simulate!(X, mcProcess::HestonProcess, rfCurve::ZeroRateCurve, mcBaseData::SerialAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ₀ = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
####Simulation
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / (κ + λ1)
dt = T / Nstep
isDualZeroVol = zero(T * σ₀ * κ * θ * λ1 * σ * ρ)
isDualZero = S0 * isDualZeroVol
X[:, 1] .= isDualZero
Nsim_2 = div(Nsim, 2)
r_d = r - d
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
v_mp = [σ₀^2 + isDualZero for _ = 1:Nsim_2]
v_mm = [σ₀^2 + isDualZero for _ = 1:Nsim_2]
e1 = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
e2_rho = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
e2 = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
isDualZeroVol_eps = isDualZeroVol + eps(isDualZeroVol)
for j = 1:Nstep
randn!(mcBaseData.parallelMode.rng, e1)
randn!(mcBaseData.parallelMode.rng, e2_rho)
@. e2 = e1 * ρ + e2_rho * sqrt(1 - ρ * ρ)
tmp_ = incremental_integral(r_d, (j - 1) * dt, dt)
@. @views Xp[:, j+1] = Xp[:, j] + (tmp_ - 0.5 * v_mp * dt) + sqrt(v_mp) * sqrt(dt) * e1
@. @views Xm[:, j+1] = Xm[:, j] + (tmp_ - 0.5 * v_mm * dt) - sqrt(v_mm) * sqrt(dt) * e1
@. v_mp += κ_s * (θ_s - v_mp) * dt + (σ * sqrt(dt)) * sqrt(v_mp) * e2
@. v_mm += κ_s * (θ_s - v_mm) * dt - (σ * sqrt(dt)) * sqrt(v_mm) * e2
@. v_mp = max(v_mp, isDualZeroVol_eps)
@. v_mm = max(v_mm, isDualZeroVol_eps)
end
## Conclude
@. X = S0 * exp(X)
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2924 | using Sobol, StatsFuns
function simulate!(X, mcProcess::HestonProcess, rfCurve::ZeroRate, mcBaseData::SerialSobolMonteCarloConfig, T::numb) where {numb <: Number}
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ₀ = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
####Simulation
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / κ_s
seq = SobolSeq(2 * Nstep)
skip(seq, Nstep * Nsim)
dt = T / Nstep
isDualZero = T * r * σ₀ * θ_s * κ_s * σ * ρ * 0.0 * S0
view(X, :, 1) .= isDualZero
vec = Array{typeof(get_rng_type(isDualZero))}(undef, 2 * Nstep)
for i = 1:Nsim
v_m = σ₀^2
next!(seq, vec)
vec .= norminvcdf.(vec)
for j = 1:Nstep
@views e1 = vec[j]
@views e2 = e1 * ρ + vec[Nstep+j] * sqrt(1 - ρ * ρ)
@views X[i, j+1] = X[i, j] + ((r - d) - 0.5 * v_m) * dt + sqrt(v_m) * sqrt(dt) * e1
v_m += κ_s * (θ_s - v_m) * dt + σ * sqrt(v_m) * sqrt(dt) * e2
#when v_m = 0.0, the derivative becomes NaN
v_m = max(v_m, isDualZero)
end
end
## Conclude
@. X = S0 * exp(X)
return
end
function simulate!(X, mcProcess::HestonProcess, rfCurve::ZeroRateCurve, mcBaseData::SerialSobolMonteCarloConfig, T::numb) where {numb <: Number}
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ₀ = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
####Simulation
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / (κ + λ1)
r_d = r - d
dt = T / Nstep
seq = SobolSeq(2 * Nstep)
skip(seq, Nstep * Nsim)
zero_drift = incremental_integral(r_d, dt * 0.0, dt)
isDualZeroVol = T * σ₀ * κ * θ * λ1 * σ * ρ * 0.0 * zero_drift
isDualZero = S0 * isDualZeroVol
view(X, :, 1) .= isDualZero
vec = Array{typeof(get_rng_type(isDualZero))}(undef, 2 * Nstep)
tmp_ = [incremental_integral(r_d, (j - 1) * dt, dt) for j = 1:Nstep]
isDualZeroVol_eps = isDualZeroVol + eps(isDualZeroVol)
for i = 1:Nsim
v_m = σ₀^2
next!(seq, vec)
@. vec = norminvcdf(vec)
for j = 1:Nstep
@views e1 = vec[j]
@views e2 = e1 * ρ + vec[Nstep+j] * sqrt(1 - ρ * ρ)
@views X[i, j+1] = X[i, j] + (tmp_[j] - 0.5 * v_m) * dt + sqrt(v_m) * sqrt(dt) * e1
v_m += κ_s * (θ_s - v_m) * dt + σ * sqrt(v_m) * sqrt(dt) * e2
#when v_m = 0.0, the derivative becomes NaN
v_m = max(v_m, isDualZeroVol_eps)
end
end
## Conclude
@. X = S0 * exp(X)
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1845 | """
Struct for Kou Process
kouProcess=KouProcess(σ::num1,λ::num2,p::num3,λ₊::num4,λ₋::num5) where {num1,num2,num3,num4,num5 <: Number}
Where:
σ = volatility of the process.
λ = jumps intensity.
p = prob. of having positive jump.
λ₊ = positive jump size.
λ₋ = negative jump size.
"""
struct KouProcess{num <: Number, num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, abstrUnderlying <: AbstractUnderlying, numtype <: Number} <: FiniteActivityProcess{numtype}
σ::num
λ::num1
p::num2
λ₊::num3
λ₋::num4
underlying::abstrUnderlying
function KouProcess(σ::num, λ::num1, p::num2, λ₊::num3, λ₋::num4, underlying::abstrUnderlying) where {num <: Number, num1 <: Number, num2 <: Number, num3 <: Number, num4 <: Number, abstrUnderlying <: AbstractUnderlying}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "volatility must be positive"
ChainRulesCore.@ignore_derivatives @assert λ > 0 "λ, i.e. jump intensity, must be positive"
ChainRulesCore.@ignore_derivatives @assert 0 <= p <= 1 "p must be a probability"
ChainRulesCore.@ignore_derivatives @assert λ₊ > 0 "λ₊ must be positive"
ChainRulesCore.@ignore_derivatives @assert λ₋ > 0 "λ₋ must be positive"
zero_typed = promote_type(num, num1, num2, num3, num4)
return new{num, num1, num2, num3, num4, abstrUnderlying, zero_typed}(σ, λ, p, λ₊, λ₋, underlying)
end
end
export KouProcess;
function compute_jump_size(mcProcess::KouProcess, mcBaseData::MonteCarloConfiguration)
if rand(mcBaseData.parallelMode.rng) < mcProcess.p
return randexp(mcBaseData.parallelMode.rng) / mcProcess.λ₊
end
return -randexp(mcBaseData.parallelMode.rng) / mcProcess.λ₋
end
compute_drift(mcProcess::KouProcess) = mcProcess.p / (mcProcess.λ₊ - 1) - (1 - mcProcess.p) / (mcProcess.λ₋ + 1)
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1771 | """
Struct for LogNormalMixture
lnmModel=LogNormalMixture(η::Array{num1},λ::Array{num2}) where {num1,num2<: Number}
Where:
η = Array of volatilities.
λ = Array of weights.
"""
struct LogNormalMixture{num <: Number, num2 <: Number, abstrUnderlying <: AbstractUnderlying, numtype <: Number} <: ItoProcess{numtype}
η::Array{num, 1}
λ::Array{num2, 1}
underlying::abstrUnderlying
function LogNormalMixture(η::Array{num, 1}, λ::Array{num2, 1}, underlying::abstrUnderlying) where {num <: Number, num2 <: Number, abstrUnderlying <: AbstractUnderlying}
ChainRulesCore.@ignore_derivatives @assert minimum(η) > 0.0 "Volatilities must be positive"
ChainRulesCore.@ignore_derivatives @assert minimum(λ) > 0.0 "weights must be positive"
ChainRulesCore.@ignore_derivatives @assert sum(λ) <= 1.0 "λs must be weights"
ChainRulesCore.@ignore_derivatives @assert length(λ) == length(η) - 1 "Check vector lengths"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num2)
return new{num, num2, abstrUnderlying, typeof(zero_typed)}(η, λ, underlying)
end
end
export LogNormalMixture;
function simulate!(S, mcProcess::LogNormalMixture, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
ChainRulesCore.@ignore_derivatives @assert T > 0.0
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
η_gbm = mcProcess.η
λ_gmb = copy(mcProcess.λ)
push!(λ_gmb, 1.0 - sum(mcProcess.λ))
mu_gbm = r - d
S .= 0
tmp_s = similar(S)
for (η_gbm_, λ_gmb_) in zip(η_gbm, λ_gmb)
simulate!(tmp_s, GeometricBrownianMotion(η_gbm_, mu_gbm, S0), mcBaseData, T)
@. S += λ_gmb_ * tmp_s
end
return nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1516 | """
Struct for Merton Process
mertonProcess=MertonProcess(σ::num1,λ::num2,μ_jump::num3,σ_jump::num4) where {num1,num2,num3,num4<: Number}
Where:
σ = volatility of the process.
λ = jumps intensity.
μ_jump = jumps mean.
σ_jump = jumps variance.
"""
struct MertonProcess{num <: Number, num1 <: Number, num2 <: Number, num3 <: Number, abstrUnderlying <: AbstractUnderlying, numtype <: Number} <: FiniteActivityProcess{numtype}
σ::num
λ::num1
μ_jump::num2
σ_jump::num3
underlying::abstrUnderlying
function MertonProcess(σ::num, λ::num1, μ_jump::num2, σ_jump::num3, underlying::abstrUnderlying) where {num <: Number, num1 <: Number, num2 <: Number, num3 <: Number, abstrUnderlying <: AbstractUnderlying}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "volatility must be positive"
ChainRulesCore.@ignore_derivatives @assert λ > 0 "jump intensity must be positive"
ChainRulesCore.@ignore_derivatives @assert σ_jump > 0 "positive λ must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1) + zero(num2) + zero(num3)
return new{num, num1, num2, num3, abstrUnderlying, typeof(zero_typed)}(σ, λ, μ_jump, σ_jump, underlying)
end
end
export MertonProcess;
compute_jump_size(mcProcess::MertonProcess, mcBaseData::MonteCarloConfiguration) = mcProcess.μ_jump + mcProcess.σ_jump * randn(mcBaseData.parallelMode.rng);
compute_drift(mcProcess::MertonProcess) = exp(mcProcess.μ_jump + mcProcess.σ_jump^2 / 2.0) - 1.0
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 860 | using Distributions;
using Statistics
### Utils
include("utils.jl")
### Ito Processes
include("brownian_motion.jl")
include("brownian_motion_aug.jl")
include("brownian_motion_sobol.jl")
include("geometric_brownian_motion.jl")
include("geometric_brownian_motion_aug.jl")
include("black_scholes.jl")
include("heston.jl")
include("heston_aug.jl")
include("heston_sobol.jl")
include("log_normal_mixture.jl")
include("shifted_log_normal_mixture.jl")
### Finite Activity Levy Processes
include("fa_levy.jl")
include("kou.jl")
include("merton.jl")
### Infinite Activity Levy Processes
include("subordinated_brownian_motion.jl")
include("subordinated_brownian_motion_aug.jl")
include("subordinated_brownian_motion_sobol.jl")
include("variance_gamma.jl")
include("normal_inverse_gaussian.jl")
### MultiDimensional
include("nvariate.jl")
include("nvariate_log.jl")
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1906 | """
Struct for NIG Process
nigProcess=NormalInverseGaussianProcess(σ::num1,θ::num2,κ::num3) where {num1,num2,num3<: Number}
Where:
σ = volatility of the process.
θ = variance of volatility.
κ = skewness of volatility.
"""
struct NormalInverseGaussianProcess{num <: Number, num1 <: Number, num2 <: Number, abstrUnderlying <: AbstractUnderlying, numtype <: Number} <: InfiniteActivityProcess{numtype}
σ::num
θ::num1
κ::num2
underlying::abstrUnderlying
function NormalInverseGaussianProcess(σ::num, θ::num1, κ::num2, underlying::abstrUnderlying) where {num <: Number, num1 <: Number, num2 <: Number, abstrUnderlying <: AbstractUnderlying}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "volatility must be positive"
ChainRulesCore.@ignore_derivatives @assert κ > 0 "κappa must be positive"
ChainRulesCore.@ignore_derivatives @assert 1 - (σ^2 + 2 * θ) * κ > 0 "Parameters with unfeasible values"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1) + zero(num2)
return new{num, num1, num2, abstrUnderlying, typeof(zero_typed)}(σ, θ, κ, underlying)
end
end
export NormalInverseGaussianProcess;
function simulate!(X, mcProcess::NormalInverseGaussianProcess, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
θ = mcProcess.θ
κ = mcProcess.κ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
ψ = (1 - sqrt(1 - (σ^2 + 2 * θ) * κ)) / κ
drift = r - d - ψ
#Define subordinator
IGRandomVariable = InverseGaussian(dt, (dt^2) / κ)
#Call SubordinatedBrownianMotion
simulate!(X, SubordinatedBrownianMotion(σ, drift, θ, IGRandomVariable), mcBaseData, T)
@. X = S0 * exp(X)
return nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2750 | """
Struct for MultiVariate Copula Process
gaussianCopulaNVariateProcess=GaussianCopulaNVariateProcess(models::num1,λ::num2,p::num3,λ₊::num4,λ₋::num5) where {num1,num2,num3,num4,num5 <: Number}
Where:
models = the processes.
rho = correlation matrix.
"""
struct GaussianCopulaNVariateProcess{num3 <: Number, numtype <: Number} <: NDimensionalMonteCarloProcess{numtype}
rho::Matrix{num3}
models::Tuple{Vararg{BaseProcess}}
function GaussianCopulaNVariateProcess(rho::Matrix{num3}, models::Tuple) where {num3 <: Number}
sz = size(rho)
ChainRulesCore.@ignore_derivatives @assert sz[1] == sz[2]
ChainRulesCore.@ignore_derivatives @assert length(models) == sz[1]
ChainRulesCore.@ignore_derivatives @assert isposdef(rho)
zero_typed = predict_output_type_zero(models...) + zero(num3)
return new{num3, typeof(zero_typed)}(rho, models)
end
function GaussianCopulaNVariateProcess(rho::Matrix{num3}, models::BaseProcess...) where {num3 <: Number}
sz = size(rho)
ChainRulesCore.@ignore_derivatives @assert sz[1] == sz[2]
ChainRulesCore.@ignore_derivatives @assert length(models) == sz[1]
ChainRulesCore.@ignore_derivatives @assert isposdef(rho)
zero_typed = predict_output_type_zero(models...) + zero(num3)
return new{num3, typeof(zero_typed)}(rho, models)
end
function GaussianCopulaNVariateProcess(models::BaseProcess...)
len_ = length(models)
return GaussianCopulaNVariateProcess(Matrix{Float64}(I, len_, len_), models...)
end
function GaussianCopulaNVariateProcess(model1::BaseProcess, model2::BaseProcess, rho::num3) where {num3 <: Number}
corr_matrix_ = [1 rho; rho 1]
ChainRulesCore.@ignore_derivatives @assert isposdef(corr_matrix_)
return GaussianCopulaNVariateProcess(corr_matrix_, model1, model2)
end
end
export GaussianCopulaNVariateProcess;
function simulate!(S_total, mcProcess::GaussianCopulaNVariateProcess, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
ChainRulesCore.@ignore_derivatives @assert T > 0
####Simulation
## Simulate
len_ = length(mcProcess.models)
for i = 1:len_
simulate!(S_total[i], mcProcess.models[i], rfCurve, mcBaseData, T)
end
rho = mcProcess.rho
if (isdiag(rho))
return
end
U_joint = Matrix{eltype(rho)}(undef, len_, Nsim)
for j = 1:Nstep
gausscopulagen2!(U_joint, rho, mcBaseData)
for i = 1:len_
@views tmp_ = S_total[i][:, j+1]
@views Statistics.quantile!(tmp_, U_joint[i, :])
end
end
## Conclude
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2584 | """
Struct for MultiVariate (log moneyness x-> S0*exp(x) ) Copula Process
gaussianCopulaNVariateLogProcess=GaussianCopulaNVariateLogProcess(models::num1,λ::num2,p::num3,λ₊::num4,λ₋::num5) where {num1,num2,num3,num4,num5 <: Number}
Where:
models = the processes.
rho = correlation matrix.
"""
struct GaussianCopulaNVariateLogProcess{num3 <: Number, numtype <: Number} <: NDimensionalMonteCarloProcess{numtype}
models::Tuple{Vararg{BaseProcess}}
rho::Matrix{num3}
function GaussianCopulaNVariateLogProcess(rho::Matrix{num3}, models::BaseProcess...) where {num3 <: Number}
sz = size(rho)
ChainRulesCore.@ignore_derivatives @assert sz[1] == sz[2]
ChainRulesCore.@ignore_derivatives @assert length(models) == sz[1]
ChainRulesCore.@ignore_derivatives @assert isposdef(rho)
zero_typed = predict_output_type_zero(models...) + zero(num3)
return new{num3, typeof(zero_typed)}(models, rho)
end
function GaussianCopulaNVariateLogProcess(models::BaseProcess...)
len_ = length(models)
return GaussianCopulaNVariateLogProcess(Matrix{Float64}(I, len_, len_), models...)
end
function GaussianCopulaNVariateLogProcess(model1::BaseProcess, model2::BaseProcess, rho::num3) where {num3 <: Number}
corr_matrix_ = [1.0 rho; rho 1.0]
ChainRulesCore.@ignore_derivatives @assert isposdef(corr_matrix_)
return GaussianCopulaNVariateLogProcess(corr_matrix_, model1, model2)
end
end
export GaussianCopulaNVariateLogProcess;
function simulate!(S_Total, mcProcess::GaussianCopulaNVariateLogProcess, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
ChainRulesCore.@ignore_derivatives @assert T > 0.0
####Simulation
## Simulate
len_ = length(mcProcess.models)
@inbounds for i = 1:len_
@views simulate!(S_Total[i], mcProcess.models[i], rfCurve, mcBaseData, T)
end
rho = mcProcess.rho
if (isdiag(rho))
return
end
@inbounds for i = 1:len_
@. S_Total[i] = log(S_Total[i] / mcProcess.models[i].underlying.S0)
end
U_joint = Matrix{eltype(rho)}(undef, len_, Nsim)
@inbounds for j = 1:Nstep
gausscopulagen2!(U_joint, rho, mcBaseData)
for i = 1:len_
@views tmp_ = S_Total[i][:, j+1]
sort!(tmp_)
@views tmp_ .= (mcProcess.models[i].underlying.S0) .* exp.(Statistics.quantile(tmp_, U_joint[i, :]; sorted = true))
end
end
## Conclude
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2116 | """
Struct for ShiftedLogNormalMixture
lnmModel=ShiftedLogNormalMixture(η::Array{num1},λ::Array{num2},num3) where {num1,num2,num3<: Number}
Where:
η = Array of volatilities.
λ = Array of weights.
α = shift.
"""
struct ShiftedLogNormalMixture{num <: Number, num2 <: Number, num3 <: Number, abstrUnderlying <: AbstractUnderlying, numtype <: Number} <: ItoProcess{numtype}
η::Array{num, 1}
λ::Array{num2, 1}
α::num3
underlying::abstrUnderlying
function ShiftedLogNormalMixture(η::Array{num, 1}, λ::Array{num2, 1}, α::num3, underlying::abstrUnderlying) where {num <: Number, num2 <: Number, num3 <: Number, abstrUnderlying <: AbstractUnderlying}
ChainRulesCore.@ignore_derivatives @assert minimum(η) > 0 "Volatilities must be positive"
ChainRulesCore.@ignore_derivatives @assert minimum(λ) > 0 "weights must be positive"
ChainRulesCore.@ignore_derivatives @assert sum(λ) <= 1.0 "λs must be weights"
ChainRulesCore.@ignore_derivatives @assert length(λ) == length(η) - 1 "Check vector lengths"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num2) + zero(num3)
return new{num, num2, num3, abstrUnderlying, typeof(zero_typed)}(η, λ, α, underlying)
end
end
export ShiftedLogNormalMixture;
function simulate!(X, mcProcess::ShiftedLogNormalMixture, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
ChainRulesCore.@ignore_derivatives @assert T > 0
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nstep = mcBaseData.Nstep
η_gbm = copy(mcProcess.η)
λ_gmb = copy(mcProcess.λ)
mu_gbm = r - d
dt = T / Nstep
A0 = S0 * (1 - mcProcess.α)
simulate!(X, LogNormalMixture(η_gbm, λ_gmb, Underlying(A0, d)), rfCurve, mcBaseData, T)
zero_typed = ChainRulesCore.@ignore_derivatives zero(typeof(integral(mu_gbm, dt) * dt))
array_type = get_array_type(mcBaseData, mcProcess, zero_typed)
tmp_::typeof(array_type) = exp.(integral(mu_gbm, t_) for t_ = 0:dt:T)
@. X = X + mcProcess.α * S0 * (tmp_')
return nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2946 | """
Struct for SubordinatedBrownianMotion
subordinatedBrownianMotion=SubordinatedBrownianMotion(sigma::num,drift::num1,underlying::abstrUnderlying)
Where:
sigma = Volatility.
drift = drift.
underlying = underlying.
"""
struct SubordinatedBrownianMotion{num <: Number, num1 <: Number, num2 <: Number, Distr <: Distribution{Univariate, Continuous}, numtype <: Number} <: AbstractMonteCarloProcess{numtype}
sigma::num
drift::num1
θ::num2
subordinator_::Distr
function SubordinatedBrownianMotion(sigma::num, drift::num1, θ::num2, dist::Distr) where {num <: Number, num1 <: Number, num2 <: Number, Distr <: Distribution{Univariate, Continuous}}
ChainRulesCore.@ignore_derivatives @assert sigma > 0 "volatility must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1)
return new{num, num1, num2, Distr, typeof(zero_typed)}(sigma, drift, θ, dist)
end
end
export SubordinatedBrownianMotion;
function simulate!(X, mcProcess::SubordinatedBrownianMotion, mcBaseData::SerialMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
dt = T / Nstep
drift = mcProcess.drift * dt
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0.0
type_sub = typeof(rand(mcBaseData.parallelMode.rng, mcProcess.subordinator_))
isDualZero = drift * zero(type_sub)
@views X[:, 1] .= isDualZero
Z = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
dt_s = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim)
θ = mcProcess.θ
@inbounds for i = 1:Nstep
rand!(mcBaseData.parallelMode.rng, mcProcess.subordinator_, dt_s)
randn!(mcBaseData.parallelMode.rng, Z)
@views @. X[:, i+1] = X[:, i] + drift + θ * dt_s + sigma * sqrt(dt_s) * Z
end
end
function simulate!(X, mcProcess::SubordinatedBrownianMotion, mcBaseData::SerialAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
dt = T / Nstep
drift = mcProcess.drift * dt
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0.0
type_sub = typeof(quantile(mcProcess.subordinator_, 0.5))
isDualZero = drift * sigma * zero(type_sub) * 0.0
@views X[:, 1] .= isDualZero
Nsim_2 = div(Nsim, 2)
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
Z = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
dt_s = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
θ = mcProcess.θ
@inbounds for j = 1:Nstep
rand!(mcBaseData.parallelMode.rng, mcProcess.subordinator_, dt_s)
randn!(mcBaseData.parallelMode.rng, Z)
sqrt_dt_s = sqrt.(dt_s)
@views @. Xp[:, j+1] = Xp[:, j] + dt_s * θ + drift + sqrt_dt_s * Z * sigma
@views @. Xm[:, j+1] = Xm[:, j] + dt_s * θ + drift - sqrt_dt_s * Z * sigma
end
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3778 | """
Struct for SubordinatedBrownianMotion
subordinatedBrownianMotion=SubordinatedBrownianMotion(sigma::num,drift::num1)
Where:
sigma = Volatility.
drift = drift.
underlying = underlying.
"""
struct SubordinatedBrownianMotionVec{num <: Number, num1 <: Number, num4 <: Number, num2 <: Number, Distr <: Distribution{Univariate, Continuous}, numtype <: Number} <: AbstractMonteCarloProcess{numtype}
sigma::num
drift::CurveType{num1, num4}
θ::num2
subordinator_::Distr
function SubordinatedBrownianMotionVec(sigma::num, drift::CurveType{num1, num4}, θ::num2, dist::Distr) where {num <: Number, num1 <: Number, num2 <: Number, num4 <: Number, Distr <: Distribution{Univariate, Continuous}}
ChainRulesCore.@ignore_derivatives @assert sigma > 0 "volatility must be positive"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1) + zero(num4)
return new{num, num1, num4, num2, Distr, typeof(zero_typed)}(sigma, drift, θ, dist)
end
end
function SubordinatedBrownianMotion(σ::num, drift::CurveType{num1, num4}, θ::num2, subordinator_::Distr) where {num <: Number, num1 <: Number, num2 <: Number, num4 <: Number, Distr <: Distribution{Univariate, Continuous}}
return SubordinatedBrownianMotionVec(σ, drift, θ, subordinator_)
end
function simulate!(X, mcProcess::SubordinatedBrownianMotionVec, mcBaseData::SerialMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
drift = mcProcess.drift
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0
type_sub = typeof(quantile(mcProcess.subordinator_, 0.5))
dt_s = Array{type_sub}(undef, Nsim)
dt = T / Nstep
zero_drift = incremental_integral(drift, zero(type_sub), zero(type_sub) + dt) * 0
isDualZero = sigma * zero(type_sub) * zero_drift
@views X[:, 1] .= isDualZero
Z = Array{Float64}(undef, Nsim)
θ = mcProcess.θ
@inbounds for i = 1:Nstep
randn!(mcBaseData.parallelMode.rng, Z)
rand!(mcBaseData.parallelMode.rng, mcProcess.subordinator_, dt_s)
tmp_drift = incremental_integral(drift, (i - 1) * dt, dt)
# SUBORDINATED BROWNIAN MOTION (dt_s=time change)
@views @. X[:, i+1] = X[:, i] + tmp_drift + θ * dt_s + sigma * sqrt(dt_s) * Z
end
return
end
function simulate!(X, mcProcess::SubordinatedBrownianMotionVec, mcBaseData::SerialAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
type_sub = typeof(quantile(mcProcess.subordinator_, 0.5))
drift = mcProcess.drift
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
zero_drift = incremental_integral(drift, zero(type_sub), zero(type_sub) + dt) * 0
isDualZero = sigma * zero(type_sub) * zero_drift
@views X[:, 1] .= isDualZero
Nsim_2 = div(Nsim, 2)
dt_s = Array{type_sub}(undef, Nsim_2)
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
Z = Array{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
tmp_drift = Array{typeof(zero_drift)}(undef, Nsim_2)
θ = mcProcess.θ
@inbounds for i = 1:Nstep
randn!(mcBaseData.parallelMode.rng, Z)
rand!(mcBaseData.parallelMode.rng, mcProcess.subordinator_, dt_s)
# tmp_drift .= [incremental_integral(drift, t_, dt_) for (t_, dt_) in zip(t_s, dt_s)]
tmp_drift = incremental_integral(drift, (i - 1) * dt, dt)
# @. t_s += dt_s
# SUBORDINATED BROWNIAN MOTION (dt_s=time change)
@. @views Xp[:, i+1] = Xp[:, i] + tmp_drift + dt_s * θ + sigma * sqrt(dt_s) * Z
@. @views Xm[:, i+1] = Xm[:, i] + tmp_drift + dt_s * θ - sigma * sqrt(dt_s) * Z
end
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 2141 | using Sobol, StatsFuns
function simulate!(X, mcProcess::SubordinatedBrownianMotion, mcBaseData::SerialSobolMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
drift = mcProcess.drift * T / Nstep
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0
type_sub = typeof(quantile(mcProcess.subordinator_, 0.5))
isDualZero = drift * zero(type_sub) * 0.0
@views X[:, 1] .= isDualZero
seq = SobolSeq(Nstep)
skip(seq, Nstep * Nsim)
vec = Array{typeof(get_rng_type(isDualZero))}(undef, Nstep)
θ = mcProcess.θ
@inbounds for i = 1:Nsim
next!(seq, vec)
@. vec = norminvcdf(vec)
@inbounds for j = 1:Nstep
dt_s = rand(mcBaseData.parallelMode.rng, mcProcess.subordinator_)
@views X[i, j+1] = X[i, j] + drift + θ * dt_s + sigma * sqrt(dt_s) * vec[j]
end
end
end
function simulate!(X, mcProcess::SubordinatedBrownianMotionVec, mcBaseData::SerialSobolMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
drift = mcProcess.drift
dt = T / Nstep
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0
type_sub = typeof(quantile(mcProcess.subordinator_, 0.5))
zero_drift = incremental_integral(drift, zero(type_sub), zero(type_sub) + T / Nstep) * 0
isDualZero = zero_drift * zero(type_sub) * 0
@views X[:, 1] .= isDualZero
seq = SobolSeq(Nstep)
skip(seq, Nstep * Nsim)
vec = Array{typeof(get_rng_type(isDualZero))}(undef, Nstep)
θ = mcProcess.θ
@inbounds for i = 1:Nsim
# t_s = zero(type_sub)
next!(seq, vec)
@. vec = norminvcdf(vec)
@inbounds for j = 1:Nstep
dt_s = rand(mcBaseData.parallelMode.rng, mcProcess.subordinator_)
# tmp_drift = incremental_integral(drift, t_s, dt_s)
tmp_drift = incremental_integral(drift, (j - 1) * dt, dt)
# t_s += dt_s
@views X[i, j+1] = X[i, j] + tmp_drift + θ * dt_s + sigma * sqrt(dt_s) * vec[j]
end
end
return X
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 276 | function gausscopulagen2!(z, Σ::Matrix{Float64}, mcBaseData::AbstractMonteCarloConfiguration)
rand!(mcBaseData.parallelMode.rng, MvNormal(Σ), z)
@inbounds for i = 1:size(Σ, 2)
d = Normal(0, sqrt(Σ[i, i]))
@views @. z[i, :] = cdf(d, z[i, :])
end
end | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1789 | """
Struct for VG Process
vgProcess=VarianceGammaProcess(σ::num1,θ::num2,κ::num3) where {num1,num2,num3<: Number}
Where:
σ = volatility of the process.
θ = variance of volatility.
κ = skewness of volatility.
"""
struct VarianceGammaProcess{num <: Number, num1 <: Number, num2 <: Number, abstrUnderlying <: AbstractUnderlying, numtype <: Number} <: InfiniteActivityProcess{numtype}
σ::num
θ::num1
κ::num2
underlying::abstrUnderlying
function VarianceGammaProcess(σ::num, θ::num1, κ::num2, underlying::abstrUnderlying) where {num <: Number, num1 <: Number, num2 <: Number, abstrUnderlying <: AbstractUnderlying}
ChainRulesCore.@ignore_derivatives @assert σ > 0 "volatility must be positive"
ChainRulesCore.@ignore_derivatives @assert κ > 0 "κappa must be positive"
ChainRulesCore.@ignore_derivatives @assert 1 - σ * σ * κ / 2 - θ * κ >= 0 "Parameters with unfeasible values"
zero_typed = ChainRulesCore.@ignore_derivatives zero(num) + zero(num1) + zero(num2)
return new{num, num1, num2, abstrUnderlying, typeof(zero_typed)}(σ, θ, κ, underlying)
end
end
export VarianceGammaProcess;
function simulate!(X, mcProcess::VarianceGammaProcess, rfCurve::AbstractZeroRateCurve, mcBaseData::AbstractMonteCarloConfiguration, T::Number)
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
θ = mcProcess.θ
κ = mcProcess.κ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
ψ = -1 / κ * log(1 - σ^2 * κ / 2 - θ * κ)
drift = r - d - ψ
gammaRandomVariable = Gamma(dt / κ, κ)
simulate!(X, SubordinatedBrownianMotion(σ, drift, θ, gammaRandomVariable), mcBaseData, T)
@. X = S0 * exp(X)
nothing
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1632 |
function simulate!(X_cu, mcProcess::BrownianMotion, mcBaseData::CudaMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
mean_bm = μ * dt
stddev_bm = σ * sqrt(dt)
isDualZero = mean_bm * stddev_bm * zero(Int8)
@views fill!(X_cu[:, 1], isDualZero) #more efficient than @views X_cu[:, 1] .= isDualZero
Z = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
@inbounds for i = 1:Nstep
randn!(CUDA.CURAND.default_rng(), Z)
@views @. X_cu[:, i+1] = X_cu[:, i] + mean_bm + stddev_bm * Z
end
return
end
function simulate!(X_cu, mcProcess::BrownianMotion, mcBaseData::CudaAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
mean_bm = μ * dt
stddev_bm = σ * sqrt(dt)
isDualZero = mean_bm * stddev_bm * zero(Int8)
Nsim_2 = div(Nsim, 2)
@views fill!(X_cu[:, 1], isDualZero) #more efficient than @views X_cu[:, 1] .= isDualZero
X_cu_p = view(X_cu, 1:Nsim_2, :)
X_cu_m = view(X_cu, (Nsim_2+1):Nsim, :)
Z = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
for i = 1:Nstep
randn!(CUDA.CURAND.default_rng(), Z)
@views @inbounds @. X_cu_p[:, i+1] = X_cu_p[:, i] + mean_bm + stddev_bm * Z
@views @inbounds @. X_cu_m[:, i+1] = X_cu_m[:, i] + mean_bm - stddev_bm * Z
end
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 1770 |
function simulate!(X_cu, mcProcess::BrownianMotionVec, mcBaseData::CudaMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
stddev_bm = σ * sqrt(dt)
zero_drift = incremental_integral(μ, dt * 0, dt)
isDualZero = stddev_bm * 0 * zero_drift
Z = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
@views fill!(X_cu[:, 1], isDualZero) #more efficient than @views X_cu[:, 1] .= isDualZero
for i = 1:Nstep
tmp_ = incremental_integral(μ, (i - 1) * dt, dt)
randn!(CUDA.CURAND.default_rng(), Z)
@inbounds @. X_cu[:, i+1] = X_cu[:, i] + tmp_ + stddev_bm * Z
end
return
end
function simulate!(X_cu, mcProcess::BrownianMotionVec, mcBaseData::CudaAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
μ = mcProcess.μ
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
stddev_bm = σ * sqrt(dt)
zero_drift = incremental_integral(μ, dt * 0, dt)
isDualZero = stddev_bm * 0 * zero_drift
Nsim_2 = div(Nsim, 2)
@views fill!(X_cu[:, 1], isDualZero) #more efficient than @views X_cu[:, 1] .= isDualZero
X_cu_p = view(X_cu, 1:Nsim_2, :)
X_cu_m = view(X_cu, (Nsim_2+1):Nsim, :)
Z = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
for i = 1:Nstep
randn!(CUDA.CURAND.default_rng(), Z)
tmp_ = incremental_integral(μ, (i - 1) * dt, dt)
@views @. X_cu_p[:, i+1] = X_cu_p[:, i] + tmp_ + stddev_bm * Z
@views @. X_cu_m[:, i+1] = X_cu_m[:, i] + tmp_ - stddev_bm * Z
end
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 256 | include("brownian_motion_cuda.jl")
include("brownian_motion_cuda_aug.jl")
include("heston_cuda.jl")
include("heston_aug_cuda.jl")
include("fa_levy_cuda.jl")
include("subordinated_brownian_motion_cuda.jl")
include("subordinated_brownian_motion_aug_cuda.jl") | FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 869 |
function simulate!(X, mcProcess::finiteActivityProcess, rfCurve::AbstractZeroRateCurve, mcBaseData::MonteCarloConfiguration{type1, type2, type3, CudaMode}, T::numb) where {finiteActivityProcess <: FiniteActivityProcess, numb <: Number, type1 <: Number, type2 <: Number, type3 <: AbstractMonteCarloMethod}
r = rfCurve.r
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
λ = mcProcess.λ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
## Simulate
# r-d-psi(-i)
drift_rn = (r - d) - σ^2 / 2 - λ * compute_drift(mcProcess)
simulate!(X, BrownianMotion(σ, drift_rn), mcBaseData, T)
X_incr = zeros(Nsim, Nstep + 1)
add_jump_matrix!(X_incr, mcProcess, mcBaseData, T)
## Conclude
S0 = mcProcess.underlying.S0
X_incr_cu = cu(X_incr)
@. X = S0 * exp(X + X_incr_cu)
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3460 |
function simulate!(X, mcProcess::HestonProcess, rfCurve::ZeroRateCurve, mcBaseData::CudaMonteCarloConfig, T::numb) where {numb <: Number}
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ₀ = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / (κ + λ1)
r_d = r - d
dt = T / Nstep
zero_drift = incremental_integral(r_d, dt * 0.0, dt)
isDualZeroVol = zero(T * σ₀ * κ * θ * λ1 * σ * ρ * zero_drift)
isDualZero = S0 * isDualZeroVol
X[:, 1] .= isDualZero
v_m = CUDA.zeros(typeof(isDualZero), Nsim) .+ σ₀^2
isDualZeroVol_eps = isDualZeroVol + eps(isDualZeroVol)
e1 = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
e2_rho = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
e2 = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
@inbounds for j = 1:Nstep
randn!(CUDA.CURAND.default_rng(), e1)
randn!(CUDA.CURAND.default_rng(), e2_rho)
@. e2 = e1 * ρ + e2_rho * sqrt(1 - ρ * ρ)
tmp_ = incremental_integral(r_d, (j - 1) * dt, dt)
@. @views X[:, j+1] = X[:, j] + (tmp_ - 0.5 * v_m * dt) + sqrt(v_m) * sqrt(dt) * e1
@. v_m += κ_s * (θ_s - v_m) * dt + σ * sqrt(v_m) * sqrt(dt) * e2
@. v_m = max(v_m, isDualZeroVol_eps)
end
## Conclude
X .= S0 .* exp.(X)
return
end
function simulate!(X, mcProcess::HestonProcess, rfCurve::ZeroRateCurve, mcBaseData::CudaAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
r = rfCurve.r
S0 = mcProcess.underlying.S0
d = dividend(mcProcess)
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ₀ = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0.0
####Simulation
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / (κ + λ1)
dt = T / Nstep
isDualZeroVol = zero(T * σ₀ * θ_s * σ * ρ)
isDualZero = S0 * isDualZeroVol
X[:, 1] .= isDualZero
Nsim_2 = div(Nsim, 2)
r_d = r - d
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
v_mp = CUDA.zeros(typeof(isDualZero), Nsim_2) .+ σ₀^2
v_mm = CUDA.zeros(typeof(isDualZero), Nsim_2) .+ σ₀^2
e1 = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
e2_rho = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
e2 = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
isDualZeroVol_eps = isDualZeroVol + eps(isDualZeroVol)
for j = 1:Nstep
randn!(CUDA.CURAND.default_rng(), e1)
randn!(CUDA.CURAND.default_rng(), e2_rho)
@. e2 = e1 * ρ + e2_rho * sqrt(1 - ρ * ρ)
tmp_ = incremental_integral(r_d, (j - 1) * dt, dt)
@. @views Xp[:, j+1] = Xp[:, j] + (tmp_ - 0.5 * v_mp .* dt) + sqrt(max.(v_mp, 0)) * sqrt(dt) * e1
@. @views Xm[:, j+1] = Xm[:, j] + (tmp_ - 0.5 * v_mm .* dt) - sqrt(max.(v_mm, 0)) * sqrt(dt) * e1
@. v_mp += κ_s * (θ_s - v_mp) * dt + (σ * sqrt(dt)) * sqrt(v_mp) * e2
@. v_mm += κ_s * (θ_s - v_mm) * dt - (σ * sqrt(dt)) * sqrt(v_mm) * e2
@. v_mp = max(v_mp, isDualZeroVol_eps)
@. v_mm = max(v_mm, isDualZeroVol_eps)
end
## Conclude
@. X = S0 * exp(X)
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3525 |
function simulate!(X, mcProcess::HestonProcess, spotData::ZeroRate, mcBaseData::CudaMonteCarloConfig, T::numb) where {numb <: Number}
r = spotData.r
S0 = mcProcess.underlying.S0
d = mcProcess.underlying.d
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ_zero = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0
####Simulation
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / (κ + λ1)
r_d = r - d
dt = T / Nstep
isDualZeroVol = zero(T * r * σ_zero * κ * θ * λ1 * σ * ρ)
isDualZero = zero(S0 * isDualZeroVol)
@views fill!(X[:, 1], isDualZero) #more efficient than @views X_cu[:, 1] .= isDualZero
v_m = CUDA.zeros(typeof(isDualZeroVol), Nsim) .+ σ_zero^2
e1 = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
e2_rho = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
e2 = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
isDualZero_eps = isDualZeroVol + eps(isDualZeroVol)
for j = 1:Nstep
randn!(CUDA.CURAND.default_rng(), e1)
randn!(CUDA.CURAND.default_rng(), e2_rho)
@. e2 = e1 * ρ + e2_rho * sqrt(1 - ρ * ρ)
@views @inbounds @. X[:, j+1] = X[:, j] + (r_d - 0.5 * v_m) * dt + sqrt(v_m) * sqrt(dt) * e1
@. v_m += κ_s * (θ_s - v_m) * dt + σ * sqrt(v_m) * sqrt(dt) * e2
#when v_m = 0.0, the derivative becomes NaN
@. v_m = max(v_m, isDualZero_eps)
end
## Conclude
@. X = S0 * exp(X)
return
end
function simulate!(X, mcProcess::HestonProcess, spotData::ZeroRate, mcBaseData::CudaAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
r = spotData.r
S0 = mcProcess.underlying.S0
d = mcProcess.underlying.d
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
σ = mcProcess.σ
σ_zero = mcProcess.σ₀
λ1 = mcProcess.λ
κ = mcProcess.κ
ρ = mcProcess.ρ
θ = mcProcess.θ
ChainRulesCore.@ignore_derivatives @assert T > 0
####Simulation
## Simulate
κ_s = κ + λ1
θ_s = κ * θ / (κ + λ1)
r_d = r - d
dt = T / Nstep
isDualZeroVol = zero(T * r * σ_zero * κ * θ * λ1 * σ * ρ)
isDualZero = zero(S0 * isDualZeroVol)
@views fill!(X[:, 1], isDualZero) #more efficient than @views X_cu[:, 1] .= isDualZero
Nsim_2 = div(Nsim, 2)
e1 = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
e2_rho = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
e2 = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
v_m_1 = CUDA.zeros(typeof(isDualZeroVol), Nsim_2) .+ σ_zero^2
v_m_2 = CUDA.zeros(typeof(isDualZeroVol), Nsim_2) .+ σ_zero^2
isDualZero_eps = isDualZeroVol + eps(isDualZeroVol)
@inbounds for j = 1:Nstep
randn!(CUDA.CURAND.default_rng(), e1)
randn!(CUDA.CURAND.default_rng(), e2_rho)
@. e2 = -(e1 * ρ + e2_rho * sqrt(1 - ρ * ρ))
@views @. Xp[:, j+1] = Xp[:, j] + (r_d - 0.5 * v_m_1) * dt + sqrt(v_m_1) * sqrt(dt) * e1
@views @. Xm[:, j+1] = Xm[:, j] + (r_d - 0.5 * v_m_2) * dt - sqrt(v_m_2) * sqrt(dt) * e1
@. v_m_1 += κ_s * (θ_s - v_m_1) * dt + σ * sqrt(v_m_1) * sqrt(dt) * e2
@. v_m_2 += κ_s * (θ_s - v_m_2) * dt - σ * sqrt(v_m_2) * sqrt(dt) * e2
@. v_m_1 = max(v_m_1, isDualZero_eps)
@. v_m_2 = max(v_m_2, isDualZero_eps)
end
## Conclude
@. X = S0 * exp(X)
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
|
[
"MIT"
] | 0.3.2 | 728c49a9de6ffe78fceb7bcba3b53db070fa5532 | code | 3233 |
function simulate!(X, mcProcess::SubordinatedBrownianMotionVec, mcBaseData::CudaMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
drift = mcProcess.drift
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0
type_sub = typeof(quantile(mcProcess.subordinator_, 0.5))
dt_s_cpu = Array{type_sub}(undef, Nsim)
dt_s = CuArray{type_sub}(undef, Nsim)
# t_s = zeros(type_sub, Nsim)
dt = T / Nstep
zero_drift = incremental_integral(drift, zero(type_sub), zero(type_sub) + dt) * 0
isDualZero = sigma * zero(type_sub) * 0 * zero_drift
@views fill!(X[:, 1], isDualZero) #more efficient than @views X[:, 1] .= isDualZero
Z = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim)
# tmp_drift = Array{typeof(zero_drift)}(undef, Nsim)
# tmp_drift_gpu = CuArray{typeof(zero_drift)}(undef, Nsim)
θ = mcProcess.θ
@inbounds for i = 1:Nstep
randn!(CUDA.CURAND.default_rng(), Z)
rand!(mcBaseData.parallelMode.rng, mcProcess.subordinator_, dt_s_cpu)
# tmp_drift .= [incremental_integral(drift, t_, dt_) for (t_, dt_) in zip(t_s, dt_s_cpu)]
tmp_drift = incremental_integral(drift, (i - 1) * dt, dt)
# tmp_drift_gpu .= cu(tmp_drift)
# @. t_s += dt_s_cpu
dt_s .= cu(dt_s_cpu)
# SUBORDINATED BROWNIAN MOTION (dt_s=time change)
@views @. X[:, i+1] = X[:, i] + tmp_drift + θ * dt_s + sigma * sqrt(dt_s) * Z
end
return
end
function simulate!(X, mcProcess::SubordinatedBrownianMotionVec, mcBaseData::CudaAntitheticMonteCarloConfig, T::numb) where {numb <: Number}
Nsim = mcBaseData.Nsim
Nstep = mcBaseData.Nstep
type_sub = typeof(quantile(mcProcess.subordinator_, 0.5))
drift = mcProcess.drift
sigma = mcProcess.sigma
ChainRulesCore.@ignore_derivatives @assert T > 0
dt = T / Nstep
zero_drift = incremental_integral(drift, zero(type_sub), zero(type_sub) + dt)
isDualZero = sigma * zero(type_sub) * 0 * zero_drift
@views fill!(X[:, 1], isDualZero) #more efficient than @views X[:, 1] .= isDualZero
Nsim_2 = div(Nsim, 2)
dt_s = CuArray{type_sub}(undef, Nsim_2)
dt_s_cpu = Array{type_sub}(undef, Nsim_2)
# tmp_drift = Array{typeof(zero_drift)}(undef, Nsim_2)
# tmp_drift_gpu = CuArray{typeof(zero_drift)}(undef, Nsim_2)
# t_s = zeros(type_sub, Nsim_2)
Xp = @views X[1:Nsim_2, :]
Xm = @views X[(Nsim_2+1):end, :]
Z = CuArray{typeof(get_rng_type(isDualZero))}(undef, Nsim_2)
θ = mcProcess.θ
@inbounds for i = 1:Nstep
randn!(CUDA.CURAND.default_rng(), Z)
rand!(mcBaseData.parallelMode.rng, mcProcess.subordinator_, dt_s_cpu)
# tmp_drift .= [incremental_integral(drift, t_, dt_) for (t_, dt_) in zip(t_s, dt_s_cpu)]
tmp_drift = incremental_integral(drift, (i - 1) * dt, dt)
# @. t_s += dt_s_cpu
dt_s .= cu(dt_s_cpu)
# tmp_drift_gpu .= cu(tmp_drift)
# SUBORDINATED BROWNIAN MOTION (dt_s=time change)
@. @views Xp[:, i+1] = Xp[:, i] + tmp_drift + θ * dt_s + sigma * sqrt(dt_s) * Z
@. @views Xm[:, i+1] = Xm[:, i] + tmp_drift + θ * dt_s - sigma * sqrt(dt_s) * Z
end
return
end
| FinancialMonteCarlo | https://github.com/rcalxrc08/FinancialMonteCarlo.jl.git |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.