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.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
412
## CSV using .CSV read_table(::TableIOInterface.CSVFormat, filename:: AbstractString; kwargs...) = CSV.File(filename; kwargs...) read_table(::TableIOInterface.CSVFormat, io:: IO; kwargs...) = CSV.File(read(io); kwargs...) function write_table!(::TableIOInterface.CSVFormat, output:: Union{AbstractString, IO}, table; kwargs...) _checktable(table) table |> CSV.write(output; kwargs...) nothing end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
712
## JDF @info "JDF.jl is available - including functionality to read / write JDF files" using .JDF using DataFrames function read_table(::TableIOInterface.JDFFormat, filename:: AbstractString; kwargs...) return JDF.load(filename; kwargs...) end function write_table!(::TableIOInterface.JDFFormat, filename:: AbstractString, table:: DataFrame; kwargs...) JDF.save(filename, table; kwargs...) nothing end # JDF supports only DataFrames, not arbitrary Tables.jl inputs. For export, the table is converted to a DataFrame first. write_table!(::TableIOInterface.JDFFormat, filename:: AbstractString, table; kwargs...) = write_table!(TableIOInterface.JDFFormat(), filename, DataFrame(table); kwargs...)
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
962
@info "JLD2.jl is available - including functionality to read / write JLD2 files" import .JLD2 function read_table(::TableIOInterface.JLD2Format, filename:: AbstractString, tablename:: AbstractString; kwargs...) return JLD2.jldopen(filename, "r") do file file[tablename] end end function read_table(::TableIOInterface.JLD2Format, filename:: AbstractString; kwargs...) return JLD2.jldopen(filename, "r") do file table_list = keys(file) |> sort file[first(table_list)] end end function write_table!(::TableIOInterface.JLD2Format, filename:: AbstractString, tablename:: AbstractString, table; kwargs...) _checktable(table) _checktablename(tablename) JLD2.jldopen(filename, "a+") do file file[tablename] = table end nothing end function list_tables(::TableIOInterface.JLD2Format, filename:: AbstractString) return JLD2.jldopen(filename, "r") do file keys(file) |> sort end end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
993
using .JSONTables function read_table(::TableIOInterface.JSONFormat, filename:: AbstractString) local output open(filename, "r") do file output = read_table(TableIOInterface.JSONFormat(), file) end return output end read_table(::TableIOInterface.JSONFormat, io:: IO) = jsontable(io) function write_table!(::TableIOInterface.JSONFormat, filename:: AbstractString, table; orientation=:objecttable) open(filename, "w") do file write_table!(TableIOInterface.JSONFormat(), file, table; orientation=orientation) end nothing end function write_table!(::TableIOInterface.JSONFormat, io:: IO, table; orientation=:objecttable) _checktable(table) if orientation == :objecttable export_func = JSONTables.objecttable elseif orientation == :arraytable export_func = JSONTables.arraytable else error("`orientation` must be `:objecttable` (default) or `:arraytable`") end export_func(io, table) nothing end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
853
# stores Table as Julia code, precisely as NamedTuple of Arrays. _convert_to_named_tuple(table) = (; pairs(eachcol(table))...) # e.g. for DataFrames _convert_to_named_tuple(table:: T) where {T <: NamedTuple{<: AbstractArray}} = table # Do not change anything for NamedTuple of arrays function _convert_to_named_tuple(table:: T) where {T <: AbstractArray{<: NamedTuple}} column_names = keys(first(table)) data = [getproperty.(table, col) for col in column_names] return NamedTuple{column_names}(data) end function write_table!(::TableIOInterface.JuliaFormat, filename:: AbstractString, tablename:: AbstractString, table) _checktable(table) _checktablename(tablename) table_as_tuple = _convert_to_named_tuple(table) open(filename, "a") do file println(file, tablename, " = ", table_as_tuple) end nothing end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
1577
@info "Pandas.jl is available - including additional file formats using Python Pandas" import .Pandas import DataFrames # HDF5 formats function read_table(::TableIOInterface.HDF5Format, filename, key; kwargs...):: Pandas.DataFrame df_pandas = Pandas.read_hdf(filename, key; kwargs) return df_pandas end function read_table(t::TableIOInterface.HDF5Format, filename; kwargs...):: Pandas.DataFrame hdf = Pandas.HDFStore(filename) try table_list = _list_tables(t, hdf) length(table_list) > 1 && @warn "File contains more than one table, the alphabetically first one is taken" key = first(table_list) return Pandas.read_hdf(filename, key; kwargs) finally close(hdf) end end function write_table!(::TableIOInterface.HDF5Format, filename, tablename, table:: Pandas.DataFrame; kwargs...) # for HDF5 files, the table name may contain a path, therefore _checktablename is not executed. # Pandas.DataFrame has no Tables.jl compatible interface, therefore _checktable is not executed. Pandas.to_hdf(table, filename, tablename; kwargs...) nothing end write_table!(::TableIOInterface.HDF5Format, filename, tablename, table; kwargs...) = write_table!(TableIOInterface.HDF5Format(), filename, tablename, Pandas.DataFrame(table); kwargs...) function list_tables(t::TableIOInterface.HDF5Format, filename:: AbstractString) hdf = Pandas.HDFStore(filename) try _list_tables(t, hdf) finally close(hdf) end end _list_tables(::TableIOInterface.HDF5Format, hdf) = keys(hdf) |> sort
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
770
## Parquet @info "Parquet.jl is available - including functionality to read / write Parquet files" using .Parquet """ For strings (plus potentially additional data types), the binary representation in Parquet must be specified when reading the file. A general mapping can be given with the keyword argument `map_logical_types`. Alternatively, the string columns can be given """ function read_table(::TableIOInterface.ParquetFormat, filename; kwargs...) parfile = Parquet.File(filename; kwargs...) try return RecordCursor(parfile) finally close(parfile) end end function write_table!(::TableIOInterface.ParquetFormat, filename, table; kwargs...) _checktable(table) write_parquet(filename, table; kwargs...) nothing end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
1989
# PostgreSQL @info "LibPQ.jl is available - including functionality to read / write PostgreSQL databases" using .LibPQ using .CSV """ read_table(conn:: LibPQ.Connection, tablename:: AbstractString) Reads the content of a whole table and returns a Tables.jl compatible object. """ function read_table(conn:: LibPQ.Connection, tablename:: AbstractString; kwargs...) _checktablename(tablename) return execute(conn, "select * from $tablename") # SQL parameters cannot be used for table names end read_sql(conn:: LibPQ.Connection, sql:: AbstractString) = execute(conn, sql) """ write_table(conn:: LibPQ.Connection, tablename:: AbstractString, table) Writes data into an existing PostgreSQL table. The table columns must have the same names as in the input table and the types must be compliant. It is OK to have more types in the PostgreSQL table than in the input table if these columns are nullable. Note that this method does not create a non-existing table (in contrast to the corresponding SQLite method). This is a design decision because PostgreSQL databases are usually more persistant than (often "throw-away") SQLite databases. This method is using `COPY FROM STDIN` on CSV data, which is much faster than uploading using SQL statements. """ function write_table!(conn:: LibPQ.Connection, tablename:: AbstractString, table; kwargs...) # Uploading data to P _checktable(table) _checktablename(tablename) iter = CSV.RowWriter(table) column_names = first(iter) copyin = LibPQ.CopyIn("COPY $tablename ($column_names) FROM STDIN (FORMAT CSV, HEADER);", iter) execute(conn, copyin) nothing end function list_tables(conn:: LibPQ.Connection) res = execute(conn, """SELECT table_name FROM information_schema.tables where table_type in ('LOCAL TEMPORARY', 'BASE TABLE') and table_schema not in ('pg_catalog', 'information_schema');""") return collect(Tables.columntable(res).table_name) |> sort end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
2555
#SQLite @info "SQLite.jl is available - including functionality to read / write SQLite databases" using .SQLite function read_table(::TableIOInterface.SQLiteFormat, filename:: AbstractString, tablename:: AbstractString; kwargs...) db = SQLite.DB(filename) result = read_table(db, tablename; kwargs...) return result end function read_table(::TableIOInterface.SQLiteFormat, filename:: AbstractString; kwargs...) db = SQLite.DB(filename) result = read_table(db; kwargs...) return result end """ read_table(db:: SQLite.DB, tablename:: AbstractString; kwargs...) Reads the content of a whole table and returns a Tables.jl compatible object. This method takes an instance of an SQLite database connection as input. """ function read_table(db:: SQLite.DB, tablename:: AbstractString; kwargs...) _checktablename(tablename) result = DBInterface.execute(db, "select * from $tablename") # SQL parameters cannot be used for table names return result end function read_table(db:: SQLite.DB; kwargs...) table_list = list_tables(db) length(table_list) > 1 && @warn "File contains more than one table, the alphabetically first one is taken" return read_table(db, first(table_list); kwargs...) end read_sql(db:: SQLite.DB, sql:: AbstractString) = DBInterface.execute(db, sql) function write_table!(::TableIOInterface.SQLiteFormat, filename:: AbstractString, tablename:: AbstractString, table; kwargs...) _checktable(table) _checktablename(tablename) db = SQLite.DB(filename) try write_table!(db, tablename, table; kwargs...) finally close(db) end nothing end """ write_table(db:: SQLite.DB, tablename:: AbstractString, table; kwargs...) Writes the data into a new table in the SQLite database. As default, this operation will fail if the table already exists. Different behavior can be specified using the `kwargs` passed to `SQLite.load!`. Note that this behavior is different to the one for PostgreSQL, where the table must already exist. """ function write_table!(db:: SQLite.DB, tablename:: AbstractString, table; kwargs...) _checktable(table) _checktablename(tablename) table |> SQLite.load!(db, tablename; kwargs...) nothing end function list_tables(::TableIOInterface.SQLiteFormat, filename:: AbstractString) db = SQLite.DB(filename) try return list_tables(db) finally close(db) end end function list_tables(db:: SQLite.DB) files = getfield.(SQLite.tables(db), :name) return files |> sort end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
446
## StatFiles.jl - Stata, SPSS, SAS @info "StatFiles.jl is available - including functionality to read / write Stata, SAS and SPSS files" import .StatFiles const StatFilesTypes = Union{TableIOInterface.StataFormat, TableIOInterface.SPSSFormat, TableIOInterface.SASFormat} # dispatching to the concrete format is done in StatFiles.jl function read_table(::StatFilesTypes, filename; kwargs...) return StatFiles.load(filename; kwargs...) end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
1877
## Excel @info "XLSX.jl is available - including functionality to read / write Excel (xlsx) files" using .XLSX function read_table(::TableIOInterface.ExcelFormat, filename:: AbstractString, sheetname:: AbstractString; kwargs...) xf = XLSX.readxlsx(filename) try sheet = xf[sheetname] return _eachtablerow(sheet; kwargs...) finally close(xf) end end function read_table(t::TableIOInterface.ExcelFormat, filename:: AbstractString; kwargs...) xf = XLSX.readxlsx(filename) try table_list = _list_tables(t, xf) length(table_list) > 1 && @warn "File contains more than one table, the alphabetically first one is taken" sheet = xf[first(table_list)] return _eachtablerow(sheet; kwargs...) finally close(xf) end end _eachtablerow(sheet; columns=nothing, kwargs...) = isnothing(columns) ? XLSX.eachtablerow(sheet; kwargs...) : XLSX.eachtablerow(sheet, columns; kwargs...) function write_table!(::TableIOInterface.ExcelFormat, filename:: AbstractString, tablename:: AbstractString, table:: DataFrame; kwargs...) _checktable(table) _checktablename(tablename) XLSX.writetable(filename, table; overwrite=true, sheetname=tablename, kwargs...) nothing end # XLSX supports only DataFrames, not arbitrary Tables.jl inputs. For export, the table is converted to a DataFrame first. write_table!(::TableIOInterface.ExcelFormat, filename:: AbstractString, tablename:: AbstractString, table; kwargs...) = write_table!(TableIOInterface.ExcelFormat(), filename, tablename, DataFrame(table); kwargs...) function list_tables(t::TableIOInterface.ExcelFormat, filename:: AbstractString) xf = XLSX.readxlsx(filename) try return _list_tables(t, xf) finally close(xf) end end _list_tables(::TableIOInterface.ExcelFormat, xf) = XLSX.sheetnames(xf) |> sort
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
2614
## Zipped CSV Format # see https://juliadata.github.io/CSV.jl/stable/#Reading-CSV-from-gzip-(.gz)-and-zip-files-1 @info "ZipFile.jl is available - including functionality to read / write zipped files" using .ZipFile function read_table(t::TableIOInterface.ZippedFormat, zip_filename:: AbstractString; kwargs...) zf = ZipFile.Reader(zip_filename) try table_list = _list_tables(t, zf) length(table_list) > 1 && @warn "File contains more than one table, the alphabetically first one is taken" file_in_zip = filter(x->x.name == first(table_list), zf.files)[1] output = read_table(file_in_zip; kwargs...) return output finally close(zf) end end """ This method supports multiple files inside the zip file. The name of the file inside the zip file must be given. """ function read_table(::TableIOInterface.ZippedFormat, zip_filename:: AbstractString, csv_filename:: AbstractString; kwargs...) zf = ZipFile.Reader(zip_filename) try file_in_zip = filter(x->x.name == csv_filename, zf.files)[1] output = read_table(file_in_zip; kwargs...) return output finally close(zf) end end function read_table(file_in_zip:: ZipFile.ReadableFile; kwargs...) file_type = get_file_type(file_in_zip.name) return read_table(file_type, file_in_zip; kwargs...) end """ The csv file inside the zip archive is named analogue to the zip file, but with `.csv` extension. """ function write_table!(::TableIOInterface.ZippedFormat, zip_filename:: AbstractString, table; kwargs...) _checktable(table) csv_filename = string(splitext(basename(zip_filename))[1], ".csv") write_table!(TableIOInterface.ZippedFormat(), zip_filename, csv_filename, table; kwargs...) nothing end """ Writing as arbitrary file name and file format in a zip file. """ function write_table!(::TableIOInterface.ZippedFormat, zip_filename:: AbstractString, filename_in_zip:: AbstractString, table; kwargs...) _checktable(table) zf = ZipFile.Writer(zip_filename) try file_in_zip = ZipFile.addfile(zf, filename_in_zip, method=ZipFile.Deflate) file_type_in_zip = get_file_type(filename_in_zip) write_table!(file_type_in_zip, file_in_zip, table; kwargs...) finally close(zf) end nothing end function list_tables(t::TableIOInterface.ZippedFormat, filename:: AbstractString) zf = ZipFile.Reader(filename) try return _list_tables(t, zf) finally close(zf) end end _list_tables(::TableIOInterface.ZippedFormat, zf) = [f.name for f in zf.files] |> sort
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
2197
@testset "Database IO" begin @testset "SQLite" begin using SQLite fname = joinpath(testpath, "test.db") db = SQLite.DB(fname) write_table!(db, "test1", df) @test filesize(fname) > 0 @test list_tables(fname) == ["test1"] df_recovered = DataFrame(read_table(fname, "test1"); copycols=false) @test df == df_recovered df_sql = DataFrame(read_sql(db, "select * from test1 where a < 5"); copycols=false) @test df[df.a .< 5, :] == df_sql write_table!(fname, "test2", nt) nt_recovered = read_table(db, "test2") @test DataFrame(nt) == DataFrame(nt_recovered) @test_logs (:warn, "File contains more than one table, the alphabetically first one is taken") df_recovered = DataFrame(read_table(fname); copycols=false) # fetch alphabetiacally first table @test df == df_recovered @test list_tables(db) == ["test1", "test2"] end @testset "PostgreSQL" begin # the following tests require a running PostgreSQL database. # `docker run --rm --detach --name test-libpqjl -e POSTGRES_HOST_AUTH_METHOD=trust -p 5432:5432 postgres` using LibPQ conn = LibPQ.Connection("dbname=postgres user=postgres") execute(conn, """CREATE TEMPORARY TABLE test1 ( a integer PRIMARY KEY, b numeric, c character varying, d boolean, e date, f character varying );""") write_table!(conn, "test1", df) df_recovered = DataFrame(read_table(conn, "test1"); copycols=false) @test df == df_recovered df_sql = DataFrame(read_sql(conn, "select * from test1 where a < 5"); copycols=false) @test df[df.a .< 5, :] == df_sql execute(conn, """CREATE TEMPORARY TABLE test2 ( a integer PRIMARY KEY, b numeric, c character varying );""") write_table!(conn, "test2", nt) nt_recovered = read_table(conn, "test2") @test DataFrame(nt) == DataFrame(nt_recovered) @test list_tables(conn) == ["test1", "test2"] close(conn) end end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
7903
@testset "File IO" begin @testset "CSV" begin using CSV fname = joinpath(testpath, "test.csv") write_table!(fname, df) @test filesize(fname) > 0 df_recovered = DataFrame(read_table(fname); copycols=false) @test df == df_recovered fname = joinpath(testpath, "test2.csv") write_table!(fname, nt) @test filesize(fname) > 0 nt_recovered = read_table(fname) @test DataFrame(nt) == DataFrame(nt_recovered) end @testset "JDF" begin using JDF fname = joinpath(testpath, "test.jdf") write_table!(fname, df) @test isdir(fname) # JDF creates a directory, not a single file df_recovered = DataFrame(read_table(fname); copycols=false) @test df == df_recovered fname = joinpath(testpath, "test2.jdf") write_table!(fname, nt) @test isdir(fname) # JDF creates a directory, not a single file nt_recovered = read_table(fname) @test DataFrame(nt) == DataFrame(nt_recovered) end @testset "Parquet" begin using Parquet df_parquet = df[!, Not(:e)] # Parquet currently does not support Date element type fname = joinpath(testpath, "test.parquet") write_table!(fname, df_parquet) @test filesize(fname) > 0 df_recovered = DataFrame(read_table(fname); copycols=false) @test df_parquet == df_recovered fname = joinpath(testpath, "test2.parquet") write_table!(fname, nt) @test filesize(fname) > 0 nt_recovered = read_table(fname) @test DataFrame(nt) == DataFrame(nt_recovered) end @testset "Arrow" begin using Arrow fname = joinpath(testpath, "test.arrow") write_table!(fname, df) @test filesize(fname) > 0 df_recovered = DataFrame(read_table(fname); copycols=false) @test df == df_recovered fname = joinpath(testpath, "test2.arrow") write_table!(fname, nt) @test filesize(fname) > 0 nt_recovered = read_table(fname) @test DataFrame(nt) == DataFrame(nt_recovered) end @testset "JLD2" begin using JLD2 fname = joinpath(testpath, "test.jld2") write_table!(fname, "table2", vcat(df, df)) write_table!(fname, "table1", df) @test filesize(fname) > 0 df_recovered = DataFrame(read_table(fname); copycols=false) @test df == df_recovered @test list_tables(fname) == ["table1", "table2"] end @testset "XLSX" begin using XLSX fname = joinpath(testpath, "test.xlsx") write_table!(fname, "test_sheet_42", df) @test filesize(fname) > 0 @test list_tables(fname) == ["test_sheet_42"] df_recovered = DataFrame(read_table(fname); copycols=false) @test df == df_recovered # import specific columns df_recovered = DataFrame(read_table(fname; columns="B:E"); copycols=false) @test select(df, :b, :c, :d, :e) == df_recovered fname = joinpath(testpath, "test2.xlsx") write_table!(fname, "sheet_1", nt) @test filesize(fname) > 0 nt_recovered = read_table(fname, "sheet_1") # default name @test DataFrame(nt) == DataFrame(nt_recovered) end @testset "JSON" begin using JSONTables fname = joinpath(testpath, "test_obj.json") write_table!(fname, df, orientation=:objecttable) @test filesize(fname) > 0 df_recovered = DataFrame(read_table(fname)) # note that DataFrame(; copycols=false) gives wrong column types! df_recovered.e = Date.(df_recovered.e) # Date format is not automatically detected, need to be converted manually @test df == df_recovered fname = joinpath(testpath, "test_array.json") write_table!(fname, df, orientation=:arraytable) @test filesize(fname) > 0 df_recovered = DataFrame(read_table(fname)) # note that DataFrame(; copycols=false) gives wrong column types! df_recovered.e = Date.(df_recovered.e) # Date format is not automatically detected, need to be converted manually @test df == df_recovered fname = joinpath(testpath, "test2.json") write_table!(fname, nt) @test filesize(fname) > 0 nt_recovered = read_table(fname) # default name @test DataFrame(nt) == DataFrame(nt_recovered) @test_throws ErrorException write_table!(fname, df, orientation=:xyz) end @testset "Julia" begin fname = joinpath(testpath, "test.jl") write_table!(fname, "my_jl_table1", df) write_table!(fname, "my_jl_table2", nt) @test filesize(fname) > 0 include(fname) @test df == DataFrame(my_jl_table1) @test DataFrame(nt) == DataFrame(my_jl_table2) end @testset "StatFiles" begin using StatFiles # test files taken from https://github.com/queryverse/StatFiles.jl df_recovered = DataFrame[] for ext in ("dta", "sav", "sas7bdat") fname = joinpath(@__DIR__, "types.$ext") push!(df_recovered, DataFrame(read_table(fname); copycols=false)) end @test size(df_recovered[1]) == size(df_recovered[2]) == size(df_recovered[3]) == (3, 6) @test dropmissing(df_recovered[1]) == dropmissing(df_recovered[2]) == dropmissing(df_recovered[3]) end @testset "zipped" begin using ZipFile fname = joinpath(testpath, "test.zip") write_table!(fname, df) @test filesize(fname) > 0 @test list_tables(fname) == ["test.csv"] df_recovered = DataFrame(read_table(fname); copycols=false) @test df == df_recovered fname = joinpath(testpath, "test2.zip") write_table!(fname, nt) @test filesize(fname) > 0 nt_recovered = read_table(fname, "test2.csv") @test DataFrame(nt) == DataFrame(nt_recovered) fname = joinpath(testpath, "test3.zip") write_table!(fname, "test.json", df; orientation=:arraytable) @test filesize(fname) > 0 df_recovered = read_table(fname, "test.json") |> DataFrame # note that DataFrame(; copycols=false) gives wrong column types! df_recovered.e = Date.(df_recovered.e) # Date format is not automatically detected, need to be converted manually @test df == df_recovered df_recovered = read_table(fname) |> DataFrame # note that DataFrame(; copycols=false) gives wrong column types! df_recovered.e = Date.(df_recovered.e) # Date format is not automatically detected, need to be converted manually @test df == df_recovered end @testset "conversions" begin using SQLite # file formats name1 = joinpath(testpath, "test.zip") name2 = joinpath(testpath, "testx.jdf") name3 = joinpath(testpath, "testx.xlsx") write_table!(name2, read_table(name1)) df_intermediate = DataFrame(read_table(name2)) df_intermediate.c = string.(df_intermediate.c) # XLSX.jl only supports plain string type df_intermediate.f = string.(df_intermediate.f) write_table!(name3, "my_sheet", df_intermediate) df_recovered = DataFrame(read_table(name3); copycols=true) @test df == df_recovered # SQLite from JDF name4 = joinpath(testpath, "testx.db") write_table!(name4, "my_table", DataFrame(read_table(name2))) df_recovered = DataFrame(read_table(name3); copycols=false) @test df == df_recovered # SQLite from XLSX name4 = joinpath(testpath, "testx.db") write_table!(name4, "my_table", read_table(name3)) df_recovered = DataFrame(read_table(name3); copycols=false) @test df == df_recovered end include("test_pandas.jl") # could only be tested if Pandas.jl, Python, Pandas and PyTables are installed end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
1027
@testset "PlutoUI" begin df = DataFrame(a=1:10, b=0.1:0.1:1, c="hello".* string.(1:10), d=Bool.((1:10) .% 2), e=Date("2020-08-15") .+ Day.(1:10), f="world!" .* string.(1:10)) empty_file_picker = Dict{Any, Any}("name" => "", "data" => UInt8[], "type" => "") @test_throws ErrorException read_table(empty_file_picker) filenames = ["test.csv", "test.xlsx", "test_array.json", "test.arrow", "test.zip", "test3.zip"] # "test_obj.json" not checked here - strange behaviour with Julia 1.6 nightly. To be checked after Julia 1.6 release. for filename ∈ filenames @info "testing import of file $filename from PlutoUI.FilePicker" file_picker = Dict{Any, Any}("name" => filename, "data" => read(joinpath(testpath, filename)), "type" => "") df_recovered = DataFrame(read_table(file_picker); copycols=false) df_recovered[!, :e] = Date.(df_recovered.e) # some impots do not convert date columns automatically @test df_recovered == df end end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
1032
using TableIO using Test using DataFrames using Dates function compare_df_ignore_order(df1:: DataFrame, df2:: DataFrame) sort(names(df1)) == sort(names(df2)) || return false for col in names(df1) df1[!, col] == df2[!, col] || return false end return true end testpath = mktempdir() println("Temporary directory for test files: ", testpath) # defining Tables.jl compatible test data df = DataFrame(a=1:10, b=0.1:0.1:1, c="hello".* string.(1:10), d=Bool.((1:10) .% 2), e=Date("2020-08-15") .+ Day.(1:10), f="world!" .* string.(1:10)) nt = [(a=1, b=0.5, c="hello"), (a=2, b=0.9, c="world"), (a=3, b=5.5, c="!")] @testset "TableIO.jl" begin @test TableIO._checktablename("foo") == false # valid names do not throw an error @test TableIO._checktablename("bar.foo") == false @test_throws ErrorException TableIO._checktablename("Robert'); DROP TABLE students; --") == false # https://xkcd.com/327/ include("file_io.jl") include("database_io.jl") include("plutoui_file_picker.jl") end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
code
753
# install Python dependencies ENV["PYTHON"] = "" using Pkg Pkg.activate(".") Pkg.add(["PyCall", "Conda"]) Pkg.build("PyCall") using Conda Conda.add("pandas") Conda.add("pytables") @testset "HDF5" begin import Pandas fname = joinpath(testpath, "test.hdf") write_table!(fname, "/data", df) @test filesize(fname) > 0 @test list_tables(fname) == ["/data"] df_recovered = DataFrame(read_table(fname, "/data"); copycols=false) @test compare_df_ignore_order(df,df_recovered) fname = joinpath(testpath, "test2.hdf") write_table!(fname, "my_data", nt) @test filesize(fname) > 0 nt_recovered = DataFrame(read_table(fname, "my_data"); copycols=false) @test compare_df_ignore_order(DataFrame(nt), nt_recovered) end
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.4.1
f8844cb81b0c3a2d5c96c1387abebe61f18e619e
docs
8864
# TableIO [![Build Status](https://travis-ci.com/lungben/TableIO.jl.svg?branch=master)](https://travis-ci.com/lungben/TableIO.jl) [![codecov](https://codecov.io/gh/lungben/TableIO.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/lungben/TableIO.jl) A small "glue" package for reading and writing tabular data. It aims to provide a uniform api for reading and writing tabular data from and to multiple sources. This package is "intelligent" in this sense that it automatically selects the right reading / writing methods depending on the file extension. ## Supported Formats * CSV via <https://github.com/JuliaData/CSV.jl> * JSON via <https://github.com/JuliaData/JSONTables.jl> * Zipped CSV or JSON via <https://github.com/fhs/ZipFile.jl> * JDF via <https://github.com/xiaodaigh/JDF.jl> * Parquet via <https://github.com/JuliaIO/Parquet.jl> * Apache Arrow via <https://github.com/JuliaData/Arrow.jl> * Excel (xlsx) via <https://github.com/felipenoris/XLSX.jl> * SQLite via <https://github.com/JuliaDatabases/SQLite.jl> * PostgreSQL via <https://github.com/invenia/LibPQ.jl> - note that CSV.jl is required for PostgreSQL, too. * Read-only: Stata (dta), SPSS (dat) and SAS (sas7bdat) via <https://github.com/queryverse/StatFiles.jl> * HDF5 (Pandas format) via [Pandas.jl](https://github.com/JuliaPy/Pandas.jl) - requires Python with Pandas and PyTables installed on Python side. The underlying packages are not direct dependencies of TableIO and are therefore not installed automatically with it. This is for reduction of installation size and package load time. For installation of the Python requirements for Pandas HDF5 use the following Julia commands: ENV["PYTHON"] = "" # to use a separate Conda environment for Julia using Pkg Pkg.add(["PyCall", "Conda", "Pandas"]) Pkg.build("PyCall") using Conda Conda.add("pandas") Conda.add("pytables") ## Installation using Pkg Pkg.add("TableIO") using TableIO Before using a specific format, the corresponding package needs to be installed and imported: ] add JDF import JDF # or using JDF If the file format specific library is not imported and / or installed, an error message is raised. ## Reading Data The function read_table reads a data source (file or database) and returns a Table.jl interface, e.g. for creating a DataFrame. using TableIO, DataFrames CSV Format: using CSV df = DataFrame(read_table("my_data.csv"); copycols=false) # Keyword arguments can be passed to the CSV reader (CSV.jl) df = DataFrame(read_table("my_data.zip"); copycols=false) # zipped CSV format (assuming there is only 1 file in the archive) JSON Format: using Dates, JSONTables df = read_table("my_data.json") |> DataFrame # note that |> DataFrame(; copycols=false) gives wrong column types! df.my_date_col = Dates.(df.my_date_col) # Dates are imported as strings by default, need to be manually converted df = read_table("my_data.zip", "my_data.json") |> DataFrame Binary Formats: using JDF df = DataFrame(read_table("my_data.jdf"); copycols=false) # JDF (compressed binary format) using Parquet df = DataFrame(read_table("my_data.parquet"); copycols=false) # Parquet using Arrow df = DataFrame(read_table("my_data.arrow"); copycols=false) # Apache Arrow import Pandas # using gives a naming conflict df = DataFrame(read_table("my_data.hdf", "key"); copycols=false) # HDF5 (via Pandas) Excel: using XLSX df = DataFrame(read_table("my_data.xlsx"); copycols=false) # imports 1st sheet df = DataFrame(read_table("my_data.xlsx", "MyAwesomeSheet"); copycols=false) # imports named sheet SQLite: using SQLite df = DataFrame(read_table("my_data.db", "my_table"); copycols=false) # SQLite from file, table name must be given Alternatively, SQLite database objects could be used: using SQLite sqlite_db = SQLite.DB("my_data.db") df = DataFrame(read_table(sqlite_db, "my_table"); copycols=false) # SQLite from database connection, table name must be given PostgreSQL: using LibPQ, CSV # CSV is required here because `write_table!` for PostgreSQL depends on CSV postgres_conn = LibPQ.Connection("dbname=postgres user=postgres") df = DataFrame(read_table(postgres_conn, "my_table"); copycols=false) # reading from Postgres connection StatFiles.jl integration: using StatFiles df = DataFrame(read_table("my_data.dta"); copycols=false) # Stata df = DataFrame(read_table("my_data.sav"); copycols=false) # SPSS df = DataFrame(read_table("my_data.sas7bdat"); copycols=false) # SAS For data formats supporting multiple tables inside a file, the function `list_tables` returns an alphabetically sorted list of table names. table_names = list_tables(filename) ## Writing Data The function write_table! writes a Table.jl compatible data source into a file or databse. using TableIO, DataFrames CSV Format: using CSV write_table!("my_data.csv", df) write_table!("my_data.zip", df) # zipped CSV. If no "inner" file name is given, the table is always stored in csv format with the same file name as the zip archive JSON Format: using JSONTables write_table!("my_data.json", df) # dictionary of arrays write_table!("my_data.json", df, orientation=:objecttable) # dictionary of arrays write_table!("my_data.json", df, orientation=:arraytable) # array of dictionaries write_table!("my_data.zip", "my_data.json", df) # need to explicitly give a file name inside zip archive, otherwise csv format is used Binary Formats: using JDF write_table!("my_data.jdf", df) # JDF (compressed binary format) using Parquet write_table!("my_data.parquet", df) # Parquet - note that Date element type is not supported yet using Arrow write_table!("my_data.arrow", df) # Apache Arrow import Pandas # using gives a naming conflict write_table!("my_data.hdf", "key", df) # HDF5 (via Pandas) Excel: write_table!("my_data.xlsx", "test_sheet_42", df) # creates sheet with defined name SQLite: using SQLite write_table!("my_data.db", "my_table", df) # SQLite from file, table must not exist sqlite_db = SQLite.DB("my_data.db") write_table!(sqlite_db, "my_table", df) # SQLite from database connection PostgreSQL: using LibPQ, CSV postgres_conn = LibPQ.Connection("dbname=postgres user=postgres") write_table!(postgres_conn, "my_table", df) # table must exist and be compatible with the input data StatFiles.jl integration: `write_table!` is not supported. Additionally, it is possible to export tabular data into Julia code (`.jl` files): write_table!("my_data.jl", "my_table", df) To read this data, the corresponding Julia source code file can be included: include("my_data.jl") @assert DataFrame(my_table) == df ## Conversions It is possible to pass the output of `read_table` directly as input to `write_table!` for converting tabular data between different formats: name1 = joinpath(testpath, "test.zip") # zipped CSV name2 = joinpath(testpath, "testx.jdf") # binary name3 = joinpath(testpath, "testx.xlsx") # Excel name4 = joinpath(testpath, "testx.db") # SQLite write_table!(name2, read_table(name1)) write_table!(name3, read_table(name2)) write_table!(name4, "my_table", read_table(name3)) df_recovered = DataFrame(read_table(name4, "my_table"); copycols=false) ## PlutoUI Integration In a [Pluto.jl](https://github.com/fonsp/Pluto.jl) notebook, TableIO can be used directly on a [PlutoUI.jl](https://github.com/fonsp/PlutoUI.jl) FilePicker output. Example (run in a Pluto.jl notebook): using PlutoUI, TableIO, DataFrames @bind f PlutoUI.FilePicker() # pick any supported file type df = DataFrame(read_table(f); copycols=false) This functionality works for all supported file formats if the corresponding import packages are installed. It is not required to import them, this is done automatically. ## Testing The PostgreSQL component requires a running PostgreSQL database for unit tests. This database can be started using the following command: `docker run --rm --detach --name test-libpqjl -e POSTGRES_HOST_AUTH_METHOD=trust -p 5432:5432 postgres` ## Disclaimer If you encounter warnings like ┌ Warning: Package TableIO does not have CSV in its dependencies: │ - If you have TableIO checked out for development and have │ added CSV as a dependency but haven't updated your primary │ environment's manifest file, try `Pkg.resolve()`. │ - Otherwise you may need to report an issue with TableIO └ Loading CSV into TableIO from project dependency, future warnings for TableIO are suppressed. please ignore them. TableIO purposely has not included the libraries for the specific file formats as its own dependencies.
TableIO
https://github.com/lungben/TableIO.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
563
using Documenter push!(LOAD_PATH, "../src/") using QuickHeaps DEPLOYDOCS = (get(ENV, "CI", nothing) == "true") makedocs( sitename = "Efficient and versatile binary heaps and priority queues for Julia", format = Documenter.HTML( prettyurls = DEPLOYDOCS, ), authors = "Éric Thiébaut and contributors", modules = [QuickHeaps], pages = ["index.md", "install.md", "binaryheaps.md", "priorityqueues.md", "nodes.md", "library.md"] ) if DEPLOYDOCS deploydocs( repo = "github.com/emmt/QuickHeaps.jl.git", ) end
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
3141
""" The `QuickHeaps` module implements versatile binary heaps and priority queues for Julia. Wikipedia page https://en.wikipedia.org/wiki/Binary_heap has very clear explanations about binary heaps. This code was much inspired by the [DataStructures.jl](https://github.com/JuliaCollections/DataStructures.jl) package but has a number of improvements: - sorting methods are 2 to 4 times faster (in part because NaN are ignored but also because of carefully in-lining critical sections); - methods not having the `unsafe` word in their name are safer and check their arguments for correctness (methods with the `unsafe` word in their name are in tended to be as fast as possible). """ module QuickHeaps export # Form Base.Order: Ordering, ForwardOrdering, ReverseOrdering, Forward, Reverse, # From this package: FastForward, FastReverse, FastMin, FastMax, SafeMin, SafeMax, AbstractBinaryHeap, BinaryHeap, FastBinaryHeap, AbstractPriorityQueue, PriorityQueue, FastPriorityQueue, heapify, heapify!, isheap, setroot!, dequeue_node!, # From Base (in recent versions of Julia): peek, # From DataStructures: enqueue!, dequeue!, dequeue_pair! import Base: IndexStyle, IteratorEltype, IteratorSize, Pair, Tuple, copy, delete!, eltype, empty!, first, get, getindex, getkey, haskey, isempty, iterate, keytype, keys, length, peek, pop!, push!, resize!, setindex!, show, size, sizehint!, valtype, values # The `peek` method appeared in Julia 1.5. @static if isdefined(Base, :peek) import Base: peek end using Base: @propagate_inbounds, OneTo, has_offset_axes, HasEltype, HasLength import DataStructures: # heapify!, heapify, isheap enqueue!, dequeue!, dequeue_pair! using TypeUtils @deprecate to_eltype(A, x) as(eltype(A), x) false #------------------------------------------------------------------------------ # In order to perform fast sorting (without taking care of NaN's), we # extend `Base.Order.lt` method for specialized ordering types. The # ordering can be an instance or its type. using Base.Order: Ordering, ForwardOrdering, ReverseOrdering, Forward, Reverse import Base.Order: lt """ FastForwardOrdering is the singleton type for fast *forward* ordering without considering NaN's. """ struct FastForwardOrdering <: Ordering end lt(::FastForwardOrdering, a, b) = a < b const FastForward = FastForwardOrdering() const FastReverse = ReverseOrdering(FastForward) const FastMin = FastForward const FastMax = FastReverse const SafeMin = Forward const SafeMax = Reverse """ default_ordering(T) yields the default ordering for an ordered data structure of type `T`. This method shall be specialized for each ordered data structure. """ default_ordering(x::Any) = default_ordering(typeof(x)) default_ordering(::Type) = Forward #------------------------------------------------------------------------------ include("utilities.jl") include("binaryheaps.jl") include("nodes.jl") include("priorityqueues.jl") end # module
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
16914
""" QuickHeaps.AbstractBinaryHeap{T,O} is the super-type of binary heaps in `QuickHeaps` whose values have type `T` and whose ordering has type `O`. The following methods are available for a binary heap `h` (those which modify the heap contents re-order heap values as needed to maintain the heap structure): pop!(h) # deletes and returns root value of heap h push!(h, x) # pushes value x in heap h empty!(h) # empties heap h isempty(h) # yields whether heap h is empty delete!(h, i) # deletes i-th value from heap h peek(h) # yields root value of heap h without deleting it first(h) # idem setroot!(h, x) # same as h[1] = x, replaces root value of heap h by x A binary heap `h` behaves like an abstract vector (with 1-based linear indices), in particular: length(h) # the number of values in heap h h[i] # the i-th value of heap h h[i] = x # set the i-th value of heap h and heapify h Note that `h[1]` is the root value of the heap `h` and that setting a value in the heap may trigger reordering of the values to maintain the binary heap structure. In other words, after doing `h[i] = x`, do not assume that `h[i]` yields `x`. Operations that modify the heap, like deletion by `delete!(h,i)`, insertion by `h[i] = x`, pushing by `push!(h,x)`, and extracting by `pop!(h)` are of complexity `O(1)` in the best case, `O(log(n))` in the worst case, with `n = length(h)` the number of values in the heap `h`. Retrieving a given value with `peek(h)`, `first(h)`, or `h[i]` is always of complexity `O(1)`. """ abstract type AbstractBinaryHeap{T,O<:Ordering} <: AbstractVector{T} end typename(::Type{<:AbstractBinaryHeap}) = "binary heap" """ BinaryHeap{T}([o::Ordering = Forward,][ vals::AbstractVector]) yields an empty binary heap whose values have type `T` and with ordering specified by `o`. For example, a min-heap (resp. a max-heap) is built if `o` specifies forward (resp. reverse) ordering. An optional vector `vals` storing the initial values of the binary heap can be specified. These values in `vals` need not be ordered, the `BinaryHeap` constructor automatically takes care of that. If `vals` is a `Vector{T}` instance, the binary-heap will be directly built into `vals`. Call `BinaryHeap(copy(vals))` to create a binary heap with its own storage. Arguments `o` and `vals` may be specified in any order. Method `sizehint!(h,n)` may be called to anticipate that the heap may contains `n` values. """ struct BinaryHeap{T,O} <: AbstractBinaryHeap{T,O} order::O # ordering of values data::Vector{T} # storage for the values BinaryHeap{T}(o::O=default_ordering(BinaryHeap)) where {T,O<:Ordering} = new{T,O}(o, Vector{T}(undef, 0)) BinaryHeap{T}(o::O, vals::AbstractVector) where {T,O<:Ordering} = heapify!(new{T,O}(o, vals)) end """ FastBinaryHeap{T}([o::Ordering = FastForward,][ vals::AbstractVector]) yields a fast binary heap. Compared to `BinaryHeap{T}(...)`, the default ordering is `FastForward` and the array backing the storage of the heap values is never reduced to improve performances in some cases. You may call `resize!(h)` to explicitly reduce the storage of fast binary-heap `h` to its minimum. """ mutable struct FastBinaryHeap{T,O} <: AbstractBinaryHeap{T,O} order::O # ordering of values data::Vector{T} # storage for the values count::Int # current number of values FastBinaryHeap{T}(o::O=default_ordering(FastBinaryHeap)) where {T,O<:Ordering} = new{T,O}(o, Vector{T}(undef, 0), 0) FastBinaryHeap{T}(o::O, vals::AbstractVector) where {T,O<:Ordering} = heapify!(new{T,O}(o, vals, length(vals))) end default_ordering(::Type{<:AbstractBinaryHeap}) = Forward default_ordering(::Type{<:FastBinaryHeap}) = FastForward # Outer constructors. for type in (:BinaryHeap, :FastBinaryHeap) @eval begin $type{T}(vals::AbstractVector, o::Ordering=default_ordering($type)) where {T} = $type{T}(o, vals) $type(vals::AbstractVector{T}) where {T} = $type{T}(vals) $type(o::Ordering, vals::AbstractVector{T}) where {T} = $type{T}(o, vals) $type(vals::AbstractVector{T}, o::Ordering) where {T} = $type{T}(o, vals) end end """ QuickHeaps.storage(h) yields the array backing the storage of the values in the binary heap `h`. This method may be specialized for custom binary heap types. """ storage(h::AbstractBinaryHeap) = getfield(h, :data) """ QuickHeaps.ordering(h) yields the ordering of the values in the binary heap `h`. This method may be specialized for custom binary heap types. """ ordering(h::AbstractBinaryHeap) = getfield(h, :order) length(h::FastBinaryHeap) = getfield(h, :count) length(h::BinaryHeap) = length(storage(h)) size(h::AbstractBinaryHeap) = (length(h),) IndexStyle(::Type{<:AbstractBinaryHeap}) = IndexLinear() sizehint!(h::AbstractBinaryHeap, n::Integer) = begin sizehint!(storage(h), n) return h end isempty(h::AbstractBinaryHeap) = length(h) < 1 # Call `resize!(h)` with no other arguments to reduce the storage size. resize!(h::AbstractBinaryHeap) = h # do nothing by default resize!(h::FastBinaryHeap) = begin resize!(storage(h), length(h)) return h end # Heap indexing. Note that linear 1-based indexing is assumed for the # array storing the heap. heap_left(i::Int) = 2*i heap_right(i::Int) = 2*i + 1 heap_parent(i::Int) = div(i, 2) @inline function getindex(h::AbstractBinaryHeap, i::Int) @boundscheck checkbounds(h, i) @inbounds r = getindex(storage(h), i) return r end @inline @propagate_inbounds setindex!(h::AbstractBinaryHeap, x, i::Int) = setindex!(h, as(eltype(h), x), i) @inline function setindex!(h::AbstractBinaryHeap{T}, x::T, i::Int) where {T} @boundscheck checkbounds(h, i) A = storage(h) @inbounds y = A[i] # replaced value o = ordering(h) if lt(o, y, x) # Heap structure _above_ replaced entry will remain valid, down-heapify # to fix the heap structure at and _below_ the entry. unsafe_heapify_down!(o, A, i, x, length(h)) else # Heap structure _below_ replaced entry will remain valid, up-heapify # to fix the heap structure at and _above_ the entry. unsafe_heapify_up!(o, A, i, x) end return h end first(h::AbstractBinaryHeap) = peek(h) function peek(h::AbstractBinaryHeap) isempty(h) && throw_argument_error(typename(h), " is empty") @inbounds r = getindex(storage(h), 1) return r end empty!(h::FastBinaryHeap) = (setfield!(h, :count, 0); h) empty!(h::BinaryHeap) = (empty!(storage(h)); h) function pop!(h::AbstractBinaryHeap) n = length(h) n ≥ 1 || throw_argument_error(typename(h), " is empty") A = storage(h) @inbounds x = A[1] if n > 1 # Peek the last value and down-heapify starting at the root of the # binary heap to insert it. @inbounds y = A[n] unsafe_heapify_down!(ordering(h), A, 1, y, n - 1) end unsafe_shrink!(h, n - 1) return x end # Implement push! in a similar way as for AbstractDict to force loop unrolling. push!(h::AbstractBinaryHeap, x) = push!(h, as(eltype(h), x)) push!(h::AbstractBinaryHeap, x, y) = push!(push!(h, x), y) push!(h::AbstractBinaryHeap, x, y, z...) = push!(push!(push!(h, x), y), z...) function push!(h::AbstractBinaryHeap{T}, x::T) where {T} n = length(h) + 1 unsafe_heapify_up!(ordering(h), unsafe_grow!(h, n), n, x) return h end """ setroot!(h, x) -> h replaces the value of the root note in heap `h` by `x`. This is similar to `h[1] = x` but a bit faster. """ setroot!(h::AbstractBinaryHeap, x) = setroot!(h, as(eltype(h), x)) function setroot!(h::AbstractBinaryHeap{T}, x::T) where {T} n = length(h) n ≥ 1 || throw_argument_error(typename(h), " is empty") unsafe_heapify_down!(ordering(h), storage(h), 1, x, n) return h end delete!(h::AbstractBinaryHeap, i::Integer) = delete!(h, as(Int, i)) function delete!(h::AbstractBinaryHeap, i::Int) n = length(h) in_range(i, n) || throw_argument_error("out of range index") if i < n # Replace the deleted value by the last value in the heap and # up-/down-heapify to restore the binary heap structure. A = storage(h) o = ordering(h) @inbounds x = A[n] # value to replace deleted value @inbounds y = A[i] # deleted value if lt(o, y, x) # Heap structure _above_ deleted entry will remain valid, # down-heapify to fix the heap structure at and _below_ the entry. unsafe_heapify_down!(o, A, i, x, n - 1) else # Heap structure _below_ deleted entry will remain valid, # up-heapify to fix the heap structure at and _above_ the entry. unsafe_heapify_up!(o, A, i, x) end end unsafe_shrink!(h, n - 1) return h end """ QuickHeaps.unsafe_grow!(h, n) -> A grows the size of the binary heap `h` to be `n` and returns the array `A` backing the storage of the values. This method is *unsafe* because it does not check its arguments and because it breaks the binary heap structure of the array of values. This method is called by `push!` to grow the size of the heap and shall be specialized for any concrete sub-types of `QuickHeaps.AbstractBinaryHeap`. """ unsafe_grow!(h::BinaryHeap, n::Int) = resize!(storage(h), n) unsafe_grow!(h::FastBinaryHeap, n::Int) = begin A = storage(h) length(A) < n && resize!(A, n) setfield!(h, :count, n) return A end """ QuickHeaps.unsafe_shrink!(h, n) shrinks the size of the binary heap `h` to be `n`. This method is *unsafe* because it does not check its arguments. This method is called by `delete!` to eventually reduce the size of the heap and shall be specialized for any concrete sub-type of [`QuickHeaps.AbstractBinaryHeap`](@ref). """ unsafe_shrink!(h::BinaryHeap, n::Int) = resize!(storage(h), n) unsafe_shrink!(h::FastBinaryHeap, n::Int) = setfield!(h, :count, n) """ heapify!(h) -> h reorders the values in the binary heap `h` in-place. This method should be called to initialize the heap or to re-order the heap if its contents have been modified by other methods than `pop!` or `push!`. The method can be called at a lower level to heapify (part of) an array storing the heap values: heapify!([o=Base.Forward,] A, n=length(A)) -> A reorders the `n` first elements of array `A` in-place to form a binary heap according to the ordering specified by `o`. The array `A` must have 1-based linear indexing. Arguments may be specified in any order. """ function heapify!(h::AbstractBinaryHeap) heapify!(ordering(h), storage(h), length(h)) return h end heapify!(o::Ordering, A::AbstractArray, n::Integer) = heapify!(o, A, as(Int, n)) function heapify!(o::Ordering, A::AbstractArray, n::Int = length(A)) # Heapify the n first elements of A. check_heap_storage(A, n) @inbounds for i in heap_parent(n):-1:1 unsafe_heapify_down!(o, A, i, A[i], n) end return A end """ heapify([o=Base.Forward,] A, n=length(A)) yields an array with the `n` first values of array `A` stored in a binary heap structure of ordering specified by `o`. The storage of the returned heap is a different array than `A`. Arguments may be specified in any order. """ heapify(o::Ordering, A::AbstractArray, n::Integer) = heapify(o, A, as(Int, n)) heapify(o::Ordering, A::AbstractArray{T}, n::Int = length(A)) where {T} = heapify!(o, copyto!(Vector{T}(undef, n), 1, A, 1, n)) """ isheap([o=Base.Forward,], A, n=length(A)) yields whether the `n` first elements of array `A` have a binary heap structure ordered as specified by `o`. Arguments may be specified in any order. isheap(obj; check=false) yields whether object `obj` is a binary heap. If keyword `check` is true, the internal structure of `obj` is checked; otherwise, the type of `obj` is trusted to determine whether it is a binary heap. """ isheap(o::Ordering, A::AbstractArray, n::Integer) = isheap(o, A, as(Int, n)) function isheap(o::Ordering, A::AbstractArray, n::Int = length(A)) check_heap_storage(A, n) @inbounds for i in 1:div(n, 2) l = heap_left(i) r = heap_right(i) if lt(o, A[l], A[i]) || (r ≤ n && lt(o, A[r], A[i])) return false end end return true end isheap(h::AbstractBinaryHeap; check::Bool = false) = if check isheap(ordering(h), storage(h), length(h)) else true end # Cope with different ordering of arguments and using the same default ordering # as in base Julia and DataStructures. for func in (:heapify, :heapify!, :isheap) @eval begin function $func(A::AbstractArray, o::Ordering = default_ordering(A), n::Integer = length(A)) return $func(o, A, n) end function $func(A::AbstractArray, n::Integer, o::Ordering = default_ordering(A)) return $func(o, A, n) end end end """ QuickHeaps.heapify_down!(o, A, i, x=A[i], n=lengh(A)) -> A stores the value `x` in the `i`-th entry of the binary heap built into the `n` first elements of array `A` with ordering `o` and, if needed, moves down the inserted value to maintain the binary heap structure. This method is called to *heapify* an array in order to initialize or rebuild the heap structure or to replace the value of the root value of the heap and update the heap structure. """ function heapify_down!(o::Ordering, A::AbstractArray, i::Integer, x = A[i], n::Integer = length(A)) heapify_down!(o, A, as(Int, i), as(eltype(A), x), as(Int, n)) end function heapify_down!(o::Ordering, A::AbstractArray{T}, i::Int, x::T, n::Int) where {T} check_heap_storage(A, n) in_range(i, n) || throw_argument_error("out of range index") unsafe_heapify_down!(o, A, i, x, n) return A end """ QuickHeaps.unsafe_heapify_down!(o, A, i, x=A[i], n=lengh(A)) This method is a fast but *unsafe* version of [`QuickHeaps.heapify_down!`](@ref) which assumes that all arguments are correct, that is `A` implements 1-based linear indexing, `0 ≤ n ≤ lengh(A)`, and `1 ≤ i ≤ n`. """ @inline function unsafe_heapify_down!(o::Ordering, A::AbstractArray{T}, i::Int, x::T = (@inbounds A[i]), n::Int = length(A)) where {T} @inbounds begin while (l = heap_left(i)) ≤ n j = (r = heap_right(i)) > n || lt(o, A[l], A[r]) ? l : r lt(o, A[j], x) || break A[i] = A[j] i = j end A[i] = x end end """ QuickHeaps.heapify_up!(o, A, i, x=A[i]) -> A stores the value `x` in the `i`-th entry of the binary heap built into the `i` first elements of array `A` with ordering `o` and, if needed, moves up the value to maintain the heap structure. """ function heapify_up!(o::Ordering, A::AbstractArray, i::Integer, x = A[i]) heapify_up!(o, A, as(Int, i), as(eltype(A), x)) end function heapify_up!(o::Ordering, A::AbstractArray{T}, i::Int, x::T) where {T} check_heap_storage(A) in_range(i, length(A)) || error("out of range index") unsafe_heapify_up!(o, A, i, x) return A end """ QuickHeaps.unsafe_heapify_up!(o, A, i, x=A[i]) This methods is a fast but *unsafe* version of [`QuickHeaps.heapify_up!`](@ref) which assumes that all arguments are correct, that is `A` implements 1-based linear indexing and `1 ≤ i ≤ length(A)`. """ @inline function unsafe_heapify_up!(o::Ordering, A::AbstractArray{T}, i::Int, x::T = (@inbounds A[i])) where {T} @inbounds begin while (j = heap_parent(i)) ≥ 1 && lt(o, x, A[j]) A[i] = A[j] i = j end A[i] = x end end """ QuickHeaps.check_heap_storage(A) throws an exception if array `A` is not suitable for storing a binary heap, that is if `A` does not have 1-based linear indexing. QuickHeaps.check_heap_storage(A, n) throws an exception if the first elements of array `A` are not suitable for storing a binary heap of size `n`. """ function check_heap_storage(A::AbstractArray) has_standard_linear_indexing(A) || throw(ArgumentError( "array storing a binary heap must have 1-based linear indexing")) nothing end function check_heap_storage(A::AbstractArray, n::Int) # Check that array has linear indexing and that 0 ≤ n ≤ length(A). check_heap_storage(A) (n % UInt) ≤ (length(A) % UInt) || throw_argument_error( "out of range heap size") nothing end
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
2999
""" QuickHeaps.AbstractNode{K,V} is the super-type of nodes with a key of type `K` and a value of type `V`. Nodes can be used in binary heaps and priority queues to represent key-value pairs and specific ordering rules may be imposed by specializing the `Base.lt` method which is by default: Base.lt(o::Ordering, a::T, b::T) where {T<:QuickHeaps.AbstractNode} = lt(o, QuickHeaps.get_val(a), QuickHeaps.get_val(b)) """ abstract type AbstractNode{K,V} end """ QuickHeaps.Node{K=typeof(k),V=typeof(v)}(k,v) yields a node storing key `k` and value `v`. Optional type parameters `K` and `V` are the respective types of the key and of the value. See also [`QuickHeaps.AbstractNode`](@ref), [`QuickHeaps.AbstractPriorityQueue`](@ref). """ struct Node{K,V} <: AbstractNode{K,V} key::K val::V Node{K,V}(key, val) where {K,V} = new{K,V}(key, val) end Node{K}(key, val::V) where {K,V} = Node{K,V}(key, val) Node(key::K, val::V) where {K,V} = Node{K,V}(key, val) """ get_key(x::QuickHeaps.AbstractNode) -> k yields the key `k` of node `x`. This method may be specialized for any sub-types of [`QuickHeaps.AbstractNode`](@ref). Also see [`QuickHeaps.get_val`](@ref). """ get_key(x::Node) = getfield(x, :key) """ QuickHeaps.get_val(x::QuickHeaps.AbstractNode) -> v yields the value `v` of node `x`. This method may be specialized for any sub-types of [`QuickHeaps.AbstractNode`](@ref). Also see [`QuickHeaps.get_key`](@ref). """ get_val(x::Node) = getfield(x, :val) for type in (:AbstractNode, :Node) @eval begin $type(x::$type) = x $type{K}(x::$type{K}) where {K} = x $type{K,V}(x::$type{K,V}) where {K,V} = x end end Node(x::AbstractNode) = Node(get_key(x), get_val(x)) Node{K}(x::AbstractNode) where {K} = Node{K}(get_key(x), get_val(x)) Node{K,V}(x::AbstractNode) where {K,V} = Node{K,V}(get_key(x), get_val(x)) Node(x::Tuple{Any,Any}) = Node(x[1], x[2]) Node{K}(x::Tuple{Any,Any}) where {K} = Node{K}(x[1], x[2]) Node{K,V}(x::Tuple{Any,Any}) where {K,V} = Node{K,V}(x[1], x[2]) Tuple(x::AbstractNode) = (get_key(x), get_val(x)) Node(x::Pair) = Node(x.first, x.second) Node{K}(x::Pair) where {K} = Node{K}(x.first, x.second) Node{K,V}(x::Pair) where {K,V} = Node{K,V}(x.first, x.second) Pair(x::AbstractNode) = get_key(x) => get_val(x) Base.convert(::Type{T}, x::T) where {T<:AbstractNode} = x Base.convert(::Type{T}, x::AbstractNode) where {T<:AbstractNode} = T(x) Base.convert(::Type{T}, x::Tuple{Any,Any}) where {T<:AbstractNode} = T(x) Base.convert(::Type{T}, x::Pair) where {T<:AbstractNode} = T(x) iterate(x::AbstractNode) = (get_key(x), first) iterate(x::AbstractNode, ::typeof(first)) = (get_val(x), last) iterate(x::AbstractNode, ::typeof(last)) = nothing # Nodes are sorted according to their values. for O in (:Ordering, :ForwardOrdering, :ReverseOrdering, :FastForwardOrdering) @eval begin lt(o::$O, a::T, b::T) where {T<:AbstractNode} = lt(o, get_val(a), get_val(b)) end end
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
21830
""" QuickHeaps.AbstractPriorityQueue{K,V,O} is the super type of priority queues with nodes consisting in pairs of keys of type `K`, priority values of type `V`, and ordering of type `O<:Base.Ordering`. Priority queues implement an API similar to dictionaries with the additional feature of maintaining an ordered structure so that getting the node of highest priority costs `O(1)` while pushing a node costs `O(log(n))` with `n` the size of the queue. See online documentation for more details. `QuickHeaps` provides two concrete types of priority queues: [`PriorityQueue`](@ref) for any kind of keys and [`FastPriorityQueue`](@ref) for keys which are analoguous to array indices. """ abstract type AbstractPriorityQueue{K,V,O<:Ordering} <: AbstractDict{K,V} end default_ordering(::Type{<:AbstractPriorityQueue}) = Forward typename(::Type{<:AbstractPriorityQueue}) = "priority queue" """ PriorityQueue{K,V}([o=Forward,] T=Node{K,V}) yields a priority queue for keys of type `K` and priority values of type `V`. Optional arguments `o::Ordering` and `T<:AbstractNode{K,V}` are to specify the ordering of values and type of nodes to store key-value pairs. Type parameters `K` and `V` may be omitted if the node type `T` is specified. Having a specific node type may be useful to specialize the `Base.lt` method which is called to determine the order. If keys are analoguous to array indices (linear or Cartesian), [`FastPriorityQueue`](@ref) may provide a faster alternative. """ struct PriorityQueue{K,V,O,T} <: AbstractPriorityQueue{K,V,O} order::O nodes::Vector{T} index::Dict{K,Int} end # Copy constructor. The copy is independent from the original. copy(pq::PriorityQueue{K,V,O,T}) where {K,V,O,T} = PriorityQueue{K,V,O,T}(ordering(pq), copy(nodes(pq)), copy(index(pq))) """ FastPriorityQueue{V}([o=Forward,] [T=Node{Int,V},] dims...) yields a priority queue for keys analoguous of indices in an array of size `dims...` and priority values of type `V`. Optional arguments `o::Ordering` and `T<:AbstractNode{Int,V}` are to specify the ordering of values and type of nodes to store key-value pairs (the key is stored as a linear index of type `Int`). Type parameter `V` may be omitted if the node type `T` is specified. See [`PriorityQueue`](@ref) if keys cannot be assumed to be array indices. """ struct FastPriorityQueue{V,N,O, T<:AbstractNode{Int,V}} <: AbstractPriorityQueue{Int,V,O} order::O nodes::Vector{T} index::Array{Int,N} end # Copy constructor. The copy is independent from the original. copy(pq::FastPriorityQueue{V,N,O,T}) where {V,N,O,T} = FastPriorityQueue{V,N,O,T}(ordering(pq), copy(nodes(pq)), copy(index(pq))) # Constructors for PriorityQueue instances. function PriorityQueue{K,V}(o::O = default_ordering(PriorityQueue), ::Type{T} = Node{K,V}) where {K,V,O<:Ordering, T<:AbstractNode{K,V}} return PriorityQueue{K,V,O,T}(o, T[], Dict{K,V}()) end PriorityQueue{K,V}(::Type{T}) where {K,V,T<:AbstractNode{K,V}} = PriorityQueue{K,V}(default_ordering(PriorityQueue), T) PriorityQueue{K}(::Type{T}) where {K,V,T<:AbstractNode{K,V}} = PriorityQueue{K,V}(T) PriorityQueue(::Type{T}) where {K,V,T<:AbstractNode{K,V}} = PriorityQueue{K,V}(T) PriorityQueue{K}(o::Ordering, ::Type{T}) where {K,V,T<:AbstractNode{K,V}} = PriorityQueue{K,V}(o, T) PriorityQueue(o::Ordering, ::Type{T}) where {K,V,T<:AbstractNode{K,V}} = PriorityQueue{K,V}(o, T) # Constructors for FastPriorityQueue instances. FastPriorityQueue{V}(dims::Integer...) where {V} = FastPriorityQueue{V}(dims) FastPriorityQueue{V}(o::Ordering, dims::Integer...) where {V} = FastPriorityQueue{V}(o, dims) FastPriorityQueue{V}(T::Type{<:AbstractNode{Int,V}}, dims::Integer...) where {V} = FastPriorityQueue{V}(T, dims) FastPriorityQueue(T::Type{<:AbstractNode{Int,<:Any}}, dims::Integer...) = FastPriorityQueue(T, dims) FastPriorityQueue{V}(o::Ordering, T::Type{<:AbstractNode{Int,V}}, dims::Integer...) where {V} = FastPriorityQueue{V}(o, T, dims) FastPriorityQueue(o::Ordering, T::Type{<:AbstractNode{Int,<:Any}}, dims::Integer...) = FastPriorityQueue(o, T, dims) FastPriorityQueue{V}(dims::Tuple{Vararg{Integer}}) where {V} = FastPriorityQueue(Node{Int,V}, dims) FastPriorityQueue{V}(o::Ordering, dims::Tuple{Vararg{Integer}}) where {V} = FastPriorityQueue(o, Node{Int,V}, dims) FastPriorityQueue{V}(o::Ordering, T::Type{<:AbstractNode{Int,V}}, dims::Tuple{Vararg{Integer}}) where {V} = FastPriorityQueue(o, T, dims) FastPriorityQueue{V}(T::Type{<:AbstractNode{Int,V}}, dims::Tuple{Vararg{Integer}}) where {V} = FastPriorityQueue(T, dims) FastPriorityQueue(T::Type{<:AbstractNode{Int,V}}, dims::Tuple{Vararg{Integer}}) where {V} = FastPriorityQueue(default_ordering(FastPriorityQueue), T, dims) FastPriorityQueue(o::O, T::Type{<:AbstractNode{Int,V}}, dims::NTuple{N,Integer}) where {O<:Ordering,V,N} = FastPriorityQueue{V,N,O,T}(o, T[], zeros(Int, dims)) #show(io::IO, ::MIME"text/plain", pq::AbstractPriorityQueue) = # print(io, "priority queue of type ", nameof(typeof(pq)), # " with ", length(pq), " node(s)") show(io::IO, ::MIME"text/plain", pq::PriorityQueue{K,V}) where {K,V} = print(io, typename(pq), " of type ", nameof(typeof(pq)), "{", nameof(K), ",", nameof(V), "} with ", length(pq), " node(s)") show(io::IO, ::MIME"text/plain", pq::FastPriorityQueue{V}) where {V} = print(io, typename(pq), " of type ", nameof(typeof(pq)), "{", nameof(V), "} with ", length(pq), " node(s)") """ QuickHeaps.ordering(pq) -> o yields the object `o` specifying the ordering of priority values in the priority queue `pq`. """ ordering(pq::AbstractPriorityQueue) = getfield(pq, :order) """ QuickHeaps.index(pq) -> I yields the object `I` storing the key-index association in priority queue `pq`. This object can be used as `I[key]` to yield , for a given key, the index in `QuickHeaps.nodes(pq)`, the associated binary heap. """ index(pq::AbstractPriorityQueue) = getfield(pq, :index) """ QuickHeaps.nodes(pq) yields the array backing the storage of the nodes of priority queue `pq`. """ nodes(pq::AbstractPriorityQueue) = getfield(pq, :nodes) node_type(pq::AbstractPriorityQueue) = node_type(typeof(pq)) node_type(::Type{<:PriorityQueue{K,V,O,T}}) where {K,V,O,T} = T node_type(::Type{<:FastPriorityQueue{V,N,O,T}}) where {V,N,O,T} = T length(pq::AbstractPriorityQueue) = length(nodes(pq)) isempty(pq::AbstractPriorityQueue) = (length(pq) ≤ 0) keytype(pq::AbstractPriorityQueue) = keytype(typeof(pq)) keytype(::Type{<:AbstractPriorityQueue{K,V}}) where {K,V} = K valtype(pq::AbstractPriorityQueue) = valtype(typeof(pq)) valtype(::Type{<:AbstractPriorityQueue{K,V}}) where {K,V} = V haskey(pq::AbstractPriorityQueue, key) = (heap_index(pq, key) != 0) for (func, getter) in ((:get, :get_val), (:getkey, :get_key)) @eval function $func(pq::AbstractPriorityQueue, key, def) n = length(pq) if n > 0 i = heap_index(pq, key) if in_range(i, n) # FIXME: Testing that i > 0 should be sufficient. @inbounds x = getindex(nodes(pq), i) return $getter(x) end end return def end end function delete!(pq::AbstractPriorityQueue, key) n = length(pq) if n > 0 i = heap_index(pq, key) if in_range(i, n) # FIXME: Testing that i > 0 should be sufficient. A = nodes(pq) @inbounds k = get_key(A[i]) # key to be deleted if i < n # Replace the deleted node by the last node in the heap and # up-/down-heapify to restore the binary heap structure. We # cannot assume that the deleted node data be accessible nor # valid, so we explicitely replace it before deciding in which # direction to go and reheapify. Also see `unsafe_enqueue!`. @inbounds x = A[n] # get last node @inbounds A[i] = x # replace deleted node o = ordering(pq) if i ≤ 1 || lt(o, (@inbounds A[heap_parent(i)]), x) unsafe_heapify_down!(pq, i, x, n - 1) else unsafe_heapify_up!(pq, i, x) end end unsafe_shrink!(pq, n - 1) unsafe_delete_key!(pq, k) end end return pq end first(pq::AbstractPriorityQueue) = peek(pq) peek(pq::AbstractPriorityQueue) = peek(Pair, pq) # FIXME: Same code as for binary heaps. function peek(T::Type, pq::AbstractPriorityQueue) isempty(pq) && throw_argument_error(typename(pq), " is empty") @inbounds x = getindex(nodes(pq), 1) return T(x) end function empty!(pq::PriorityQueue) empty!(nodes(pq)) empty!(index(pq)) return pq end function empty!(pq::FastPriorityQueue) empty!(nodes(pq)) fill!(index(pq), 0) return pq end # Private structure used by iterators on priority queues. struct PriorityQueueIterator{F,Q<:AbstractPriorityQueue} f::F pq::Q end IteratorEltype(itr::PriorityQueueIterator) = IteratorEltype(typeof(itr)) IteratorEltype(::Type{<:PriorityQueueIterator}) = HasEltype() eltype(itr::PriorityQueueIterator) = eltype(typeof(itr)) eltype(::Type{<:PriorityQueueIterator{typeof(get_key),Q}}) where {Q} = keytype(Q) eltype(::Type{<:PriorityQueueIterator{typeof(get_val),Q}}) where {Q} = valtype(Q) eltype(::Type{<:PriorityQueueIterator{F,Q}}) where {F,Q} = Any IteratorSize(itr::PriorityQueueIterator) = IteratorSize(typeof(itr)) IteratorSize(::Type{<:PriorityQueueIterator}) = HasLength() length(itr::PriorityQueueIterator) = length(itr.pq) # Unordered iterators. NOTE: All iterators shall however return the elements in # the same order. function iterate(pq::AbstractPriorityQueue, i::Int = 1) in_range(i, length(pq)) || return nothing @inbounds x = getindex(nodes(pq), i) return Pair(x), i + 1 end keys(pq::AbstractPriorityQueue) = PriorityQueueIterator(get_key, pq) values(pq::AbstractPriorityQueue) = PriorityQueueIterator(get_val, pq) function Base.iterate(itr::PriorityQueueIterator, i::Int = 1) in_range(i, length(itr.pq)) || return nothing @inbounds x = getindex(nodes(itr.pq), i) return itr.f(x), i + 1 end pop!(pq::AbstractPriorityQueue) = dequeue_pair!(pq) """ dequeue!(pq) -> key removes the root node from the priority queue `pq` and returns its key. Also see [`dequeue_node!`](@ref) and [`dequeue_pair!`](@ref). """ dequeue!(pq::AbstractPriorityQueue) = get_key(dequeue_node!(pq)) """ dequeue_node!(pq) -> node removes and returns the root node from the priority queue `pq`. Also see [`dequeue!`](@ref) and [`dequeue_pair!`](@ref). """ function dequeue_node!(pq::AbstractPriorityQueue) # The code is almost the same as pop! for a binary heap. n = length(pq) n ≥ 1 || throw_argument_error(typename(pq), " is empty") A = nodes(pq) @inbounds x = A[1] if n > 1 # Peek the last node and down-heapify starting at the root of the # binary heap to insert it. @inbounds y = A[n] unsafe_heapify_down!(pq, 1, y, n - 1) end unsafe_delete_key!(pq, get_key(x)) unsafe_shrink!(pq, n - 1) return x end """ dequeue_pair!(pq) -> (key => val) removes the root node from the priority queue `pq` and returns it as a key-value `Pair`. This is the same as `pop!(pq)`. Also see [`dequeue!`](@ref) and [`dequeue_node!`](@ref). """ dequeue_pair!(pq::AbstractPriorityQueue) = Pair(dequeue_node!(pq)) # For AbstractDict, pushing pair(s) is already implemented via setindex! # Implement push! for 2-tuples and nodes in a similar way as for AbstractDict. push!(pq::AbstractPriorityQueue, x::AbstractNode) = enqueue!(pq, get_key(x), get_val(x)) push!(pq::AbstractPriorityQueue, x::Tuple{Any,Any}) = enqueue!(pq, x[1], x[2]) for T in (AbstractNode, Tuple{Any,Any}) @eval begin push!(pq::AbstractPriorityQueue, a::$T, b::$T) = push!(push!(pq, a), b) push!(pq::AbstractPriorityQueue, a::$T, b::$T, c::$T...) = push!(push!(push!(pq, a), b), c...) end end function getindex(pq::PriorityQueue, key) i = heap_index(pq, key) # FIXME: Testing that i > 0 should be sufficient. in_range(i, length(pq)) || throw_argument_error( typename(pq), " has no node with key ", key) @inbounds r = getindex(nodes(pq), i) return get_val(r) end setindex!(pq::PriorityQueue, val, key) = enqueue!(pq, key, val) # Union of types that can be used to index fast priority queues. const FastIndex = Union{Integer,CartesianIndex} # For indexing fast priority queues, we first convert the key into a linear # index (using the current bounds checking state). for keytype in (:Integer, :(FastIndex...)) @eval begin @inline @propagate_inbounds function getindex(pq::FastPriorityQueue, key::$keytype) k = linear_index(pq, key) @inbounds i = getindex(index(pq), k) A = nodes(pq) if in_range(i, A) @inbounds x = A[i] return get_val(x) end throw_argument_error(typename(pq), " has no node with key ", normalize_key(pq, key)) end @inline @propagate_inbounds function setindex!(pq::FastPriorityQueue, val, key::$keytype) return enqueue!(pq, key, val) end end end normalize_key(pq::FastPriorityQueue, key::Integer) = as(Int, key) normalize_key(pq::FastPriorityQueue, key::Tuple{Vararg{FastIndex}}) = to_indices(index(pq), key) """ Quickheaps.to_key(pq, k) converts the key `k` to the type suitable for priority queue `pq`. """ to_key(pq::AbstractPriorityQueue{K,V}, key::K) where {K,V} = key to_key(pq::AbstractPriorityQueue{K,V}, key) where {K,V} = as(K, key) """ Quickheaps.to_val(pq, v) converts the value `v` to the type suitable for priority queue `pq`. """ to_val(pq::AbstractPriorityQueue{K,V}, val::V) where {K,V} = val to_val(pq::AbstractPriorityQueue{K,V}, val) where {K,V} = as(V, val) """ Quickheaps.to_node(pq, k, v) converts the the key `k` and the value `v` into a node type suitable for priority queue `pq`. """ to_node(pq::AbstractPriorityQueue, key, val) = node_type(pq)(to_key(pq, key), to_val(pq, val)) """ Quickheaps.heap_index(pq, k) -> i yields the index of the key `k` in the binary heap backing the storage of the nodes of the priority queue `pq`. If the key is not in priority queue, `i = 0` is returned, otherwise `i ∈ 1:n` with `n = length(pq)` is returned. The `heap_index` method is used to implement `haskey`, `get`, and `delete!` methods for priority queues. The `heap_index` method shall be specialized for any concrete sub-types of `QuickHeaps.AbstractPriorityQueue`. """ heap_index # NOTE: `heap_index` ~ `ht_keyindex` in `base/dict.jl` # By default, pretend that the key is missing. heap_index(pq::AbstractPriorityQueue, key) = 0 heap_index(pq::PriorityQueue, key) = get(index(pq), key, 0) function heap_index(pq::FastPriorityQueue, key::Integer) k = as(Int, key) I = index(pq) in_range(k, I) || return 0 @inbounds i = I[k] return i end function heap_index(pq::FastPriorityQueue, key::CartesianIndex) I = index(pq) if checkbounds(Bool, I, key) @inbounds i = I[key] return i end return 0 end function heap_index(pq::FastPriorityQueue, key::Tuple{Vararg{FastIndex}}) I = index(pq) if checkbounds(Bool, I, key...) @inbounds i = I[key...] return i end return 0 end """ QuickHeaps.linear_index(pq, k) converts key `k` into a linear index suitable for the fast priority queue `pq`. The key can be a linear index or a multi-dimensional index (anything accepted by `to_indices`). The current settings for bounds checking are used. """ @inline @propagate_inbounds linear_index(pq::FastPriorityQueue, key::Integer) = # Convert to Int, then re-call linear_index for bound checking. Note that # the type assertion performed by `as` avoids infinite recursion. linear_index(pq, as(Int, key)) @inline function linear_index(pq::FastPriorityQueue, key::Int) @boundscheck checkbounds(index(pq), key) return key end @inline @propagate_inbounds function linear_index(pq::FastPriorityQueue, key::Tuple{Vararg{FastIndex}}) # FIXME: Shall we store the linear_indices (a small object) in the priority # queue directly? return LinearIndices(index(pq))[key...] # also does the bound checking end linear_index(pq::FastPriorityQueue, key) = throw_invalid_key(pq, key) @noinline throw_invalid_key(pq::AbstractPriorityQueue, key) = throw_argument_error( "invalid key of type ", typeof(key), " for ", nameof(typeof(pq))) @noinline throw_invalid_key(pq::FastPriorityQueue, key) = throw_argument_error( "invalid key of type ", typeof(key), " for ", nameof(typeof(pq)), " expecting a linear index, an ", ndims(index(pq)), "-dimensional Cartesian index") # The following is to allow the syntax enqueue!(pq, key=>val) enqueue!(pq::AbstractPriorityQueue, pair::Pair) = enqueue!(pq, pair.first, pair.second) # For a general purpose priority queue, build the node then enqueue. enqueue!(pq::PriorityQueue, key, val) = enqueue!(pq, to_node(pq, key, val)) enqueue!(pq::PriorityQueue{K,V,O,T}, x::T) where {K,V,O,T} = unsafe_enqueue!(pq, x, get(index(pq), get_key(x), 0)) # For a fast priority queue, converts the key into a linear index, then enqueue. @inline @propagate_inbounds function enqueue!(pq::FastPriorityQueue, key, val) k = linear_index(pq, key) # not to_key v = to_val(pq, val) x = to_node(pq, k, v) @inbounds i = getindex(index(pq), k) return unsafe_enqueue!(pq, x, i) end enqueue!(pq::FastPriorityQueue{V,N,O,T}, x::T) where {V,N,O,T} = enqueue!(pq, get_key(x), get_val(x)) """ QuickHeaps.unsafe_enqueue!(pq, x, i) -> pq stores node `x` in priority queue `pq` at index `i` and returns the priority queue. The argument `i` is an index in the binary heap backing the storage of the nodes of the priority queue. Index `i` is determined by the key `k` of the node `x` and by the current state of the priority queue. If `i` is not a valid index in the binary heap, a new node is added; otherwise, the node at index `i` in the binary heap is replaced by `x`. In any cases, the binary heap is reordered as needed. This function is *unsafe* because it assumes that the key `k` of the node `x` is valid (e.g. it is not out of bounds for fast priority queues) in the sense that `I[k]` is valid for the index `I` of the priority queue. """ function unsafe_enqueue!(pq::AbstractPriorityQueue, x, i::Int) A = nodes(pq) if in_range(i, A) # The key alreay exists. Replace the node in the heap by the new node # and up-/down-heapify to restore the binary heap structure. We cannot # assume that the replaced node data be accessible nor valid, so we # explicitely replace it before deciding in which direction to go and # reheapify. Also see `delete!`. @inbounds A[i] = x # replace deleted node o = ordering(pq) if i ≤ 1 || lt(o, (@inbounds A[heap_parent(i)]), x) unsafe_heapify_down!(pq, i, x) else unsafe_heapify_up!(pq, i, x) end else # No such key already exists. Create a new slot at the end of the node # list and up-heapify to fix the structure and insert the new node. n = length(pq) + 1 unsafe_heapify_up!(unsafe_grow!(pq, n), n, x) end return pq end """ QuickHeaps.unsafe_grow!(pq, n) -> pq grows the size of the binary heap backing the storage of the nodes of the priority queue `pq` to be `n` and returns the priority queue object. """ unsafe_grow!(pq::Union{PriorityQueue,FastPriorityQueue}, n::Int) = begin resize!(nodes(pq), n) return pq end """ QuickHeaps.unsafe_shrink!(pq, n) shrinks the size of the binary heap backing the storage of the nodes of the priority queue `pq` to be `n`. """ unsafe_shrink!(pq::Union{PriorityQueue,FastPriorityQueue}, n::Int) = resize!(nodes(pq), n) """ QuickHeaps.unsafe_delete_key!(pq, k) deletes key `k` from the index of the priority queue `pq` assuming `k` is valid. """ unsafe_delete_key!(pq::AbstractPriorityQueue{K}, key::K) where {K} = unsafe_delete_key!(index(pq), key) # Specialized version for the type of the index. unsafe_delete_key!(I::Array{Int}, key::Int) = @inbounds I[key] = 0 unsafe_delete_key!(I::AbstractDict, key) = delete!(I, key) @inline function unsafe_heapify_down!(pq::AbstractPriorityQueue, i::Int, x, n::Int = length(pq)) o = ordering(pq) A = nodes(pq) I = index(pq) @inbounds begin while (l = heap_left(i)) ≤ n j = (r = heap_right(i)) > n || lt(o, A[l], A[r]) ? l : r lt(o, A[j], x) || break I[get_key(A[j])] = i A[i] = A[j] i = j end I[get_key(x)] = i A[i] = x end end @inline function unsafe_heapify_up!(pq::AbstractPriorityQueue, i::Int, x) o = ordering(pq) A = nodes(pq) I = index(pq) @inbounds begin while (j = heap_parent(i)) ≥ 1 && lt(o, x, A[j]) I[get_key(A[j])] = i A[i] = A[j] i = j end I[get_key(x)] = i A[i] = x end end
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
2082
""" has_standard_linear_indexing(A) yields whether array `A` implements standard linear indexing (1-based). """ has_standard_linear_indexing(A::Array) = true has_standard_linear_indexing(A::AbstractArray) = is_one_based_unit_range(eachindex(A)) """ is_one_based_unit_range(itr) yields whether iterator `itr` is a 1-based unit range. """ is_one_based_unit_range(itr) = false is_one_based_unit_range(itr::Base.OneTo) = true is_one_based_unit_range(itr::AbstractUnitRange{T}) where {T} = first(itr) == oneunit(T) """ in_range(i, len::Integer) yields whether `1 ≤ i ≤ len`. in_range(i, A::Array) yields whether `i` is a valid linear index of array `A`. in_range(i, R::AbstractUnitRange{<:Integer}) yields whether `i` is in the range `R`. """ in_range(i::Integer, len::Integer) = ((i % UInt) - 1 < (len % UInt)) in_range(i::Integer, A::Array) = in_range(i, length(A)) in_range(i::Integer, R::OneTo) = in_range(i, length(R)) in_range(i::Integer, R::AbstractUnitRange{<:Integer}) = (i ∈ R) """ has_bad_values(A[, isbad]) yields whether array `A` has bad values according to predicate `isbad`. For arrays with floating-point values, `isbad` default to `isnan` if unspecified. For integer-valued arrays, this function always returns `false` if `isnan` is unspecified. """ function has_bad_values(A::AbstractArray, isbad) flag = false @inbounds @simd for i in eachindex(A) flag |= isbad(A[i]) end return flag end has_bad_values(A::AbstractArray{<:Integer}) = false has_bad_values(A::AbstractArray{<:AbstractFloat}) = has_bad_values(A, isnan) """ typename(x) yields a short string describing the type of object `x`. Argument may also be the object type. """ typename(x::Any) = typename(typeof(x)) typename(T::DataType) = string(nameof(T)) for (func, type) in ((:throw_argument_error, :ArgumentError), (:throw_dimension_mismatch, :DimensionMismatch),) @eval begin $func(msg::$type.types[1]) = throw($type(msg)) @noinline $func(args...) = $func(string(args...)) end end
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
1844
module BenchmarkingQuickHeaps using BenchmarkTools using QuickHeaps using DataStructures using Base.Order: Forward, Reverse, Ordering print_with_arrow(args...; kwds...) = print_with_arrow(stdout, args...; kwds...) function print_with_arrow(io::IO, args...; width::Integer=70) msg = string(args...) len = max(2, width - 3 - length(msg)) print(io, msg, " ", repeat("-", len), ">") end function runtests(T::Type = Float64, n::Int = 1000) x = rand(T, n) xsav = copy(x) w = similar(x) width = 69 for pass in 1:2 for version in (:DataStructures, :QuickHeaps) println("\nTimings for \"$version\" methods (T=$T, n=$n):") for order in (:(Base.Forward), :(Base.Reverse), :(DataStructures.FasterForward()), :(DataStructures.FasterReverse()), :(QuickHeaps.FastMin), :(QuickHeaps.FastMax),) if pass == 1 print_with_arrow(" - $version.heapify!(..., $order)"; width=width) @btime $version.heapify!(copyto!($w, $x), $order); print(); @assert x == xsav # check that x was left unchanged @assert @eval($version.isheap)(w, @eval($order)) else @eval($version.heapify!)(copyto!(w, x), @eval($order)); @assert x == xsav # check that x was left unchanged print_with_arrow(" - $version.isheap(..., $order)"; width=width) @btime $version.isheap($w, $order); print(); end end end end end if !isinteractive() runtests() end end # module
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
9119
module TestingBinaryHeaps using Test using Base: Ordering, ForwardOrdering, ReverseOrdering, Forward, Reverse, lt using QuickHeaps using QuickHeaps: AbstractBinaryHeap, FastForwardOrdering, FastForward, FastReverse, FastMin, FastMax, SafeMin, SafeMax, isheap, heapify, heapify!, ordering, storage orientation(::Any) = 0 orientation(h::AbstractBinaryHeap) = orientation(typeof(h)) orientation(::Type{<:AbstractBinaryHeap{T,O}}) where {T,O} = orientation(O) orientation(o::Ordering) = orientation(typeof(o)) orientation(::Type{<:Union{ForwardOrdering,FastForwardOrdering}}) = +1 orientation(::Type{<:ReverseOrdering{O}}) where {O} = -orientation(O) is_min_ordering(x) = orientation(x) > 0 is_max_ordering(x) = orientation(x) < 0 function is_sorted(o::Base.Ordering, x::AbstractVector) flag = false for i in 2:length(x) flag |= lt(o, x[i], x[i-1]) end return !flag end other_type(::Type{Float64}) = Float32 other_type(::Type{Float32}) = Float64 other_type(::Type{Int16}) = Int32 other_type(::Type{Int32}) = Int16 other_type(::Type{Int64}) = Int32 other_type(::Type{UInt16}) = UInt32 other_type(::Type{UInt32}) = UInt16 other_type(::Type{UInt64}) = UInt32 # In Julia 1.0 "$o" with o=nothing is an error, so provide our own singleton type # to represent unspecified argument. struct Nil end const nil = Nil() Base.print(io::IO, ::Nil) = nothing # Yields a non-heap vector of the values. vals(h::BinaryHeap) = storage(h) vals(h::AbstractBinaryHeap) = view(storage(h), Base.OneTo(length(h))) # Checks whether 2 arrays have the same entries although not nceessarily in the same # order. same_entries(A::AbstractArray, B::AbstractArray) = sort(vec(A)) == sort(vec(B)) # A1 and A2 are two arrays such that view(A,1:i) is not a heap in any ordering # for A = A1 or A2 and i ≥ 3. These arrays where randomly generated by # something like: # A1 = rand(1:15, 16) # A2 = map(x->round(Int,100*x)/10, rand(Float64, 11)) # with some manual re-ordering of the 3 first entries to ensure that the # non-heap property holds. const A1 = [7, 12, 5, 13, 6, 14, 12, 1, 10, 6, 9, 4, 10, 7, 12, 14]; const A2 = [3.0, 6.4, 1.1, 9.2, 1.2, 8.2, 1.3, 7.9, 9.1, 2.3, 8.2]; @testset "Arrays as binary heaps" begin for (A, dir) in ( ([1, 4, 2, 6, 5, 3, 8, 7, 11, 13, 10, 14, 9, 12], +1), # min-heap ([14, 11, 13, 9, 10, 12, 7, 8, 4, 2, 5, 1, 6, 3], -1), # max-heap ([13, 1, 14, 8, 10, 9, 7, 2, 5, 4, 12, 3, 6, 11], 0), # not heap ) n = length(A) flag = (dir > 0) success = true @test flag == isheap(A) for np in 3:n # last elements can be discarded success &= (flag == isheap(A, np)) end @test success for o in (Forward, FastForward, Reverse, FastReverse) flag = (dir*orientation(o) > 0) @test flag == isheap(A, o) @test flag == isheap(o, A) @test flag == isheap(A, n, o) @test flag == isheap(A, o, Int16(n)) success = true for np in 3:n # last elements can be discarded success &= (flag == isheap(o, A, np)) end @test success end B = heapify(A) @test same_entries(A, B) @test isheap(B) @test !isheap(B, Reverse) QuickHeaps.heapify_down!(Forward, B, 1, Int16(1234)) @test isheap(Forward, B) QuickHeaps.heapify_up!(Forward, B, length(B), Int16(-789)) @test isheap(Forward, B) B = heapify(A, Reverse, Int16(n)) @test same_entries(A, B) @test !isheap(B) @test isheap(B, Reverse) C = copy(A) B = heapify!(C) @test same_entries(A, B) @test B === C @test isheap(B) B = heapify!(C, Reverse, Int16(n)) @test same_entries(A, B) @test B === C @test isheap(B, Reverse) QuickHeaps.heapify_down!(Reverse, B, 1, Int16(-1234)) @test isheap(B, Reverse) QuickHeaps.heapify_up!(Reverse, B, length(B), Int16(789)) @test isheap(B, Reverse) end end @testset "Binary heaps " begin @test QuickHeaps.default_ordering(AbstractBinaryHeap) === SafeMin @test QuickHeaps.default_ordering(FastBinaryHeap) === FastMin pass = 0 for o in (nil, SafeMin, SafeMax, FastMin, FastMax), B in (BinaryHeap, FastBinaryHeap), A in (A1, A2) pass += 1 n = length(A) T = eltype(A) S = other_type(T) expected_ordering = (o !== nil ? o : B <: FastBinaryHeap ? FastMin : SafeMin) # Build an empty binary-heap and fill it. h1 = (o === nil ? B{T}() : B{T}(o)) @test eltype(h1) == T @test IndexStyle(h1) == IndexLinear() @test length(h1) == 0 @test size(h1) == (0,) @test isempty(h1) @test isheap(h1) && isheap(h1; check=true) && isheap(h1; check=false) @test_throws ArgumentError peek(h1) @test_throws ArgumentError pop!(h1) @test ordering(h1) === expected_ordering # Start with given array without specifying type. h2 = (o === nil ? B(copy(A)) : T <: Integer ? B(o, copy(A)) : B(copy(A), o)) @test ordering(h2) === expected_ordering @test eltype(h2) == T @test IndexStyle(h2) == IndexLinear() @test length(h2) == n @test size(h2) == (n,) @test !isempty(h2) @test isheap(h2) && isheap(h2; check=true) && isheap(h2; check=false) @test same_entries(h2, A) # Start with given array and specifying the same element type. h3 = (o === nil ? B{T}(copy(A)) : T <: Integer ? B{T}(o, copy(A)) : B{T}(copy(A), o)) @test ordering(h3) === expected_ordering @test eltype(h3) == T @test IndexStyle(h3) == IndexLinear() @test length(h3) == n @test size(h3) == (n,) @test !isempty(h3) @test isheap(h3) && isheap(h3; check=true) && isheap(h3; check=false) @test same_entries(h3, A) # Start with given array and specifying another element type. h4 = (o === nil ? B{S}(A) : S <: Integer ? B{S}(A, o) : B{S}(o, A)) @test ordering(h4) === expected_ordering @test eltype(h4) == S @test IndexStyle(h4) == IndexLinear() @test length(h4) == n @test size(h4) == (n,) @test !isempty(h4) @test isheap(h4) && isheap(h4; check=true) && isheap(h4; check=false) @test same_entries(h4, convert(Vector{S}, A)) # Do not repeat the following tests for default ordering. o === nil && continue # Fill empty heap vith values. isodd(pass) && sizehint!(h1, n) for i in 1:n if T <: Integer # Push entry with different type but not actually changing value. push!(h1, convert(S, A[i])) else push!(h1, A[i]) end @test isheap(h1; check=true) @test !isempty(h1) v1 = (is_min_ordering(h1) ? minimum(vals(h1)) : maximum(vals(h1))) @test peek(h1) === v1 @test first(h1) === v1 @test length(h1) == i end @test same_entries(h1, A) # Empty heap by repeatedly pop root entry and check that entries are extracted # in order. x1 = eltype(h1)[] while !isempty(h1) len = length(h1) push!(x1, pop!(h1)) @test length(h1) == len - 1 @test isheap(h1; check=true) end @test same_entries(x1, A) @test is_sorted(ordering(h1), x1) resize!(h1) # shrink internal buffer # Empty heap by deleting entries in somewhat random order. x2 = eltype(h2)[] while !isempty(h2) len = length(h2) i = 1 + Int(hash(len) % len) # reproducible pseudo-random index push!(x2, h2[i]) if isodd(len) delete!(h2, i) else delete!(h2, Int16(i)) end @test length(h2) == len - 1 @test isheap(h2; check=true) end @test same_entries(x2, A) # Empty heap then fill it by pieces. @test isempty(empty!(h3)) push!(h3, A[1:4]...) @test length(h3) == 4 @test isheap(h3; check=true) for i in 5:n push!(h3, A[i]) end @test same_entries(h3, A) # Perturbate heap in different ways. vmax = maximum(vals(h4)) for i in 1:n vi = convert(other_type(eltype(h4)), vmax - h4[i]) if i == 1 && eltype(h4) <: Integer # Just take another path to set the first entry. QuickHeaps.setroot!(h4, vi) else # Set i-th entry. h4[i] = vi end @test isheap(h4; check=true) @test length(h4) == n v1 = (is_min_ordering(h4) ? minimum(vals(h4)) : maximum(vals(h4))) @test peek(h4) === v1 @test first(h4) === v1 end end end end # module
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
3031
module TestingQuickNodes using Test using Base: Ordering, ForwardOrdering, ReverseOrdering, Forward, Reverse, lt using QuickHeaps using QuickHeaps: AbstractNode, Node import QuickHeaps: get_key, get_val @testset "Standard nodes " begin for (k, v) in (("foo", 2.1), (:bar, 11), (CartesianIndex(11,2), nothing)) K = typeof(k) V = typeof(v) x = Node(k, v) @test isa(x, AbstractNode) @test isa(x, Node) @test isa(x, AbstractNode{K,V}) @test isa(x, Node{K,V}) # Node <-> Tuple @test Tuple(x) === (k, v) @test Node((k, v)) === x @test convert(Node, (k, v)) === x @test convert(Node{K}, (k, v)) === x @test convert(Node{K,V}, (k, v)) === x kp, vp = x @test kp === k && vp === v # Node <-> Pair @test Pair(x) === (k => v) @test Node(k => v) === x @test convert(Node, k => v) === x @test convert(Node{K}, k => v) === x @test convert(Node{K,V}, k => v) === x # Node <-> (Abstract)Node @test AbstractNode(x) === x @test AbstractNode{K}(x) === x @test AbstractNode{K,V}(x) === x @test convert(AbstractNode, x) === x @test convert(AbstractNode{K}, x) === x @test convert(AbstractNode{K,V}, x) === x @test Node(x) === x @test Node{K}(x) === x @test Node{K,V}(x) === x @test convert(Node, x) === x @test convert(Node{K}, x) === x @test convert(Node{K,V}, x) === x # Iterator. r1 = iterate(x) @test r1 isa Tuple{Any,Any} && r1[1] === get_key(x) if r1 isa Tuple{Any,Any} r2 = iterate(x, r1[2]) @test r2 isa Tuple{Any,Any} && r2[1] === get_val(x) if r2 isa Tuple{Any,Any} @test iterate(x, r2[2]) isa Nothing end end end end struct KeyOnlyNode{K} <: AbstractNode{K,Nothing} key::K end get_key(x::KeyOnlyNode) = getfield(x, :key) get_val(x::KeyOnlyNode) = nothing KeyOnlyNode(x::Tuple{K,Nothing}) where {K} = KeyOnlyNode{K}(x[1]) KeyOnlyNode(x::Pair{K,Nothing}) where {K} = KeyOnlyNode{K}(x.first) @testset "Custom nodes " begin for k in ("foo", :bar, CartesianIndex(1,2)) K = typeof(k) x = KeyOnlyNode(k) @test isa(x, AbstractNode) @test isa(x, KeyOnlyNode) @test isa(x, AbstractNode{K,Nothing}) @test isa(x, KeyOnlyNode{K}) @test Tuple(x) === (k, nothing) @test KeyOnlyNode((k, nothing)) === x @test Pair(x) === (k => nothing) @test KeyOnlyNode(k => nothing) === x kp, vp = x V = typeof(vp) @test kp === k && vp === nothing @test Node(x) === Node(kp, vp) @test Node{K}(x) === Node(kp, vp) @test Node{K,V}(x) === Node(kp, vp) @test convert(Node, x) === Node(kp, vp) @test convert(Node{K}, x) === Node(kp, vp) @test convert(Node{K,V}, x) === Node(kp, vp) end end end # module
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
8695
module TestingQuicjPriorityQueues using Test using Random using Base: @propagate_inbounds, lt, ReverseOrdering, Reverse, IteratorEltype, HasEltype, IteratorSize, HasLength using QuickHeaps using QuickHeaps: AbstractPriorityQueue, PriorityQueue, FastPriorityQueue, AbstractNode, get_key, get_val, isheap, index, nodes, ordering, in_range, heap_index function test_queue!(A::AbstractPriorityQueue{K,V}, key_list::AbstractVector{K}, val_list::AbstractVector{V}) where {K,V} # Check arguments. axes(val_list) == axes(key_list) || error("incompatible indices") n = length(key_list) axes(key_list) == (1:n,) || error("non-standard indices") o = ordering(A) # Dummy private function used to "label" the tests. check(flag::Bool, comment) = flag # Checks keytype, etc. @test keytype(A) == K @test keytype(typeof(A)) == K @test IteratorSize(keys(A)) == HasLength() @test IteratorSize(typeof(keys(A))) == HasLength() @test IteratorEltype(keys(A)) == HasEltype() @test IteratorEltype(typeof(keys(A))) == HasEltype() @test eltype(keys(A)) == K @test eltype(typeof(keys(A))) == K # Checks valtype, etc. @test valtype(A) == V @test valtype(typeof(A)) == V @test IteratorSize(values(A)) == HasLength() @test IteratorSize(typeof(values(A))) == HasLength() @test IteratorEltype(values(A)) == HasEltype() @test IteratorEltype(typeof(values(A))) == HasEltype() @test eltype(values(A)) == V @test eltype(typeof(values(A))) == V # Check that `enqueue!` maintains the binary-heap structure. R = Dict{K,V}() # reference dictionary test_1 = true test_2 = true for (k, v) in zip(key_list, val_list) enqueue!(A, k, v) test_1 &= isheap(o, nodes(A)) test_2 &= !haskey(R, k) # unique key? R[k] = v end @test check(test_1, "binary-heap structure after `enqueue!`") @test check(test_2, "unique keys after `enqueue!`") @test length(A) == n # Check `first`, `peek`, `keys`, and `values`. k, v = first(A) @test v == (isa(o, ReverseOrdering) ? maximum : minimum)(values(A)) @test v == first(values(A)) @test k == first(keys(A)) x = peek(AbstractNode, A) @test v == get_val(x) @test k == get_key(x) # Check `getindex` in random order. test_1 = true for i in randperm(n) k = key_list[i] test_1 &= (haskey(A,k) && A[k] == R[k]) end @test check(test_1, "`getindex` in random order") # Test that `keys` and `values` yield all elements in the same order as # `iterate`. test_1 = true test_2 = true for (k,v,kv) in zip(keys(A), values(A), A) test_1 &= (k == kv.first) test_2 &= (v == kv.second) end @test check(test_1, "keys in heap order") @test check(test_2, "values in heap order") # Check `copy`. B = copy(A) @test typeof(B) === typeof(A) @test length(B) == length(A) @test nodes(A) == nodes(B) @test index(A) == index(B) S = Set(keys(B)) @test length(S) == length(B) # keys are unique? test_1 = true for k in S test_1 &= (haskey(A, k) && haskey(B, k) && A[k] == B[k]) end @test check(test_1, "`copy` yields same nodes") # Check `haskey`, `get`, and `getkey`. test_1 = true test_2 = true test_3 = true for key in keys(B) test_1 &= haskey(B, key) test_2 &= get(B,key,undef) === B[key] test_3 &= getkey(B,key,undef) === key end @test check(test_1, "`haskey(pq,key)` yields true for all existing keys") @test check(test_2, "`get(pq,key,def)` yields key priority for all existing keys") @test check(test_2, "`getkey(pq,key,def)` yields key for all existing keys") # Check `delete!` and result of addressing a non-existing key. for key in (length(B) - 3, length(B)>>1, 2) delete!(B, key) @test !haskey(B, key) @test get(B, key, undef) === undef @test_throws ArgumentError B[key] end # Check `isempty`, `empty!`, etc. empty!(B) @test isempty(B) @test length(B) == 0 @test length(A) == n # no side effects on A # Check `setindex!` in heap order. length(B) > 1 && empty!(B) test_1 = true test_2 = true for i in randperm(n) k, v = key_list[i], val_list[i] B[k] = v test_1 &= isheap(o, nodes(B)) test_2 &= (haskey(B, k) && B[k] == R[k]) end @test check(test_1, "heap structure preserved by `setindex!`") @test check(test_2, "same value for key after `setindex!`") @test length(B) == length(A) test_1 = true test_2 = true for i in randperm(n) k = key_list[i] test_1 &= haskey(B, k) test_2 &= B[k] == R[k] end @test check(test_1, "no missing keys in random order") @test check(test_2, "same values in random order") # Check that `delete!` maintains the binary-heap structure. test_1 = true test_2 = true test_3 = true for i in randperm(n) k = key_list[i] test_1 &= haskey(B, k) delete!(B, k) test_2 &= isheap(o, nodes(B)) test_3 &= !haskey(B, k) end @test check(test_1, "keys exist before `delete!`") @test check(test_2, "heap structure preserved by `delete!`") @test check(test_3, "keys do not exist after `delete!`") @test isempty(B) # Check that `pop!`, `dequeue_pair!`, and `dequeue_node!`, extracts nodes # in order and maintains the binary-heap structure. B = copy(A) test_0 = true test_1 = true test_2 = true test_3 = true prev = (isa(o, ReverseOrdering) ? typemax : typemin)(V) for i in 1:n if (i % 3) == 1 x = pop!(B) test_0 &= (x isa Pair) k, v = x elseif (i % 3) == 2 x = dequeue_pair!(B) test_0 &= (x isa Pair) k, v = x else x = dequeue_node!(B) test_1 &= (x isa AbstractNode) k, v = x end k, v = x test_2 &= isheap(o, nodes(B)) test_3 &= !lt(o, v, prev) prev = v end @test check(test_0, "`pop!` and `dequeue_pair!` yield pairs") @test check(test_1, "`dequeue_node!` yield nodes") @test check(test_2, "heap structure preserved by `pop!`") @test check(test_3, "`pop!` yields keys in order") @test isempty(B) # Tests for fast priority queues. if isa(A, FastPriorityQueue) cartesian_index = CartesianIndices(index(A)) linear_index = LinearIndices(index(A)) test_1 = true test_2 = true test_3 = true test_4 = true test_5 = true test_6 = true test_7 = true test_8 = true for i in randperm(n) k = key_list[i] c = cartesian_index[k] inds = c.I test_1 &= haskey(A, c) test_2 &= haskey(A, inds) test_3 &= (A[k] == A[c]) test_4 &= (A[k] == A[inds...]) v = A[k] test_5 &= !haskey(delete!(A, c), k) A[c] = v test_6 &= (haskey(A, k) && A[k] == v) test_7 &= !haskey(delete!(A, inds), k) A[inds...] = v test_8 &= (haskey(A, k) && A[k] == v) end @test check(test_1, "`haskey` with Cartesian index") @test check(test_2, "`haskey` with multi-dimensional index") @test check(test_3, "`getindex` with Cartesian index") @test check(test_4, "`getindex` with multi-dimensional index") @test check(test_5, "`delete!` with Cartesian index") @test check(test_6, "`setindex!` with Cartesian index") @test check(test_7, "`delete!` with multi-dimensional index") @test check(test_8, "`setindex!` with multi-dimensional index") end end @testset "Priority queues " begin @test QuickHeaps.default_ordering(AbstractPriorityQueue) === SafeMin @test QuickHeaps.default_ordering(PriorityQueue) === SafeMin K, V, n = Int, Float64, 20 key_list = map(K, 1:n) val_list = rand(V, n) test_queue!(PriorityQueue{K,V}(), key_list, val_list) test_queue!(PriorityQueue{K,V}(Reverse), key_list, val_list) end @testset "Fast priority queues " begin @test QuickHeaps.default_ordering(FastPriorityQueue) === SafeMin V, dims = Float32, (2,3,4) n = prod(dims) m = div(9n + 5, 10) # keep ~90% of indices key_list = randperm(n)[1:m] val_list = rand(V, m) test_queue!(FastPriorityQueue{V}(dims), key_list, val_list) test_queue!(FastPriorityQueue{V}(Reverse, dims), key_list, val_list) end end # module
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
123
include("utilities_tests.jl") include("nodes_tests.jl") include("binaryheaps_tests.jl") include("priorityqueues_tests.jl")
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
code
2103
module TestingQuickHeapsUtilities using Test using QuickHeaps @testset "Utilities " begin let A = rand(Float32, 6) @test QuickHeaps.has_standard_linear_indexing(A) == true @test QuickHeaps.has_standard_linear_indexing(view(A, 2:3:6)) == true end @test QuickHeaps.is_one_based_unit_range(axes(rand(3), 1)) == true @test QuickHeaps.is_one_based_unit_range(1:4) == true @test QuickHeaps.is_one_based_unit_range(2:4) == false @test QuickHeaps.is_one_based_unit_range(1:2:5) == false let A = rand(Float32, 2) @test_deprecated QuickHeaps.to_eltype(A, 11) @test QuickHeaps.to_eltype(A, 11) isa Float32 @test QuickHeaps.to_eltype(A, π) isa Float32 end @test QuickHeaps.in_range(0, 3) == false @test QuickHeaps.in_range(1, 3) == true @test QuickHeaps.in_range(3, 3) == true @test QuickHeaps.in_range(4, 3) == false let A = collect(0:4) @test QuickHeaps.in_range(0, A) == false @test QuickHeaps.in_range(1, A) == true @test QuickHeaps.in_range(5, A) == true @test QuickHeaps.in_range(6, A) == false end let R = Base.OneTo(5) @test QuickHeaps.in_range(0, R) == false @test QuickHeaps.in_range(1, R) == true @test QuickHeaps.in_range(5, R) == true @test QuickHeaps.in_range(6, R) == false end let R = 0:4 @test QuickHeaps.in_range(-1, R) == false @test QuickHeaps.in_range(0, R) == true @test QuickHeaps.in_range(4, R) == true @test QuickHeaps.in_range(5, R) == false end let x = nothing @test QuickHeaps.typename(x) isa String @test QuickHeaps.typename(x) == QuickHeaps.typename(typeof(x)) end @test QuickHeaps.has_bad_values(1:2) == false @test QuickHeaps.has_bad_values([1.0,2.0]) == false @test QuickHeaps.has_bad_values([1.0,2.0,NaN]) == true @test_throws ArgumentError QuickHeaps.throw_argument_error("invald ", "argument") @test_throws DimensionMismatch QuickHeaps.throw_dimension_mismatch("not", " same dimensions") end end # module
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
1751
# User visible changes in `QuickHeaps` ## Version 0.2.2 - Update compatibility for `TypeUtils`. ## Version 0.2.1 - Package `TypeUtils` replaces `ArrayTools`. - Un-exported method `QuickHeaps.to_eltype(A, x)` has been deprecated, use `as(eltype(A), x)`. ## Version 0.2.0 This version mainly provides a cleaner API where priority queues behave more like dictionaries. - Provide `dequeue_node!` which removes the root node from a priority queue and returns it. This is similar to `dequeue_pair!` or `pop!` which both return a `Pair`. The syntax `dequeue(T,pq)!` to remove the root node from `pq` and return it converted to type `T` is no longer supported; call `T(dequeue_node!(pq))` or `convert(T, dequeue_node!(pq))` instead. - The noun *node* is replaced by *value* for a binary-heap. The non-exported method `QuickHeaps.nodes(h)` has been renamed as `QuickHeaps.storage(h)` to retrieve the object backing the storage of the binary heap `h`. - Change parameters of priority queue types which are now `AbstractPriorityQueue{K,V,O}`, `PriorityQueue{K,V,O,T}`, and `FastPriorityQueue{V,N,O,T}` with `K` the type of the keys, `V` the type of the priority values, `O` the type of the ordering, `T<:AbstractNode{K,V}` the type of the nodes, and `N` the number of dimensions. - Priority queues behave more like dictionaries. Methods `get(pq,key,def)` and `getkey(pq,key,def)` yield the value (was the node) and the key associated with `key` in priority queue `pq` or `def` if such a key does not exist. - `heapify_down!` and `heapify_up!` return the array. - Remove unused non-exported methods `unsafe_heapify!`, `require_one_based_indexing`, ... ## Version 0.1.2 - Fix a few bugs. - provide docs. - Extend tests.
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
9053
# Versatile binary heaps and priority queues for Julia [![Doc. Stable][doc-stable-img]][doc-stable] [![Doc. Devel][doc-dev-img]][doc-dev] [![License][license-img]][license-url] [![Build Status][github-ci-img]][github-ci-url] [![Build Status][appveyor-img]][appveyor-url] [![Coverage][codecov-img]][codecov-url] `QuickHeaps` is a small [Julia][julia-url] package providing versatile [binary heaps](https://en.wikipedia.org/wiki/Binary_heap) and [priority queues](https://en.wikipedia.org/wiki/Priority_queue). These data structures are more flexible and may be quite significantly faster than those provided by [`DataStructures`][datastructures-url]. ## Installation The easiest way to install `QuickHeaps` is to use [Julia's package manager](https://pkgdocs.julialang.org/): ```julia using Pkg pkg"add QuickHeaps" ``` ## Documentation Documentation is available for different versions of `QuickHeaps`: - [last release][doc-stable]; - [development version][doc-stable]. ## Speed up and strengthen sorting algorithms The sorting algorithms in Julia are very powerful but have some issues (for me): 1. Sorting algorithms involve lots of comparisons and could be much faster if we know that there are no NaN's in the arrays to sort or if we assume (at our own risk) that they can be ignored. 2. Some non-exported methods may be very useful if they can be safely called. This short note is bout dealing with these two points. ### Speed up sorting Sorting algorithms in Julia rely on `Base.Order.lt(o,x,y)` to check whether `x` is *before* `y` according to the ordering specified in `o` (the letters `lt` stands for *less than*). Most (all?) Julia sorting methods have an `order` keyword to specify the ordering. By default, ordering is `Base.Order.Forward` which is the singleton of type `Base.Order.ForwardOrdering`. Another usual choice is to take `Base.Order.Reverse`. In short, when sorting, you are using the following definitions: ```julia const Forward = ForwardOrdering() const Reverse = ReverseOrdering() lt(o::ForwardOrdering, a, b) = isless(a,b) lt(o::ReverseOrdering, a, b) = lt(o.fwd,b,a) ``` So it turns out that, `isless` is eventually called, not the operator `<`. For integers `isless(x,y)` and `x < y` are the same (at least as far as execution time is concerned) but for floating-point values, `isless` takes care of NaN's which involves overheads and this may strongly impact the execution time of sorting algorithms. Simple means to ignore NaN's in sorting consists in defining your own ordering types and extend the `Base.Order.lt` method, this is pretty simple: ```julia using Base: Ordering, ReverseOrdering struct FastForwardOrdering <: Ordering end const FastForward = FastForwardOrdering() const FastReverse = ReverseOrdering(FastForward) import Base: lt lt(::FastForwardOrdering, a, b) = a < b ``` Then just use keyword `order=FastForward` or `order=FastReverse` in calls to sort methods to benefit from a speed-up factor between 2 or 3. Almost for free! The very same trick has been implemented in the [`DataStructures`](https://github.com/JuliaCollections/DataStructures.jl) package with `DataStructures.FasterForward()` and `DataStructures.FasterReverse()`. Checking that an array has NaN's can be checked in linear time, that is `O(n)`, for arrays of `n` floating-point values by the following method: ```julia function has_nans(A::AbstractArray{<:AbstractFloat}) flag = false @inbounds @simd for i in eachindex(A) flag |= isnan(A[i]) end return flag end ``` where short-circuit has been purposely avoided to exploit SIMD optimization. The rationale is that if you are mostly interested in arrays with no NaN's, you expect that the entire array be checked. A simple benchmark follows: ```julia using BenchmarkTools x = rand(1000); @btime has_nans($x) # ----> 119.054 ns (0 allocations: 0 bytes) ``` which is much shorter than the time it takes to heapify the array. This test could be applied to arrays of floating-point values to choose between fast/slow ordering. This would not change the behavior of the sorting methods but would significantly reduce the execution time most of the time. For integer-valued arrays, it takes `O(1)` time to check for NaN's: ```julia has_nans(A::AbstractArray{<:Integer}) = false ``` An additional speed-up by a factor between 1.5 and 2 is achievable by proper use of `@inline`, `@inbounds` and `@propagate_inbounds` macros in the code implementing the sorting algorithms. This however requires to modify existing code. This is what is done in [`QuickHeaps`](https://github.com/emmt/QuickHeaps.jl). ### Application to binary heaps As an illustration of the above discussion, below is the output of a small benchmark ran by: ```julia julia --project test/benchmarks.jl ``` with Julia 1.6.3 on an AMD Ryzen Threadripper 2950X 16-Core Processor: ``` Timings for "DataStructures" methods (T=Float64, n=1000): - DataStructures.heapify!(..., Base.Forward) ---------------------> 7.478 μs (0 allocations: 0 bytes) - DataStructures.heapify!(..., Base.Reverse) ---------------------> 7.268 μs (0 allocations: 0 bytes) - DataStructures.heapify!(..., DataStructures.FasterForward()) ---> 3.444 μs (0 allocations: 0 bytes) - DataStructures.heapify!(..., DataStructures.FasterReverse()) ---> 3.428 μs (0 allocations: 0 bytes) - DataStructures.heapify!(..., QuickHeaps.FastMin) ---------------> 3.413 μs (0 allocations: 0 bytes) - DataStructures.heapify!(..., QuickHeaps.FastMax) ---------------> 3.428 μs (0 allocations: 0 bytes) Timings for "QuickHeaps" methods (T=Float64, n=1000): - QuickHeaps.heapify!(..., Base.Forward) -------------------------> 4.852 μs (0 allocations: 0 bytes) - QuickHeaps.heapify!(..., Base.Reverse) -------------------------> 4.506 μs (0 allocations: 0 bytes) - QuickHeaps.heapify!(..., DataStructures.FasterForward()) -------> 1.655 μs (0 allocations: 0 bytes) - QuickHeaps.heapify!(..., DataStructures.FasterReverse()) -------> 1.658 μs (0 allocations: 0 bytes) - QuickHeaps.heapify!(..., QuickHeaps.FastMin) -------------------> 1.637 μs (0 allocations: 0 bytes) - QuickHeaps.heapify!(..., QuickHeaps.FastMax) -------------------> 1.658 μs (0 allocations: 0 bytes) Timings for "DataStructures" methods (T=Float64, n=1000): - DataStructures.isheap(..., Base.Forward) -----------------------> 1.910 μs (0 allocations: 0 bytes) - DataStructures.isheap(..., Base.Reverse) -----------------------> 1.932 μs (0 allocations: 0 bytes) - DataStructures.isheap(..., DataStructures.FasterForward()) -----> 563.027 ns (0 allocations: 0 bytes) - DataStructures.isheap(..., DataStructures.FasterReverse()) -----> 575.110 ns (0 allocations: 0 bytes) - DataStructures.isheap(..., QuickHeaps.FastMin) -----------------> 575.087 ns (0 allocations: 0 bytes) - DataStructures.isheap(..., QuickHeaps.FastMax) -----------------> 573.750 ns (0 allocations: 0 bytes) Timings for "QuickHeaps" methods (T=Float64, n=1000): - QuickHeaps.isheap(..., Base.Forward) ---------------------------> 1.820 μs (0 allocations: 0 bytes) - QuickHeaps.isheap(..., Base.Reverse) ---------------------------> 1.821 μs (0 allocations: 0 bytes) - QuickHeaps.isheap(..., DataStructures.FasterForward()) ---------> 381.527 ns (0 allocations: 0 bytes) - QuickHeaps.isheap(..., DataStructures.FasterReverse()) ---------> 383.847 ns (0 allocations: 0 bytes) - QuickHeaps.isheap(..., QuickHeaps.FastMin) ---------------------> 378.627 ns (0 allocations: 0 bytes) - QuickHeaps.isheap(..., QuickHeaps.FastMax) ---------------------> 384.631 ns (0 allocations: 0 bytes) ``` These timings show the gain in speed for `heapify!` by using `<` instead of `isless` by a factor of 2.3 for the binary heap implemented by `DataStructures` and by a factor of 3.2 for the binary heap implemented by `QuickHeaps`. These timings also show that `heapify!` in `QuickHeaps` is faster than in `DataStructures` by a factor greater than 1.5 with standard orderings and by a factor better than 2 with faster orderings. [julia-url]: https://julialang.org/ [datastructures-url]: https://github.com/JuliaCollections/DataStructures.jl [license-url]: ./LICENSE.md [license-img]: http://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat [doc-stable]: https://emmt.github.io/QuickHeaps.jl/stable [doc-dev]: https://emmt.github.io/QuickHeaps.jl/dev [doc-stable-img]: https://img.shields.io/badge/docs-stable-blue.svg [doc-dev-img]: https://img.shields.io/badge/docs-dev-blue.svg [github-ci-img]: https://github.com/emmt/QuickHeaps.jl/actions/workflows/CI.yml/badge.svg?branch=master [github-ci-url]: https://github.com/emmt/QuickHeaps.jl/actions/workflows/CI.yml?query=branch%3Amaster [appveyor-img]: https://ci.appveyor.com/api/projects/status/github/emmt/QuickHeaps.jl?branch=master [appveyor-url]: https://ci.appveyor.com/project/emmt/QuickHeaps-jl/branch/master [codecov-img]: http://codecov.io/github/emmt/QuickHeaps.jl/coverage.svg?branch=master [codecov-url]: http://codecov.io/github/emmt/QuickHeaps.jl?branch=master
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
1472
- Add `@inbounds` and benchmark priority queues. - Extend `maximum` and `minimum` for binary heaps. - Remove `push!(heap,())`, implement `push!(heap)`. - Implement `pushpop!` and `heapreplace!` (see https://en.wikipedia.org/wiki/Binary_heap). - Provide aliases `MinHeap`, `MaxHeap`, `FastMinHeap`, and `FastMaxHeap`. - Add a switch to automatically cope with NaN's. - `enqueue!(Val(:up), pq, k => v)` and `enqueue!(Val(:down), pq, k => v)` - Priority queue index can be any sub-type of `AbstractDict` of `AbstractArray`. - Deal with non 1-based indices in binary heaps. - Ensure type-stability of pairs (`Pair{K,V}`) returned by priority queues. - Have a `wrap!(BinaryHeap,vals)` method that shares the vector of values while the constructor always copies the vector of values. - For priority queues: extend `pairs` - Remove unused `heapify_down!`, `heapify_up!`, and `require_one_based_indexing`. - Change `show` method for `AbstractPriorityQueue` to reflect that. - Allow for directly storing pairs in `AbstractPriorityQueue`? - Implement `merge`, `merge!`, and `reverse`: ```julia reverse(h::BinaryHeap) = BinaryHeap(copy(values(h), 1:lenght(h)), reverse(ordering(h))) reverse(pq::PriorityQueue{K,V,O,T}) where {K,V,O,T} = merge!(PriorityQueue{K,V}(reverse(ordering(pq)), T), pq) reverse(pq::FastPriorityQueue{V,N,O,T}) where {V,N,O,T} = merge!(FastPriorityQueue{V,N}(reverse(ordering(pq)), T), size(index(pq)); pq) ... ```
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
7812
# Binary heaps [Binary heaps](https://en.wikipedia.org/wiki/Binary_heap) dynamically store values in a tree structure built according to a given ordering of these values. Thanks to this structure, a number of operations can be efficiently implemented. For a binary heap of `n` values, pushing a new value, extracting the least (or the greatest depending on the ordering) value out of the heap, deleting a value, and replacing a value all have a complexity of `O(log(n))` at worst. Just getting the least (or the greatest) value without extracting it out of the heap is an `O(1)` operation. ## Basic usage In `QuickHeaps`, a binary heap is created by the [`BinaryHeap`](@ref) constructor: ```julia h = BinaryHeap{T}(o = FastMin) ``` where `T` is the type of the values stored by the heap and `o::Ordering` is the ordering rule for sorting values. The default `FastMin` ordering yields a *min-heap* whose root entry is the smallest one. With `o = ReverseOrdering(FastMin)` or `o = FastMax`, a *max-heap* is created. The root element of a min-heap (resp. a max-heap) is the smallest one (resp. the greatest one). !!! warning Ordering `FastMin` (resp. `FastMax`) is like `Forward` (resp. `Reverse`) but much faster for floating-point values. However, `FastMin` and `FastMax` are not consistent with NaN (*Not a Number*) values. If your data may contains NaNs, use `Forward` or `Reverse` instead of `FastMin` or `FastMax`. Aliases `SafeMin=Forward` (and `SafeMax=Reverse`) are provided by the `QuickHeaps` package. A vector `vals` storing the initial values of the binary heap can be specified: ```julia h = BinaryHeap{T}(vals, o = FastMin) ``` to create a binary heap starting with the values in `vals`. Type parameter `T` can be omitted to assume `T=eltype(vals)`. The initial values need not be ordered, the `BinaryHeap` constructor automatically takes care of that. If `vals` is a `Vector` instance with elements of type `T`, the binary-heap will be directly built into `vals`. Call `BinaryHeap(copy(vals))` to create a binary heap with its own storage. A binary heap `h` can be used as an ordered queue of values: ```julia pop!(h) # yields the root value and discard it from the heap push!(h, x) # pushes value x in heap h ``` The *root* value is the first one according to the ordering of the heap. To examine the root value without discarding it from the heap, call either of: ```julia peek(h) first(h) h[1] ``` A binary heap `h` behaves like an abstract vector (with 1-based linear indices), in particular: ```julia length(h) # yields the number of values in heap h h[i] # yields the i-th value of heap h h[i] = x # sets the i-th value of heap h and heapify h ``` Note that `h[1]` is the value of the root entry of the heap `h` (the least heap values for a min-heap, the greatest heap value for a max-heap) and that setting a value in the heap may trigger reordering of the values stored by the heap to maintain the binary heap structure. In particular, after doing `h[i] = x`, do not assume that `h[i]` yields `x`. To delete the `i`-th value from the heap `h`, call: ```julia delete!(h, i) ``` Call `empty!(h)` to delete all the values of the binary heap `h` and `isempty(h)` to query whether `h` is empty. !!! note Operations that modify the heap, like deletion by `delete!(h,i)`, insertion by `h[i] = x`, pushing by `push!(h,x)`, and extracting by `pop!(h)` are of numerical complexity `O(1)` in the best case, `O(log(n))` in the worst case, with `n = length(h)` the number of values in the heap `h`. Query a given value with `peek(h)`, `first(h)`, or `h[i]` is always of complexity `O(1)`. ### Advanced usage Instances of [`BinaryHeap`](@ref) store their values in a Julia vector whose length is always equal to the number of stored values. Slightly faster binary heaps are created by the [`FastBinaryHeap`](@ref) constructor. Such binary heaps never automatically reduce the size of the array backing the storage of their values (even though the size is automatically augmented as needed). You may call `resize!(h)` to explicitly reduce the storage to its minimum. A hint about the anticipated size `n` of a heap `h` (of any kind) can be set by: ```julia sizehint!(h, n) ``` which yields `h`. ### Customize binary heaps The behavior of the binary heap types provided by `QuickHeaps` can be tweaked by using a particular instance of the ordering `o::Ordering` and by specializing the `Base.lt` method called as `Base.lt(o,x,y)` to decide whether value `x` occurs before value `y` according to ordering `o`. Note that in the implementation of binary heaps in the `QuickHeaps` package, `x` and `y` will always be both of type `T`, the type of the values stored by the heap. If this is not sufficient, a custom binary heap type may be created that inherits from `AbstractBinaryHeap{T,O}` with `T` the type of the values stored by the heap and `O` the type of the ordering. Assuming the array backing the storage of the values in the custom heap type has 1-based linear indexing, it is sufficient to specialize the following methods for an instance `h` of the custom heap type, say `CustomBinaryHeap`: - `Base.length(h::CustomBinaryHeap)` yields the number of values in `h`; - `Base.empty!(h::CustomBinaryHeap)` delete all values in `h`; - [`QuickHeaps.storage`](@ref)`(h::CustomBinaryHeap)` yields the array backing the storage of values; - [`QuickHeaps.ordering`](@ref)`(h::CustomBinaryHeap)`] yields the ordering of the values; - [`QuickHeaps.unsafe_grow!`](@ref)`(h::CustomBinaryHeap)` - [`QuickHeaps.unsafe_shrink!`](@ref)`(h::CustomBinaryHeap)` to have a fully functional custom binary heap type. By default, `Base.resize!(h)` does nothing (except returning its argument) for any instance `h` of a type that inherits from `AbstractBinaryHeap`; but this method may also be specialized. The `QuickHeaps` package provides a number of methods (some unexported) that may be useful for implementing new binary heap types: - [`QuickHeaps.heapify`](@ref) - [`QuickHeaps.heapify!`](@ref) - [`QuickHeaps.isheap`](@ref) - [`QuickHeaps.heapify_down!`](@ref) - [`QuickHeaps.heapify_up!`](@ref) - [`QuickHeaps.unsafe_heapify_down!`](@ref) - [`QuickHeaps.unsafe_heapify_up!`](@ref) Note that the `heapify`, `heapify!`, and `isheap` methods which are exported by the `QuickHeaps` package have the same behavior but are different than those in the [`DataStructures`](https://github.com/JuliaCollections/DataStructures.jl) package. If you are using both packages, you'll have to explicitly prefix these methods by the package module. ## Simple priority queues A binary heap can be used to implement a simple [priority queue](https://en.wikipedia.org/wiki/Priority_queue) with keys of type `K` and values of type `V` as follows: ```julia struct Node{K,V} key::K val::V end Base.lt(o::Base.Ordering, a::T, b::T) where {T<:Node} = lt(o, a.val, b.val) Q = FastBinaryHeap{Node}() ``` This simple priority queue is a binary heap (a *min-heap* in that case) of nodes storing key-value pairs which as sorted according to their values. The same `Node` structure as the one defined above and with the same specialization of `Base.lt` is provided (but not exported) by `QuickHeaps`, so a simplified version of the above example is: ```julia using QuickHeaps: Node Q = FastBinaryHeap{Node}() ``` Such a priority queue is faster than `DataStructures.PriorityQueue` but it provides no means to requeue a node nor to ensure that keys are unique. An auxiliary array, a dictionary, or a set can be used for that, this is implemented by [`QuickHeaps.PriorityQueue`](@ref) and [`QuickHeaps.FastPriorityQueue`](@ref) which are more flexible and offer more capabilities than the simple implementation in the above example.
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
525
# Introduction `QuickHeaps` is a [Julia](https://julialang.org/) package providing versatile [binary heaps](binaryheaps.html) and [priority queues](priorityqueues.html). These data structures are more flexible and may be quite significantly faster than those provided by [`DataStructures`](https://github.com/JuliaCollections/DataStructures.jl). ## Table of contents ```@contents Pages = ["install.md", "binaryheaps.md", "priorityqueues.md", "nodes.md", "library.md"] ``` ## Index of types and methods ```@index ```
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
169
# Installation The easiest way to install `QuickHeaps` is to use [Julia's package manager](https://pkgdocs.julialang.org/): ```julia using Pkg pkg"add QuickHeaps" ```
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
1527
# Reference The following reproduces the in-lined documentation about types and methods of the [`QuickHeaps`](https://github.com/emmt/QuickHeaps.jl) package. This documentation is also available from the REPL by typing `?` followed by the name of a method or a type. ## Binary Heaps ```@docs QuickHeaps.AbstractBinaryHeap QuickHeaps.BinaryHeap QuickHeaps.FastBinaryHeap QuickHeaps.heapify QuickHeaps.heapify! QuickHeaps.heapify_down! QuickHeaps.heapify_up! QuickHeaps.isheap QuickHeaps.unsafe_heapify_down! QuickHeaps.unsafe_heapify_up! QuickHeaps.unsafe_grow! QuickHeaps.unsafe_shrink! ``` ## Priority Queues ```@docs QuickHeaps.AbstractPriorityQueue QuickHeaps.PriorityQueue QuickHeaps.FastPriorityQueue dequeue!(::QuickHeaps.AbstractPriorityQueue) dequeue_node! dequeue_pair! ``` ## Nodes ```@docs QuickHeaps.AbstractNode QuickHeaps.Node QuickHeaps.get_key QuickHeaps.get_val ``` ## Orderings ```@docs QuickHeaps.FastForwardOrdering QuickHeaps.default_ordering ``` ## Miscellaneous The following unexported methods may be needed for implementing new types of binary heap or of priority queue. End-users probably not have to worry about these. ```@docs QuickHeaps.has_bad_values QuickHeaps.has_standard_linear_indexing QuickHeaps.heap_index QuickHeaps.in_range QuickHeaps.is_one_based_unit_range QuickHeaps.linear_index QuickHeaps.nodes QuickHeaps.index QuickHeaps.storage QuickHeaps.ordering QuickHeaps.setroot! QuickHeaps.to_eltype QuickHeaps.to_key QuickHeaps.to_node QuickHeaps.to_val QuickHeaps.typename ```
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
1812
# Nodes types Nodes in priority queues provided by `QuickHeaps` have super-type: ```julia QuickHeaps.AbstractNode{K,V} ``` with `K` and `V` the respective types of the key and of the value of the node. In principle, priority of a node is based on its value, but this may be changed by using custom node and/or ordering types. Having a specific node type different than, say, `Pair{K,V}` is to allow customizing how the nodes are compared for ordering by specializing `Base.lt` without [type-piracy](https://docs.julialang.org/en/v1/manual/style-guide/#Avoid-type-piracy). A node `x` can be iterated and converted into a pair or a 2-tuple of its key `k` and its value `v` and conversely: ```julia k, v = x # extract key and value of a node Pair(x) # yields k=>v Tuple(x) # yields (k,v) QuickHeaps.Node((k, v)) # is the same as QuickHeaps.Node(k, v) QuickHeaps.Node(k => v) # is the same as QuickHeaps.Node(k, v) ``` The `getkey` and (unexported) [`QuickHeaps.getval`](@ref) methods respectively retrieve the key and the value of a node. These two methods may be specialized for a given sub-type of [`QuickHeaps.AbstractNode`](@ref). For example, a *key-only* node type can be fully implemented by: ```julia struct KeyOnlyNode{K} <: QuickHeaps.AbstractNode{K,Nothing} key::K end QuickHeaps.getkey(x::KeyOnlyNode) = getfield(x, :key) QuickHeaps.getval(x::KeyOnlyNode) = nothing KeyOnlyNode(x::Tuple{K,Nothing}) where {K} = KeyOnlyNode{K}(x[1]) KeyOnlyNode(x::Pair{K,Nothing}) where {K} = KeyOnlyNode{K}(x.first) ``` To provide your own ordring rules, you may specialize `Base.lt` which otherwise defaults to: ```julia Base.lt(o::Ordering, a::QuickHeaps.AbstractNode, b::QuickHeaps.AbstractNode) = lt(o, QuickHeaps.getval(a), QuickHeaps.getval(b)) ```
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
0.2.2
08303b9829c04879988030557cb9e65d3c1f66ff
docs
5760
# Priority queues [Priority queues](https://en.wikipedia.org/wiki/Priority_queue) are partially ordered dynamic lists of so-called *nodes* which are key-value pairs. Priority queues are designed so that updating the list of stored nodes while maintaining the ordering and retrieving or extracting the node of highest priority are efficient operations. Priority queues provided by `QuikHeaps` are similar to dictionaries (or to arrays) with the additional feature of maintaining an ordered structure so that getting the node of highest priority costs `O(1)` operations while changing the priority of a node or pushing a node only costs `O(log(n))` operations with `n` the length of the queue. ## Building priority queues In `QuikHeaps`, priority queues combine a [binary heap](binaryheaps.html) to store the partially sorted list of nodes and another structure to associate keys and nodes. There are two possibilities depending on the kind of keys. ### Versatile priority queues `QuikHeaps` provides versatile priority queues which use a dictionary to associate keys with nodes and thus impose no restrictions on the type of the keys. To build a versatile priority queue, call the [`PriorityQueue`](@ref) constructor: ```julia Q = PriorityQueue{K,V}([o=Forward,] T=Node{K,V}) ``` where optional parameter `o::Ordering` specifies the ordering for deciding the priority of values while optional parameter `T<:AbstractNode{K,V}` specifies the type of the nodes with `K` and `V` the respective types of the keys and of the values. Type parameters `K` and `V` may be omitted if the node type `T` is specified. ### Fast priority queues If keys are analoguous to indices in some array, the key-node association can be realized by a regular array which is faster than a dictionary as used by versatile priority queues. To build a fast priority queue with keys indexing an array of dimensions `dims...`, call the [`FastPriorityQueue`](@ref) constructor: ```julia Q = FastPriorityQueue{V}([o=Forward,] [T=Node{Int,V},] dims...) ``` where `o::Ordering` specifies the ordering of values in the priority queue, `T<:AbstractNode{Int,V}` is the type of the nodes depending on `V` the type of the values encoding the priority. Type parameter `V` may be omitted if the node type `T` is specified. The keys in this kind of priority queue are the linear or Cartesian indices in an array of size `dims...`. For example, if `dims = (3,4,5)`, then all the following expressions refer to the same key: ```julia Q[44] Q[2,3,4] Q[CartesianIndex(2,3,4)] ``` The storage of a fast priority queue requires `prod(dims...)*sizeof(Int) + n*sizeof(T)` bytes with `n` enqueued nodes. ## Common methods for priority queues In `QuikHeaps`, priority queues have a common interface which is described here. The first thing to do with a freshly created priority queue is to populate it. To enqueue key `k` with priority `v` in priority queue `Q`, all the following is equivalent: ```julia Q[k] = v push!(Q, k => v) enqueue!(Q, k => v) enqueue!(Q, k, v) ``` Note that key `k` may already exists in `Q`; in this case, the priority associated with the key is updated and the queue reorderd if necessary in, at worse, `O(log(n))` operations. This is generally faster than first deleting the key and then enqueuing the key with the new priority. To extract the node of highest priority out of the queue `Q` and get its key `k` and, possibly, its priority `v`, call one of: ```julia k = dequeue!(Q) k, v = pop!(Q) ``` Methods [`dequeue_pair!`](@ref) and [`dequeue_node!`](@ref) also extract the root node out of a priority queue and return it as a `Pair` or as as a node of the type used by the queue. To just examine the node of highest priority, call one of: ```julia k, v = peek(Q) k, v = first(Q) ``` Like the `dequeue!` method, the `peek` method may also be called with a type argument. A priority queue `Q` behaves like a dictionary: ```julia length(Q) # yields number of nodes isempty(Q) # yields whether priority queue is empty empty!(Q) # empties priority queue keytype(Q) # yields key type `K` valtype(Q) # yields value type `V` Q[v] # yields the value of key `k` get(Q, k, def) # query value at key, with default Q[k] = v # set value `v` of key `k` push!(Q, k => v) # idem. haskey(Q, k) # yields whether key `k` exists delete!(Q, k) # delete node at key `k` ``` Note that the syntax `Q[k]` throws an exception if key `k` does not exists in `Q`. Finally, there are different ways to iterate on the (unordered) contents of a priority queue `Q`: ```julia keys(Q) # yields iterator over keys vals(Q) # yields iterator over values for (k,v) in Q; ...; end # loop over key-value pairs ``` Note that these iterators yield nodes in their storage order which is not necessarily that of their priority. The order is however the same for these iterators. ## Priority order How are ordered the nodes is completely customizable by specializing the `Base.lt` method with the following signature: ```julia Base.lt(o::OrderingType, a::T, b::T) where {T<:NodeType} ``` which shall yield whether node `a` has (strictly) higher priority than node `b` in the queue and where `OrderingType` and `NodeType <: [QuickHeaps.AbstractNode](@ref)` are the respective types of the ordering and of the nodes of the priority queue. For the default node type, `QuickHeaps.Node{K,V}`, the implementation is: ```julia Base.lt(o::Ordering, a::T, b::T) where {T<:QuickHeaps.Node} = lt(o, QuickHeaps.getval(a), QuickHeaps.getval(b)) ``` where [`QuickHeaps.getval(a)`](@ref) yields the value of node `a`. In other words, nodes are sorted by their value according to ordering `o`.
QuickHeaps
https://github.com/emmt/QuickHeaps.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
2869
using BenchmarkTools, DynamicalBilliards, IterTools const SUITE = BenchmarkGroup(["DynamicalBilliards"]) bt = billiard_mushroom() bt2 = billiard_sinai(;setting="periodic") ################################################################################ ## COLLISION & PROPAGATION ################################################################################ particles = [Particle(0.05, 0.05, -0.1), MagneticParticle(0.05,0.05,-0.1,1.0)] obstacles = [bt[1], bt[6], bt2[1], bt2[5]] #distinct obstacles for resolvecollision! tests proptime = 4.2 ptypes = ["straight", "magnetic"] colf = (collision, next_collision, bounce!, resolvecollision!, propagate!, lyapunovspectrum ) name = (f) -> split(string(f), '.')[end] for f in colf SUITE[name(f)] = BenchmarkGroup(["propagation", "collision"]) for ptype ∈ ptypes SUITE[name(f)][ptype] = BenchmarkGroup(["propagation", "collision", ptype]) end end for (f, p) in zip(["straight", "magnetic"], particles) for o in chain(bt, bt2) SUITE["collision"][f][o.name] = @benchmarkable collision($p, $o) end end for (f, p) in zip(["straight", "magnetic"], particles) for (bname, bil) in zip(["mushroom", "psinai"], (bt, bt2)) SUITE["next_collision"][f][bname] = @benchmarkable next_collision($p, $bil) end end for (f, p) in zip(["straight", "magnetic"], particles) for (bname, bil) in zip(["mushroom", "psinai"], (bt, bt2)) ploc = copy(p) #location mutation screws up tests for different bts SUITE["bounce!"][f][bname] = @benchmarkable bounce!($ploc, $bil) end end let (f, p) = ("straight", particles[1]) #resolvecollision! is indepent of particle type for o in obstacles ploc = copy(p) SUITE["resolvecollision!"][f][o.name] = @benchmarkable resolvecollision!($ploc, $o) end end for (f, p) in zip(["straight", "magnetic"], particles) ploc = copy(p) SUITE["propagate!"][f] = @benchmarkable propagate!($ploc, $proptime) end for (f, p) in zip(["straight", "magnetic"], particles) for (bname, bil) in zip(["mushroom", "psinai"], (bt, bt2)) SUITE["lyapunovspectrum"][f][bname] = @benchmarkable lyapunovspectrum($p, $bil, 10000.0) end end ################################################################################ ## randominside – rewrite to add more non-collision benchmarks ################################################################################ SUITE["randominside"] = BenchmarkGroup() #I don't know any tags for randominside... SUITE["randominside"]["straight"] = BenchmarkGroup(["straight"]) let f = "straight" for (bname, bil) in zip(["mushroom", "psinai"], (bt, bt2)) SUITE["randominside"][f][bname] = @benchmarkable randominside($bil) end end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
116
# Run this in the REPL, not Juno!!! using PkgBenchmark bresult = benchmarkpkg("DynamicalBilliards"; retune = true)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
476
using Revise; using DynamicalBilliards, BenchmarkTools bt = billiard_sinai() p = MagneticParticle(0.1,0.1, π/8, 0.5) @btime next_collision($p, $bt) @btime bounce!($p, $bt) # before sincos(): julia> @btime bounce!($p, $bt) 278.529 ns (0 allocations: 0 bytes) (1, 0.44691013238163385, [0.707091, 0.640047], [-0.353179, 0.935556]) # after sincos(): julia> @btime bounce!($p, $bt) 57.476 ns (0 allocations: 0 bytes) (0, Inf, [0.415228, 1.10629], [0.957396, -0.288778])
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
2909
CI = get(ENV, "CI", nothing) == "true" || get(ENV, "GITHUB_TOKEN", nothing) !== nothing import Pkg Pkg.pkg"add Documenter@1" # Load documenter using Documenter using DocumenterTools: Themes ENV["JULIA_DEBUG"] = "Documenter" # For easier debugging when downloading from a specific branch. github_user = "JuliaDynamics" branch = "master" download_path = "https://raw.githubusercontent.com/$github_user/doctheme/$branch" import Downloads for file in ("juliadynamics-lightdefs.scss", "juliadynamics-darkdefs.scss", "juliadynamics-style.scss") Downloads.download("$download_path/$file", joinpath(@__DIR__, file)) end # create the themes for w in ("light", "dark") header = read(joinpath(@__DIR__, "juliadynamics-style.scss"), String) theme = read(joinpath(@__DIR__, "juliadynamics-$(w)defs.scss"), String) write(joinpath(@__DIR__, "juliadynamics-$(w).scss"), header*"\n"*theme) end # compile the themes Themes.compile(joinpath(@__DIR__, "juliadynamics-light.scss"), joinpath(@__DIR__, "src/assets/themes/documenter-light.css")) Themes.compile(joinpath(@__DIR__, "juliadynamics-dark.scss"), joinpath(@__DIR__, "src/assets/themes/documenter-dark.css")) # Download and apply CairoMakie plotting style using CairoMakie Downloads.download("$download_path/style.jl", joinpath(@__DIR__, "style.jl")) include("style.jl") """ build_docs_with_style(pages::Vector, modules... ; bib = nothing, authors = "George Datseris and contributors", htmlkw = NamedTuple(), kw... ) Call the `makedocs` function with some predefined style components. The first module dictates site name, while the rest need to be included to expand and cross-referrence docstrings from other modules. `kw` are propagated to `makedocs` while `htmlkw` are propagated to `Documenter.HTML`. """ function build_docs_with_style(pages, modules...; bib = nothing, authors = "George Datseris", draft = false, htmlkw = NamedTuple(), kwargs... ) settings = ( modules = [modules...], format = Documenter.HTML(; prettyurls = CI, assets = [ asset("https://fonts.googleapis.com/css?family=Montserrat|Source+Code+Pro&display=swap", class=:css), ], collapselevel = 3, htmlkw..., ), sitename = "$(modules[1]).jl", authors, pages, draft, doctest = false, checkdocs = :exported, linkcheck_timeout = 2, # The following Documenter fails will NOT ERROR the docbuild! warnonly = [:doctest, :missing_docs], kwargs... ) if isnothing(bib) makedocs(; settings...) else makedocs(; plugins=[bib], settings...) end if CI deploydocs( repo = "github.com/JuliaDynamics/$(modules[1]).jl.git", target = "build", push_preview = true ) end end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
1307
cd(@__DIR__) using DynamicalBilliards using CairoMakie timeseries! = DynamicalBilliards.timeseries! import Downloads Downloads.download( "https://raw.githubusercontent.com/JuliaDynamics/doctheme/master/build_docs_with_style.jl", joinpath(@__DIR__, "build_docs_with_style.jl") ) include("build_docs_with_style.jl") using Literate infile = joinpath(@__DIR__, "src", "billiards_visualizations.jl") outdir = joinpath(@__DIR__, "src") Literate.markdown(infile, outdir; credit = false) pages = [ "Introduction" => "index.md", "High Level API" => "basic/high_level.md", "Visualizing & Animating" => "billiards_visualizations.md", "Phase Spaces" => "basic/phasespaces.md", "Ray-Splitting" => "ray-splitting.md", "Lyapunov Exponents" => "lyapunovs.md", "MushroomTools" => "mushroomtools.md", "Physics" => "physics.md", "Internals" => "basic/low_level.md", "Tutorials" => [ "Defining a Billiard" => "tutorials/billiard_table.md", "Defining your own Obstacles" => "tutorials/own_obstacle.md", ] ] build_docs_with_style(pages, DynamicalBilliards; authors = "George Datseris <[email protected]>", expandfirst = ["index.md"], # warnonly = [:doctest, :missing_docs, :cross_references], )
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
941
# Color theme definitions struct CyclicContainer <: AbstractVector{String} c::Vector{String} n::Int end CyclicContainer(c) = CyclicContainer(c, 0) Base.length(c::CyclicContainer) = length(c.c) Base.size(c::CyclicContainer) = size(c.c) Base.iterate(c::CyclicContainer, state=1) = iterate(c.c, state) Base.getindex(c::CyclicContainer, i) = c.c[(i-1)%length(c.c) + 1] Base.getindex(c::CyclicContainer, i::AbstractArray) = c.c[i] function Base.getindex(c::CyclicContainer) c.n += 1 c[c.n] end Base.iterate(c::CyclicContainer, i = 1) = iterate(c.c, i) COLORSCHEME = [ "#7143E0", "#0A9A84", "#191E44", "#AF9327", "#701B80", "#2E6137", ] COLORS = CyclicContainer(COLORSCHEME) LINESTYLES = CyclicContainer(["-", ":", "--", "-."]) # other styling elements for Makie set_theme!(; palette = (color = COLORSCHEME,), fontsize = 22, figure_padding = 8, size = (800, 400), linewidth = 3.0, )
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
6696
# # [Visualizations and Animations for Billiards](@id visualizations) # All plotting and animating for DynamicalBilliards.jl # lies within a few well-defined functions # that use the [Makie](https://github.com/MakieOrg/Makie.jl) ecosystem. # - For static plotting, you can use the function [`bdplot`](@ref) and [`bdplot_boundarymap`](@ref). # - For interacting/animating, you can use the function [`bdplot_interactive`](@ref). # This function also allows you to create custom animations, see [Custom Billiards Animations](@ref). # - For producing videos of time evolution of particles in a billiard, use [`bdplot_video`](@ref). # ```@raw html # <video width="auto" controls autoplay loop> # <source src="https://raw.githubusercontent.com/JuliaDynamics/JuliaDynamics/master/videos/billiards/billiards_app.mp4?raw=true" type="video/mp4"> # </video> # ``` # ## Plotting # ```@docs # bdplot # bdplot_boundarymap # ``` # ### Plotting an obstacle with keywords using DynamicalBilliards, CairoMakie bd = billiard_sinai() fig, ax = bdplot(bd[2]) bdplot!(ax, bd[4]; color = "blue", linestyle = :dot, linewidth = 5.0) bdplot!(ax, bd[1]; color = "yellow", strokecolor = "black") fig # ### Plotting a billiard # %% #src using DynamicalBilliards, CairoMakie bd = billiard_logo()[1] fig, ax = bdplot(bd) fig # ### Plotting some particle trajectories # %% #src using DynamicalBilliards, CairoMakie timeseries! = DynamicalBilliards.timeseries! bd = billiard_hexagonal_sinai() p1 = randominside(bd) p2 = randominside(bd, 1.0) colors = [:red, :black] markers = [:circle, :rect] fig, ax = bdplot(bd) for (p, c) in zip([p1, p2], colors) x, y = timeseries!(p, bd, 20) lines!(ax, x, y; color = c) end bdplot!(ax, [p1, p2]; colors, particle_size = 10, marker = markers) fig # ### Periodic billiard plot # Rectangle periodicity: # %% #src using DynamicalBilliards, CairoMakie r = 0.25 bd = billiard_rectangle(2, 1; setting = "periodic") d = Disk([0.5, 0.5], r) d2 = Ellipse([1.5, 0.5], 1.5r, 2r/3) bd = Billiard(bd.obstacles..., d, d2) p = Particle(1.0, 0.5, 0.1) xt, yt, vxt, vyt, t = DynamicalBilliards.timeseries!(p, bd, 10) fig, ax = bdplot(bd, extrema(xt)..., extrema(yt)...) lines!(ax, xt, yt) bdplot!(ax, p; velocity_size = 0.1) fig # Hexagonal periodicity: # %% #src using DynamicalBilliards, CairoMakie bd = billiard_hexagonal_sinai(0.3, 1.50; setting = "periodic") d = Disk([0.7, 0], 0.2) d2 = Antidot([0.7/2, 0.65], 0.35) bd = Billiard(bd..., d, d2) p = MagneticParticle(-0.5, 0.5, π/5, 1.0) xt, yt = DynamicalBilliards.timeseries(p, bd, 10) fig, ax = bdplot(bd, extrema(xt)..., extrema(yt)...) lines!(ax, xt, yt) bdplot!(ax, p; velocity_size = 0.1) fig # ### Boundary map plot using DynamicalBilliards, CairoMakie bd = billiard_mushroom() n = 100 # how many particles to create t = 200 # how long to evolve each one bmap, arcs = parallelize(boundarymap, bd, t, n) randomcolor(args...) = RGBAf(0.9 .* (rand(), rand(), rand())..., 0.75) colors = [randomcolor() for i in 1:n] # random colors fig, ax = bdplot_boundarymap(bmap, arcs, color = colors) fig # ## Interactive GUI # ```@docs # bdplot_interactive # ``` # ```@raw html # <video width="auto" controls autoplay loop> # <source src="https://raw.githubusercontent.com/JuliaDynamics/JuliaDynamics/master/videos/billiards/billiards_app.mp4?raw=true" type="video/mp4"> # </video> # ``` # For example, the animation above was done with: # ```julia # using DynamicalBilliards, GLMakie # l, w, r = 0.5, 0.75, 1.0 # bd = billiard_mushroom(l, w, r) # N = 20 # ps = vcat( # [MushroomTools.randomchaotic(l, w, r) for i in 1:N], # [MushroomTools.randomregular(l, w, r) for i in 1:N], # ) # colors = [i ≤ N ? RGBf(0.1, 0.4 + 0.3rand(), 0) : RGBf(0.4, 0, 0.6 + 0.4rand()) for i in 1:2N] # fig, phs, chs = bdplot_interactive(bd, ps; # colors, plot_bmap = true, bmap_size = 8, tail_length = 2000, # ); # ``` # ## Custom Billiards Animations # %% #src # To do custom animations you need to have a good idea of how Makie's animation system works. # Have a look [at this tutorial](https://www.youtube.com/watch?v=L-gyDvhjzGQ) if you are # not familiar yet. # Following the docstring of [`bdplot_interactive`](@ref) let's add a couple of # new plots that animate some properties of the particles. # We start with creating the billiard plot and obtaining the observables: using DynamicalBilliards, CairoMakie bd = billiard_stadium(1, 1) N = 100 ps = particlebeam(1.0, 0.6, 0, N, 0.001) fig, phs, chs = bdplot_interactive(bd, ps; playback_controls=false) # Then, we add some axis layout = fig[2,1] = GridLayout() axd = Axis(layout[1,1]; ylabel = "log(⟨d⟩)", alignmode = Outside()) axs = Axis(layout[2,1]; ylabel = "std", xlabel = "time", alignmode = Outside()) hidexdecorations!(axd; grid = false) rowsize!(fig.layout, 1, Auto(2)) fig # Our next step is to create new observables to plot in the new axis, # by lifting `phs, chs`. Let's plot the distance between two particles and the # std of the particle y position. using Statistics: std ## Define observables d_p(phs) = log(sum(sqrt(sum(phs[1].p.pos .- phs[j].p.pos).^2) for j in 2:N)/N) std_p(phs) = std(p.p.pos[1] for p in phs) t = Observable([0.0]) # Time axis d = Observable([d_p(phs[])]) s = Observable([std_p(phs[])]) ## Trigger observable updates on(phs) do phs push!(t[], phs[1].T) push!(d[], d_p(phs)) push!(s[], std_p(phs)) notify.((t, d)) autolimits!(axd); autolimits!(axs) end ## Plot observables lines!(axd, t, d; color = Cycled(1)) lines!(axs, t, s; color = Cycled(2)) nothing # The figure hasn't changed yet of course, but after we step the animation, it does: dt = 0.001 for j in 1:1000 for i in 1:9 bdplot_animstep!(phs, chs, bd, dt; update = false) end bdplot_animstep!(phs, chs, bd, dt; update = true) end fig # Of course, you can produce a video of this using Makie's `record` function. # ## Video output # ```@docs # bdplot_video # ``` # Here is an example that changes plotting defaults to make an animation in # the style of [3Blue1Brown](https://www.3blue1brown.com/). # %% #src using DynamicalBilliards, CairoMakie BLUE = "#7BC3DC" BROWN = "#8D6238" colors = [BLUE, BROWN] ## Overwrite default color of obstacles to white (to fit with black background) bd = billiard_stadium(1, 1) ps = particlebeam(1.0, 0.6, 0, 200, 0.01) ## Notice that keyword `color = :white` is propagated to billiard plot bdplot_video( "3b1billiard.mp4", bd, ps; frames = 120, colors, dt = 0.01, tail_length = 100, figure = (backgroundcolor = :black,), framerate = 10, color = :white, ) # ```@raw html # <video width="auto" controls autoplay loop> # <source src="../3b1billiard.mp4" type="video/mp4"> # </video> # ```
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
288
module DynamicalBilliardsVisualizations using DynamicalBilliards, Makie import DynamicalBilliards: bdplot, bdplot!, bdplot_animstep!, bdplot_interactive, bdplot_video, bdplot_boundarymap include("defs_plotting.jl") include("defs_animating.jl") include("premade_anim_functions.jl") end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
7223
using DataStructures: CircularBuffer ###################################################################################### # Struct definitions ###################################################################################### mutable struct ParticleHelper{P, T<:Real} p::P # particle t::T # time ellapsed (resets at each collision) T::T # total time ellapsed (only resets when resetting particles) tail::CircularBuffer{Point2f} # particle positions in last recorded steps end Base.show(io::IO, ::Type{ParticleHelper}) = print(io, """ Particle helper struct. Fields: p::P # particle t::T # time ellapsed (resets at each collision) T::T # total time ellapsed (only resets when resetting particles) tail::CircularBuffer{Point2f} # particle positions in last recorded steps """) mutable struct CollisionHelper{T<:Real} i::Int # index of obstacle to be collided with tmin::T # time to next collision n::Int # total collisions so far ξsinθ::SVector{2, T} # boundary map point end Base.show(io::IO, ::Type{CollisionHelper}) = print(io, """ Collision helper struct. Fields: i::Int # index of obstacle to be collided with tmin::T # time to next collision n::Int # total collisions so far ξsinθ::SVector{2, T} # boundary map point """) function helpers_from_particle(p::AbstractParticle, bd::Billiard, L, intervals) T = eltype(p.pos) i, tmin, _ = DynamicalBilliards.next_collision(p, bd) # Do intervals always on first step, doesn't cost much... p2 = copy(p) DynamicalBilliards.propagate!(p2, tmin) ξ, sinφ = DynamicalBilliards.to_bcoords(p2.pos, p2.vel, bd[i]) ξsin = SVector(ξ, sinφ) tail = CircularBuffer{Point2f}(L) fill!(tail, Point2f(p.pos)) return ParticleHelper{typeof(p), T}(p, 0, 0, tail), CollisionHelper{T}(i, tmin, 0, ξsin) end function helpers_from_particles(ps::Vector{P}, bd::Billiard, L) where {P<:AbstractParticle} intervals = DynamicalBilliards.arcintervals(bd) T = eltype(ps[1]) phs = ParticleHelper{P, T}[] chs = CollisionHelper{T}[] for i in 1:length(ps) ph, ch = helpers_from_particle(ps[i], bd, L, intervals) push!(phs, ph); push!(chs, ch) end return phs, chs end ###################################################################################### # Stepping functions ###################################################################################### function bdplot_animstep!(phs, chs, bd, dt; update = false, intervals = nothing) phs_val = phs[]; chs_val = chs[] N = length(phs_val) any_collided = false for i in 1:N collided = bdplot_animstep!(phs_val[i], chs_val[i], bd, dt, intervals) any_collided = collided || any_collided end any_collided && notify(chs) update && notify(phs) return end function bdplot_animstep!(ph::ParticleHelper, ch::CollisionHelper, bd, dt, intervals) collided = false if ph.t + dt - ch.tmin > 0 # We reach the collision point within the `dt` window, so we need to # call the "bounce" logic rt = ch.tmin - ph.t # remaining time to collision billiards_animbounce!(ph, ch, bd, rt, intervals) dt = dt - rt # remaining dt to propagate for collided = true end DynamicalBilliards.propagate!(ph.p, dt) ph.t += dt ph.T += dt push!(ph.tail, ph.p.pos) return collided end function billiards_animbounce!(ph::ParticleHelper, ch::CollisionHelper, bd, rt, intervals) # Bring to collision and resolve it: DynamicalBilliards.propagate!(ph.p, rt) DynamicalBilliards._correct_pos!(ph.p, bd[ch.i]) DynamicalBilliards.resolvecollision!(ph.p, bd[ch.i]) DynamicalBilliards.ismagnetic(ph.p) && (ph.p.center = DynamicalBilliards.find_cyclotron(ph.p)) # Update boundary map point if necessary if !isnothing(intervals) ξ, sθ = DynamicalBilliards.to_bcoords(ph.p.pos, ph.p.vel, bd[ch.i]) ξ += intervals[ch.i] ch.ξsinθ = SVector(ξ, sθ) end # Update all remaining counters i, tmin, = DynamicalBilliards.next_collision(ph.p, bd) ch.i = i ch.tmin = tmin ch.n += 1 ph.t = 0 ph.T += rt # Also add the collision point to the tail for continuity push!(ph.tail, ph.p.pos) return end ###################################################################################### # Initialization of observables and their plots ###################################################################################### function bdplot_plotting_init!(ax::Axis, bd::Billiard, ps::Vector{<:AbstractParticle}; tail_length = 1000, colors = JULIADYNAMICS_CMAP, fade = true, tailwidth = 1, plot_particles = true, particle_size = 5, # size of marker for scatter plot of particle balls velocity_size = 0.05, # size of multiplying the quiver bmap_size = 4, α = 0.9, bmax = nothing, kwargs..., ) bdplot!(ax, bd; kwargs...) N = length(ps) cs = if !(colors isa Vector) || length(colors) ≠ N colors_from_map(colors, N, α) else to_color.(colors) end # Instantiate the helper observables phs_vals, chs_vals = helpers_from_particles(ps, bd, tail_length) phs = Observable(phs_vals); chs = Observable(chs_vals) ###################################################################################### # Initialize plot elements and link them via Observable pipeline # Tail circular data: tails = [Observable(p.tail) for p in phs[]] # Plot tails for i in 1:N x = to_color(cs[i]) if fade x = [RGBAf(x.r, x.g, x.b, i/tail_length) for i in 1:tail_length] end lines!(ax, tails[i]; color = x, linewidth = tailwidth) end # Trigger tail updates (we need `on`, can't use `lift`, coz of `push!` into buffer) on(phs) do phs for i in 1:N tails[i][] = phs[i].tail notify(tails[i]) end end # Particles and their quiver if plot_particles # plot ball and arrow as a particle balls = lift(phs -> [Point2f(ph.p.pos) for ph in phs], phs) vels = lift(phs -> [Point2f(velocity_size*ph.p.vel) for ph in phs], phs) scatter!( ax, balls; color = darken_color.(cs), markersize = particle_size, strokewidth = 0.0, ) arrows!( ax, balls, vels; arrowcolor = darken_color.(cs), linecolor = darken_color.(cs), normalize = false, # arrowsize = particle_size*vr/3, linewidth = 2, ) end # Boundary map if !isnothing(bmax) bmap_points = [Observable([Point2f(c.ξsinθ)]) for c in chs[]] for i in 1:N scatter!(bmax, bmap_points[i]; color = cs[i], markersize = bmap_size) end on(chs) do chs for i in 1:N push!(bmap_points[i][], Point2f(chs[i].ξsinθ)) notify(bmap_points[i]) end end else bmap_points = nothing end return phs, chs, bmap_points end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
10189
###################################################################################### # Constants and API ###################################################################################### SVector = DynamicalBilliards.SVector Obstacle = DynamicalBilliards.Obstacle Billiard = DynamicalBilliards.Billiard AbstractParticle = DynamicalBilliards.AbstractParticle using Makie: RGBf, RGBAf JULIADYNAMICS_COLORS = [ "#7143E0", "#191E44", "#0A9A84", "#AF9327", "#791457", "#6C768C", ] JULIADYNAMICS_CMAP = reverse(cgrad(:dense)[20:end]) function colors_from_map(cmap, N, α = 1) return collect(cgrad(cmap, N; categorical = true, alpha = α)) end """ randomcolor(args...) = RGBAf(0.9 .* (rand(), rand(), rand())..., 0.75) """ randomcolor(args...) = RGBAf(0.9 .* (rand(), rand(), rand())..., 0.75) """ darken_color(c, f = 1.2) Darken given color `c` by a factor `f`. If `f` is less than 1, the color is lightened instead. """ function darken_color(c, f = 1.2) c = to_color(c) return RGBAf(clamp.((c.r/f, c.g/f, c.b/f, c.alpha), 0, 1)...) end obcolor(::Obstacle) = JULIADYNAMICS_COLORS[3] obcolor(::Union{DynamicalBilliards.RandomWall, DynamicalBilliards.RandomDisk}) = JULIADYNAMICS_COLORS[2] obcolor(::Union{DynamicalBilliards.SplitterWall, DynamicalBilliards.Antidot, DynamicalBilliards.Ellipse}) = JULIADYNAMICS_COLORS[1] obcolor(::DynamicalBilliards.PeriodicWall) = JULIADYNAMICS_COLORS[4] obfill(o::DynamicalBilliards.Obstacle) = (obcolor(o), 0.2) obls(::Obstacle) = nothing obls(::Union{DynamicalBilliards.SplitterWall, DynamicalBilliards.Antidot, DynamicalBilliards.Ellipse}) = :dot obls(::Union{DynamicalBilliards.RandomWall, DynamicalBilliards.RandomDisk}) = [0.5, 1.0, 1.5, 2.5] oblw(::Obstacle) = 2.0 function bdplot(args...; kwargs...) fig = Figure() ax = Axis(fig[1,1]; aspect = DataAspect()) bdplot!(ax, args...; kwargs...) return fig, ax end ###################################################################################### # Obstacles, particles ###################################################################################### function bdplot!(ax, o::T; kwargs...) where {T} error("Object of type $T does not have a plotting definition yet.") end function bdplot!(ax, o::DynamicalBilliards.Semicircle; kwargs...) θ1 = atan(o.facedir[2], o.facedir[1]) + π/2 # start of semicircle θ2 = θ1 + π θ = range(θ1, θ2; length = 200) p = [Point2f(cos(t)*o.r + o.c[1], sin(t)*o.r + o.c[2]) for t in θ] lines!(ax, p; color = obcolor(o), linewidth = oblw(o), linestyle = obls(o), kwargs...) return end function bdplot!(ax, w::DynamicalBilliards.Wall; kwargs...) lines!(ax, Float32[w.sp[1],w.ep[1]], Float32[w.sp[2],w.ep[2]]; color = obcolor(w), linewidth = oblw(w), linestyle = obls(w), kwargs...) return end function bdplot!(ax, o::DynamicalBilliards.Circular; kwargs...) θ = range(0, 2π; length = 1000) p = [Point2f(cos(t)*o.r + o.c[1], sin(t)*o.r + o.c[2]) for t in θ] poly!(ax, p; color = obfill(o), strokecolor = obcolor(o), strokewidth = oblw(o), linestyle = obls(o), kwargs...) return end function bdplot!(ax, o::DynamicalBilliards.Ellipse; kwargs...) θ = range(0, 2π; length = 1000) p = [Point2f(cos(t)*o.a + o.c[1], sin(t)*o.b + o.c[2]) for t in θ] poly!(ax, p; color = obfill(o), strokecolor = obcolor(o), strokewidth = oblw(o), linestyle = obls(o), kwargs...) return end bdplot!(ax, p::AbstractParticle; kwargs...) = bdplot!(ax, [p]; kwargs...) function bdplot!(ax, ps::Vector{<:AbstractParticle}; use_cell = true, velocity_size = 0.05, particle_size = 5, α = 0.9, colors = JULIADYNAMICS_CMAP, kwargs... ) N = length(ps) cs = if !(colors isa Vector) || length(colors) ≠ N colors_from_map(colors, N, α) else to_color.(colors) end balls = [Point2f(use_cell ? p.pos + p.current_cell : p.pos) for p in ps] vels = [Point2f(velocity_size*p.vel) for p in ps] scatter!( ax, balls; color = cs, markersize = particle_size, strokewidth = 0.0, kwargs... ) arrows!( ax, balls, vels; arrowcolor = darken_color.(cs), linecolor = darken_color.(cs), normalize = false, # arrowsize = particle_size*vr/3, linewidth = 2, ) return end ###################################################################################### # Billiard ###################################################################################### function bdplot!(ax, bd::Billiard; clean = true, kwargs...) for obst in bd; bdplot!(ax, obst; kwargs...); end if clean xmin, ymin, xmax, ymax = DynamicalBilliards.cellsize(bd) dx = xmax - xmin; dy = ymax - ymin if !isinf(xmin) && !isinf(xmax) Makie.xlims!(ax, xmin - 0.01dx, xmax + 0.01dx) end if !isinf(ymin) && !isinf(ymax) Makie.ylims!(ax, ymin - 0.01dy, ymax + 0.01dy) end remove_axis!(ax) ax.aspect = DataAspect() end return end function bdplot!(ax, bd::Billiard, xmin::Real, xmax, ymin, ymax; clean=false, kwargs...) n = count(x -> typeof(x) <: DynamicalBilliards.PeriodicWall, bd) if n == 6 plot_periodic_hexagon!(ax, bd, xmin, xmax, ymin, ymax; kwargs...) elseif n ∈ (2, 4) plot_periodic_rectangle!(ax, bd, xmin, xmax, ymin, ymax; kwargs...) else error("Periodic billiards can only have 2, 4 or 6 periodic walls.") end dx = xmax - xmin; dy = ymax - ymin Makie.xlims!(ax, xmin - 0.01dx, xmax + 0.01dx) Makie.ylims!(ax, ymin - 0.01dy, ymax + 0.01dy) if clean remove_axis!(ax) ax.aspect = DataAspect() end return ax end function plot_periodic_rectangle!(ax, bd, xmin, xmax, ymin, ymax; kwargs...) # Cell limits: cellxmin, cellymin, cellxmax, cellymax = DynamicalBilliards.cellsize(bd) dcx = cellxmax - cellxmin dcy = cellymax - cellymin # Find displacement vectors dx = (floor((xmin - cellxmin)/dcx):1:ceil((xmax - cellxmax)/dcx)) * dcx dy = (floor((ymin - cellymin)/dcy):1:ceil((ymax - cellymax)/dcy)) * dcy # Plot displaced Obstacles toplot = nonperiodic(bd) for x in dx for y in dy disp = SVector(x,y) for obst in toplot bdplot!(ax, DynamicalBilliards.translate(obst, disp); kwargs...) end end end end function plot_periodic_hexagon!(ax, bd, xmin, xmax, ymin, ymax; kwargs...) # find first periodic wall to establish scale v = 1 while !(typeof(bd[v]) <: DynamicalBilliards.PeriodicWall); v += 1; end space = sqrt(sum(bd[v].sp - bd[v].ep).^2)*√3 # norm(bd[v].sp - bd[v].ep) basis_a = space*SVector(0.0, 1.0) basis_b = space*SVector(√3/2, 1/2) basis_c = space*SVector(√3, 0.0) # Cell limits: cellxmin, cellymin, cellxmax, cellymax = DynamicalBilliards.cellsize(bd) dcx = cellxmax - cellxmin dcy = cellymax - cellymin jmin = Int((ymin - cellymin - dcy/2)÷space) - 1 jmax = Int((ymax - cellymax + dcy/2)÷space) + 1 imin = Int((xmin - cellxmin - dcx/2)÷(√3*space)) - 1 imax = Int((xmax - cellxmax + dcx/2)÷(√3*space)) + 1 obstacles = nonperiodic(bd) for d in obstacles for j ∈ jmin:jmax for i ∈ imin:imax bdplot!(ax, DynamicalBilliards.translate(d, j*basis_a + i*basis_c); kwargs...) bdplot!(ax, DynamicalBilliards.translate(d, j*basis_a + i*basis_c + basis_b); kwargs...) end end end end function nonperiodic(bd::Billiard) toplot = Obstacle{eltype(bd)}[] for obst in bd typeof(obst) <: DynamicalBilliards.PeriodicWall && continue push!(toplot, obst) end return toplot end function remove_axis!(ax) ax.bottomspinevisible = false ax.leftspinevisible = false ax.topspinevisible = false ax.rightspinevisible = false ax.xgridvisible = false ax.ygridvisible = false ax.xticksvisible = false ax.yticksvisible = false ax.xticklabelsvisible = false ax.yticklabelsvisible = false end ###################################################################################### # Boundary map ###################################################################################### function bdplot_boundarymap(bmap, intervals; color = JULIADYNAMICS_COLORS[1], figkwargs = NamedTuple(), kwargs...) fig = Figure(;figkwargs...) bmapax = obstacle_axis!(fig[1,1], intervals) if typeof(bmap) <: Vector{<:SVector} c = typeof(color) <: AbstractVector ? color[1] : color scatter!(bmapax, bmap; color = c, markersize = 4, kwargs...) else for (i, bmapp) in enumerate(bmap) c = typeof(color) <: AbstractVector ? color[i] : color scatter!(bmapax, bmapp; color = c, markersize = 3, kwargs...) end end return fig, bmapax end function obstacle_axis!(figlocation, intervals) bmapax = Axis(figlocation; alignmode = Mixed(bottom = 0)) bmapax.xlabel = "arclength, ξ" bmapax.ylabel = "sine of normal angle, sin(θ)" bmapax.targetlimits[] = BBox(intervals[1], intervals[end], -1, 1) ticklabels = ["$(round(ξ, sigdigits=4))" for ξ in intervals[2:end-1]] bmapax.xticks = (Float32[intervals[2:end-1]...], ticklabels) for (i, ξ) in enumerate(intervals[2:end-1]) lines!(bmapax, [Point2f(ξ, -1), Point2f(ξ, 1)]; linestyle = :dash, color = :black) end obstacle_ticklabels = String[] obstacle_ticks = Float32[] for (i, ξ) in enumerate(intervals[1:end-1]) push!(obstacle_ticks, ξ + (intervals[i+1] - ξ)/2) push!(obstacle_ticklabels, string(i)) end ylims!(bmapax, -1, 1) xlims!(bmapax, 0, intervals[end]) obax = Axis(figlocation; alignmode = Inside()) Makie.deactivate_interaction!(obax, :rectanglezoom) obax.xticks = (obstacle_ticks, obstacle_ticklabels) obax.xaxisposition = :top obax.xticklabelalign = (:center, :bottom) obax.xlabel = "obstacle index" obax.xgridvisible = false hideydecorations!(obax) hidespines!(obax) xlims!(obax, 0, intervals[end]) return bmapax end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
4491
###################################################################################### # Exported functions ###################################################################################### function bdplot_interactive(bd::Billiard, ps::Vector{<:AbstractParticle}; playback_controls = true, dt = 0.001, plot_bmap = false, size = plot_bmap ? (1200, 600) : (800, 600), figure = NamedTuple(), kwargs... ) fig = Figure(; size, figure...) primary_layout = fig[:,1] = GridLayout() ax = Axis(primary_layout[1,1]; backgroundcolor = RGBAf(1,1,1,0)) if plot_bmap intervals = DynamicalBilliards.arcintervals(bd) bmax = obstacle_axis!(fig[:,2], intervals) else bmax = nothing intervals = nothing end phs, chs, bmap_points = bdplot_plotting_init!(ax, bd, ps; bmax, kwargs...) ps0 = Observable(deepcopy(ps)) if playback_controls control_observables = bdplot_animation_controls(fig, primary_layout) bdplot_control_actions!( fig, control_observables, phs, chs, bd, dt, ps0, intervals, bmap_points ) end return fig, phs, chs end function bdplot_video(file, bd::Billiard, ps::Vector{<:AbstractParticle}; dt = 0.001, frames = 1000, steps = 10, plot_bmap = false, framerate = 60, kwargs... ) fig, phs, chs = bdplot_interactive(bd, ps; playback_controls = false, plot_bmap, kwargs...) intervals = !plot_bmap ? nothing : DynamicalBilliards.arcintervals(bd) record(fig, file, 1:frames; framerate) do j for _ in 1:steps-1 bdplot_animstep!(phs, chs, bd, dt; update = false, intervals) end bdplot_animstep!(phs, chs, bd, dt; update = true, intervals) end return end ###################################################################################### # Internal interaction code ###################################################################################### function bdplot_animation_controls(fig, primary_layout) control_layout = primary_layout[2,:] = GridLayout(tellheight = true, tellwidth = false) height = 30 resetbutton = Button(control_layout[1,1]; label = "reset", buttoncolor = RGBf(0.8, 0.8, 0.8), height, width = 70 ) runbutton = Button(control_layout[1,2]; label = "run", buttoncolor = RGBf(0.8, 0.8, 0.8), height, width = 70 ) slidergrid = SliderGrid(control_layout[1,3], (label = "steps", range = 1:100, startvalue = 1, height) ) isrunning = Observable(false) rowsize!(primary_layout, 2, height) return isrunning, resetbutton.clicks, runbutton.clicks, slidergrid.sliders[1].value end function bdplot_control_actions!( fig, control_observables, phs, chs, bd, dt, ps0, intervals, bmap_points ) isrunning, resetbutton, runbutton, stepslider = control_observables on(runbutton) do clicks; isrunning[] = !isrunning[]; end on(runbutton) do clicks @async while isrunning[] # without `@async`, Julia "freezes" in this loop # for jjj in 1:1000 n = stepslider[] for _ in 1:n-1 bdplot_animstep!(phs, chs, bd, dt; update = false, intervals) end bdplot_animstep!(phs, chs, bd, dt; update = true, intervals) isopen(fig.scene) || break # crucial, ensures computations stop if closed window. yield() end end # Whenever initial particles are changed, trigger reset update on(ps0) do ps phs_vals, chs_vals = helpers_from_particles(deepcopy(ps), bd, length(phs[][1].tail)) phs[] = phs_vals chs[] = chs_vals if !isnothing(bmap_points) for (bmp, c) in zip(bmap_points, chs[]) bmp[] = [Point2f(c.ξsinθ)] end end end on(resetbutton) do clicks notify(ps0) # simply trigger initial particles change end # Selecting a line and making new particles ax = content(fig[1,1][1,1]) MakieLayout.deactivate_interaction!(ax, :rectanglezoom) sline = select_line(ax.scene; color = JULIADYNAMICS_COLORS[1]) dx = 0.001 # TODO: make this a keyword ω0 = DynamicalBilliards.ismagnetic(ps0[][1]) ? ps0[][1].ω : nothing N = length(ps0[]) on(sline) do val pos = val[1] dir = val[2] - val[1] φ = atan(dir[2], dir[1]) ps0[] = DynamicalBilliards.particlebeam(pos..., φ, N, dx, ω0, eltype(bd)) end end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
2154
__precompile__() """ A Julia package for dynamical billiard systems in two dimensions. It provides a flexible, easy-to-use, and intuitive framework for fast implementation of billiards of arbitrary construction. """ module DynamicalBilliards using LinearAlgebra using StaticArrays using Elliptic import Base: show, eltype, getindex const SV = SVector{2} export SVector cossin(a) = ((x, y) = sincos(a); (y, x)) ########################################## # Core # ########################################## include("billiards/particles.jl") include("billiards/obstacles.jl") include("billiards/billiardtable.jl") include("billiards/standard_billiards.jl") include("timeevolution/collisions.jl") include("timeevolution/propagation.jl") include("timeevolution/timeseries.jl") include("timeevolution/highleveltimes.jl") include("plotting_api.jl") ########################################## # Advanced # ########################################## include("boundary/boundarymap.jl") include("boundary/phasespacetools.jl") include("poincare.jl") include("lyapunov_spectrum.jl") include("mushroomtools.jl") export MushroomTools include("raysplitting.jl") include("parallel.jl") include("testing.jl") ################### # Update messages # ################### using Scratch display_update = true version_number = "4.1" update_name = "update_v$(version_number)" function __init__() if display_update # Get scratch space for this package versions_dir = @get_scratch!("versions") if !isfile(joinpath(versions_dir, update_name)) printstyled( stdout, """ \nUpdate message: DynamicalBilliards v$(version_number) Plotting & animating is now inside DynamicalBilliards.jl again, utilizing Julia Package Extension systems. This means that Julia versions 1.9+ are supported only. """; color = :light_magenta, ) touch(joinpath(versions_dir, update_name)) end end end end#module
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
13086
export lyapunovspectrum!, lyapunovspectrum export perturbationgrowth!, perturbationgrowth, perturbationevolution const δqind = SV{Int}(1,2) const δpind = SV{Int}(3,4) @inline curvature(::Semicircle{T}) where {T} = -one(T) @inline curvature(::Disk{T}) where {T} = one(T) ################################################################################ ## SPECULAR (LINEAR) ################################################################################ #=""" specular!(p::AbstractParticle, o::Obstacle, offset::MArray) Perform specular reflection based on the normal vector of the Obstacle. The function updates the position and velocity of the particle together with the components of 4 offset vectors stored in the matrix `offset` as columns. """=# function specular!(p::Particle{T}, o::Circular{T}, offset::Vector{SVector{4, T}}) where {T<:AbstractFloat} n = normalvec(o, p.pos) ti = SV{T}(-p.vel[2],p.vel[1]) cosa = -dot(n, p.vel) p.vel = p.vel + 2.0*cosa*n tf = SV{T}(-p.vel[2], p.vel[1]) @inbounds for k in eachindex(offset) δqprev = offset[k][δqind] δpprev = offset[k][δpind] # Formulas from Dellago, Posch and Hoover, PRE 53, 2, 1996: 1485-1501 (eq. 27) # with norm(p) = 1 δq = δqprev - 2*dot(δqprev,n)*n δp = δpprev - 2*dot(δpprev,n)*n - curvature(o)*2/o.r*dot(δqprev,ti)/cosa*tf ### offset[k] = vcat(δq, δp) end end function specular!(p::Particle{T}, o::Union{InfiniteWall{T},FiniteWall{T}}, offset::Vector{SVector{4, T}}) where {T<:AbstractFloat} n = normalvec(o, p.pos) specular!(p, o) for k in eachindex(offset) δqprev = offset[k][δqind] δpprev = offset[k][δpind] # Formulas from Dellago, Posch and Hoover, PRE 53, 2, 1996: 1485-1501 (eq. 20) δq = δqprev - 2.0*dot(δqprev,n)*n δp = δpprev - 2.0*dot(δpprev,n)*n ### offset[k] = vcat(δq, δp) end end ################################################################################ ## SPECULAR (MAGNETIC) ################################################################################ function specular!(p::MagneticParticle{T}, o::Circular{T}, offset::Vector{SVector{4, T}}) where {T<:AbstractFloat} n = normalvec(o, p.pos) cosa = -dot(n, p.vel) Rn = SV{T}(-n[2], n[1]) ti = SV{T}(-p.vel[2],p.vel[1]) # magterm = ω*δτ_c*(BR-RB)*p_i / δqprev_normal # i.e. everything that can be calculated without using the previous offset vector magterm = -2*p.omega*((dot(p.vel, Rn)/(-cosa))*n + Rn) #actual specular reflection should not occur before magterm is computed p.vel = p.vel + 2*cosa*n tf = SV{T}(-p.vel[2], p.vel[1]) for k in eachindex(offset) δqprev = offset[k][δqind] δpprev = offset[k][δpind] δqprev_normal = dot(δqprev, n) # Formulas derived analogously to Dellago et al., PRE 53, 2, 1996: 1485-1501 δq = δqprev - 2*δqprev_normal*n δp = δpprev - 2*dot(δpprev,n)*n - curvature(o)* 2/o.r * dot(δqprev,ti)/cosa*tf + magterm*δqprev_normal ### offset[k] = vcat(δq, δp) end end function specular!(p::MagneticParticle{T}, o::Union{InfiniteWall{T},FiniteWall{T}}, offset::Vector{SVector{4, T}}) where {T<:AbstractFloat} n = normalvec(o, p.pos) cosa = -dot(n, p.vel) Rn = SV{T}(-n[2], n[1]) # magterm = ω*δτ_c*(BR-RB)*p_i / δqprev_normal # i.e. everything that can be calculated without using the previous offset vector magterm = -2.0*p.omega*((dot(p.vel, Rn)/(-cosa))*n + Rn) #actual specular reflection should not occur before magterm is calculated p.vel = p.vel + 2*cosa*n for k in eachindex(offset) δqprev = offset[k][δqind] δpprev = offset[k][δpind] δqprev_normal = dot(δqprev, n) # Formulas derived analogously to Dellago et al., PRE 53, 2, 1996: 1485-1501 δq = δqprev - 2.0*δqprev_normal*n δp = δpprev - 2.0*dot(δpprev,n)*n + magterm*δqprev_normal ### offset[k] = vcat(δq, δp) end end ################################################################################ ## RESOLVECOLLISON ################################################################################ #=""" resolvecollision!(p::AbstractParticle, o::Union{Disk, InfiniteWall}, offset::MArray) Resolve the collision between particle `p` and obstacle `o` of type *Circular*, updating the components of the offset vectors stored in the matrix `offset` as columns. """=# resolvecollision!(p::Particle{T}, o::Obstacle{T}, offset::Vector{SVector{4, T}}) where {T} = specular!(p, o, offset) resolvecollision!(p::Particle{T}, o::PeriodicWall{T}, offset::Vector{SVector{4, T}}) where {T} = resolvecollision!(p, o) function resolvecollision!(p::MagneticParticle{T}, o::Obstacle{T}, offset::Vector{SVector{4, T}}) where {T} specular!(p, o, offset) p.center = find_cyclotron(p) return end # this method only exists to avoid ambiguity for MagneticParticles colliding with # periodic walls. resolvecollision!(p::MagneticParticle{T}, o::PeriodicWall{T}, offset::Vector{SVector{4, T}}) where {T} = resolvecollision!(p, o) ################################################################################ ## OFFSET PROPAGATION ################################################################################ """ propagate_offset!(offset::MArray{Tuple{4,4},T}, p::AbstractParticle) Computes the linearized evolution of the offset vectors during propagation for a time interval `t` """ function propagate_offset!(offset::Vector{SVector{4, T}}, t::T, #linear case p::Particle{T}) where T for k in eachindex(offset) δΓ = offset[k] offset[k] = SVector{4,T}(δΓ[1] + t*δΓ[3], δΓ[2] + t*δΓ[4], δΓ[3], δΓ[4]) end end #magnetic function propagate_offset!(offset::Vector{SVector{4, T}}, t::T, p::MagneticParticle{T}) where T ω = p.omega sω, cω = sincos(ω*t) for k in eachindex(offset) δΓ = offset[k] offset[k] = SVector{4,T}(δΓ[1] + sω/ω*δΓ[3] + (cω - 1)/ω*δΓ[4], δΓ[2] + (1 - cω)/ω*δΓ[3] + sω/ω*δΓ[4], cω*δΓ[3] - sω*δΓ[4], sω*δΓ[3] + cω*δΓ[4]) end end ################################################################################ ## PROPAGATION & RELOCATION ################################################################################ #=""" propagate!(p::AbstractParticle{T}, newpos::SV{T}, t::T, offset::MArray{Tuple{4,4},T}) Propagate the particle `p` for given time `t`, changing appropriately the the `p.pos` and `p.vel` fields together with the components of the offset vectors stored in the `offset` matrix. """=# function propagate!(p::AbstractParticle{T}, newpos::SV{T}, t::T, offset::Vector{SVector{4, T}}) where {T<: AbstractFloat} propagate!(p, newpos, t) propagate_offset!(offset, t, p) return end #=""" relocate(p::AbstractParticle, o::Obstacle, t, cp::SV{T}, offset::MArray) Propagate the particle's position for time `t` (corrected) and update the components of the `offset` matrix. """=# function relocate!(p::AbstractParticle{T}, o::Obstacle{T}, tmin, cp::SV{T}, offset::Vector{SVector{4, T}}) where {T <: AbstractFloat} okay = relocate!(p, o, tmin, cp) propagate_offset!(offset, tmin, p) return okay end ################################################################################ ## HIGH-LEVEL FUNCTION ################################################################################ function lyapunovspectrum!(p::AbstractParticle{T}, bd::Billiard{T}, t; warning::Bool = false) where {T<:AbstractFloat} if t ≤ 0.0 throw(ArgumentError( "`lyapunovspectrum()` cannot evolve backwards in time.")) end # intial offset vectors offset = [SVector{4, T}(1,0,0,0), SVector{4, T}(0,1,0,0), SVector{4, T}(0,0,1,0), SVector{4, T}(0,0,0,1)] λ = zeros(T, 4) timecount = zero(T) count = zero(t) # check for pinning before evolution if ispinned(p, bd) warning && @warn "Pinned particle!" return λ end ismagnetic = typeof(p) <: MagneticParticle while count < t # bouncing i::Int, tmin::T, cp::SV{T} = next_collision(p, bd) relocate!(p, bd[i], tmin, cp, offset) resolvecollision!(p, bd[i], offset) timecount += tmin count += increment_counter(t, tmin) # update cyclotron data ismagnetic && (p.center = find_cyclotron(p)) # QR decomposition to get Lyapunov spectrum Q, R = qr(hcat(offset[1], offset[2], offset[3], offset[4])) offset[1], offset[2], offset[3], offset[4] = Q[:, 1], Q[:, 2], Q[:, 3], Q[:, 4] for i ∈ 1:4 λ[i] += log(abs(R[i,i])) end end#time loop return λ./timecount end """ lyapunovspectrum([p::AbstractParticle,] bd::Billiard, t) Returns the finite time lyapunov exponents (averaged over time `t`) for a given particle in a billiard table using the method outlined in [1]. `t` can be either `Float` or `Int`, meaning total time or total amount of collisions. Returns zeros for pinned particles. If a particle is not given, a random one is picked through [`randominside`](@ref). See [`parallelize`](@ref) for a parallelized version. [1] : Ch. Dellago *et al*, [Phys. Rev. E **53** (1996)](http://link.aps.org/doi/10.1103/PhysRevE.53.1485) """ lyapunovspectrum(p::AbstractParticle, args...) = lyapunovspectrum!(copy(p), args...) lyapunovspectrum(bd::Billiard, args...) = lyapunovspectrum!(randominside(bd), bd, args...) ################################################################################ ## Raw perturbation growth ################################################################################ function perturbationgrowth!(p::AbstractParticle{T}, bd::Billiard{T}, t) where {T<:AbstractFloat} offset = [SVector{4, T}(1,1,1,1)] count = zero(t) timecount = zero(T) Δ = Vector{SVector{4, T}}() # perturbation vectors tim = T[] # sample times obst = Int[] # obstacle indices # check for pinning before evolution if ispinned(p, bd) return tim, Δ, obst end ismagnetic = typeof(p) <: MagneticParticle while count < t off = offset[1] # bounce i::Int, tmin::T, cp::SV{T} = next_collision(p, bd) relocate!(p, bd[i], tmin, cp, offset) timecount += tmin # push perturbations before collision push!(tim, timecount) push!(obst, i) # push after propagation evolution push!(Δ, offset[1] ./ off) off = offset[1] resolvecollision!(p, bd[i], offset) # push perturbations after collision push!(tim, timecount) push!(obst, i) push!(Δ, offset[1] ./ off) ismagnetic && (p.center = find_cyclotron(p)) # normalize perturbation vector offset[1] = offset[1] ./ norm(offset[1]) count += increment_counter(t, tmin) end#time loop return tim, Δ, obst end """ perturbationgrowth([p,] bd, t) -> ts, Rs, is Calculate the evolution of the perturbation vector `Δ` along the trajectory of `p` in `bd` for total time `t`. `Δ` is initialised as `[1,1,1,1]`. If a particle is not given, a random one is picked through [`randominside`](@ref). Returns empty lists for pinned particles. ## Description This function *safely* computes the time evolution of a perturbation vector using the linearized dynamics of the system, as outlined by [1]. Because the dynamics are linear, we can safely re-normalize the perturbation vector after every collision (otherwise the perturbations grow to infinity). Immediately before *and after* every collison, this function computes * the current time. * the element-wise ratio of Δ with its previous value * the obstacle index of the current obstacle and returns these in three vectors `ts, Rs, is`. To obtain the *actual* evolution of the perturbation vector you can use the function `perturbationevolution(Rs)` which simply does ```julia Δ = Vector{SVector{4,Float64}}(undef, length(R)) Δ[1] = R[1] for i in 2:length(R) Δ[i] = R[i] .* Δ[i-1] end ``` [1] : Ch. Dellago *et al*, [Phys. Rev. E **53** (1996)](http://link.aps.org/doi/10.1103/PhysRevE.53.1485) """ perturbationgrowth(p::AbstractParticle, args...) = perturbationgrowth!(copy(p), args...) perturbationgrowth(bd::Billiard, args...) = perturbationgrowth!(randominside(bd), bd, args...) function perturbationevolution(R::Vector{SVector{4, T}}) where T Δ = Vector{SVector{4,T}}(undef, length(R)) Δ[1] = R[1] @inbounds for i in 2:length(R) Δ[i] = R[i] .* Δ[i-1] end return Δ end @deprecate pertubationevolution perturbationevolution
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
5312
""" MushroomTools Module containing many functions helpful in simulating (perfect) mushroom billiards, see [`billiard_mushroom`](@ref). Contains stuff like initializing efficiently regular or chaotic particles and functions that return the corresponding chaotic or regular phase-space volumes or portions. The functions `V_3D_tot` and `V_3D_reg` use equations derived in ref. [1]. Made by Lukas Hupe. ## References [1] A. Barnett & T. Betcke, [Chaos **17**, 043125 (2007)](https://doi.org/10.1063/1.2816946). """ module MushroomTools using DynamicalBilliards using DynamicalBilliards: SV, cossin using LinearAlgebra #=""" is_regular(p::Particle, o::Semicircle, w) checks whether the particle `p` is on an integrable orbit in a mushroom billiard with cap `o` and stem width `w` """=# function is_regular(p::Particle{T}, l, w, r) where {T} δ = SV{T}(0.0, l) - p.pos vperp = [-p.vel[2],p.vel[1]] if norm(δ) > r #debug && println("not inside circle: pos = $(p.pos)") return false elseif p.pos[2] < l #debug && println("wrong half of circle") return false elseif abs(dot(vperp, δ)) < w/2 #debug && println("not outside critical radius") return false else #debug && println("Perfectly happy with $(p.pos) and $(p.vel)") return true end end #Formulae from quantum mushroom paper """ V_3D_tot(l,w,r) Return the total phasespace volume (3D) of a [`billiard_mushroom`](@ref) parameterized by `(l,w,r)`. """ V_3D_tot(l,w,r) = 2π*(l*w + (1/2)*π*r^2) V_3D_reg(l,w,r) = 2π*r^2*(acos(w/(2r)) - w/(2r)*sqrt(1 - (w^2)/(4r^2))) V_3D_cha(l,w,r) = V_3D_tot(l,w,r) - V_3D_reg(l,w,r) """ g_r_3D(l, w, r) Return the regular phasespace portion of the full (3D) phase-space of a [`billiard_mushroom`](@ref) with stem length `l`, stem width `w` and cap radious `r`. This result is known analytically, see [`MushroomTools`](@ref) for references. """ g_r_3D(l,w,r) = V_3D_reg(l,w,r)/V_3D_tot(l,w,r) """ g_c_3D(l, w, r) Return the chaotic phasespace portion of the full (3D) phase-space of a [`billiard_mushroom`](@ref) with stem length `l`, stem width `w` and cap radious `r`. This result is known analytically, see [`MushroomTools`](@ref) for references. """ g_c_3D(l,w,r) = 1 - g_r_3D(l,w,r) """ V_2D_tot(l,w,r) Return the total boundary map volume (2D) of a [`billiard_mushroom`](@ref) parameterized by `(l,w,r)`. """ V_2D_tot(l, w, r) = 2(π*r + 2r + 2l) V_2D_reg(l, w, r) = 2π*r*(1 - w/2r) + 2sqrt(4r*r - w*w) -2w*acos(w/2r) V_2D_cha(l,w,r) = V_2D_tot(l,w,r) - V_2D_reg(l,w,r) """ g_r_2D(l, w, r) Return the regular phasespace portion of the boundary map (2D) of a [`billiard_mushroom`](@ref) with stem length `l`, stem width `w` and cap radious `r`. This result is known analytically, see [`MushroomTools`](@ref) for references. """ g_r_2D(l,w,r) = V_2D_reg(l,w,r)/V_2D_tot(l,w,r) """ g_c_2D(l, w, r) Return the chaotic phasespace portion of the boundary map (2D) of a [`billiard_mushroom`](@ref) with stem length `l`, stem width `w` and cap radious `r`. This result is known analytically, see [`MushroomTools`](@ref) for references. """ g_c_2D(l,w,r) = 1 - g_r_2D(l,w,r) #applying Kac's Lemma to the stem τ_r_2D_kac(l,w,r) = (V_2D_tot(l,w,r) - V_2D_reg(l,w,r)) / (2w + 4l) #=""" insidemushroom(pos::StaticVector, l, w, r) Returns `true` if pos is within the mushroom parameterised by `l`, `w` and `r` """=# function insidemushroom(pos::SV{T}, l::T, w::T, r::T) where {T <: AbstractFloat} if pos[2] > 0 if pos[2] <= l if abs(pos[1]) <= w/2 return true end elseif pos[2] <= l + r if pos[1]^2 + (pos[2] - l)^2 <= r^2 return true end end end return false end """ randin_mushroom(l, w, r [, ω]) Generate a random particle within the [`billiard_mushroom`](@ref) parameterised by `l`, `w` and `r`. If `ω` is given the particle is magnetic instead. This function is much more efficient than [`randominside`](@ref). """ function randin_mushroom(l::T = 1.0, w::T = 0.2, r::T = 1.0) where {T <: AbstractFloat} pos, vel = _randin_mushroom(l, w, r) return Particle(pos, vel, zero(SV{T})) end function randin_mushroom(l::T, w::T, r::T, ω::T) where {T <: AbstractFloat} pos, vel = _randin_mushroom(l, w, r) return MagneticParticle(pos, vel, zero(SV{T}), T(ω)) end function _randin_mushroom(l::T = 1.0, w::T = 0.2, r::T = 1.0) where {T <: AbstractFloat} x = (-r, r, 2r) y = (0, l + r, l + r) pos = SV{T}(rand(T)*x[3] + x[1], rand(T)*y[3] + y[1]) while ! insidemushroom(pos, l, w, r) pos = SV{T}(rand(T)*x[3] + x[1], rand(T)*y[3] + y[1]) end φ = T(2π * rand(T)) vel = SV{T}(cossin(φ)...) return pos, vel end """ randomchaotic(l, w, r) Generate a chaotic particle, i.e. not trapped in the cap. """ function randomchaotic(l, w, r) p = randin_mushroom(l, w, r) while is_regular(p, l, w, r) p = randin_mushroom(l, w, r) end return p end """ randomregular(l, w, r) Generate a regular particle (i.e. trapped in the cap). """ function randomregular(l, w, r) p = randin_mushroom(l, w, r) while !is_regular(p, l, w, r) p = randin_mushroom(l, w, r) end return p end end # module
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
2437
using Distributed export parallelize parallelize(f, bd, t, n::Int) = parallelize(f, bd, t, [randominside(bd) for i in 1:n]) parallelize(f, bd, t, n::Int, ω) = parallelize(f, bd, t, [randominside(bd, ω) for i in 1:n]) """ parallelize(f, bd::Billiard, t, particles; partype = :threads) Parallelize function `f` across the available particles. The parallelization type can be `:threads` or `:pmap`, which use threads or a worker pool initialized with `addprocs` _before_ `using DynamicalBilliards`. `particles` can be: * A `Vector` of particles. * An integer `n` optionally followed by an angular velocity `ω`. This uses [`randominside`](@ref). The functions usable here are: * [`meancollisiontime`](@ref) * [`escapetime`](@ref) * [`lyapunovspectrum`](@ref) (returns only the maximal exponents) * [`boundarymap`](@ref) (returns vector of vectors of 2-vectors _and_ `arcintervals`) """ function parallelize(f, bd::Billiard, t, particles::Vector{<:AbstractParticle}; partype = :threads) if partype == :threads return threads_pl(f, bd, t, particles) elseif partype == :pmap return pmap_pl(f, bd, t, particles) end end function threads_pl(f, bd, t, particles) ret = _retinit(f, particles) Threads.@threads for i in 1:length(particles) @inbounds ret[i] = _getval(f, particles[i], bd, t) end return ret end function pmap_pl(f, bd, t, particles) g(p) = _getval(f, p, bd, t) ret = pmap(g, particles) return ret end _retinit(f, p::Vector{<:AbstractParticle{T}}) where {T} = zeros(T, length(p)) _retinit(::typeof(boundarymap), p::Vector{<:AbstractParticle{T}}) where {T} = Vector{Vector{SV{T}}}(undef, length(p)) _getval(f, p, bd, t) = f(p, bd, t) _getval(f::typeof(lyapunovspectrum), p, bd, t) = @inbounds f(p, bd, t)[1] _getval(f::typeof(lyapunovspectrum!), p, bd, t) = @inbounds f(p, bd, t)[1] # Methods for boundary map are trickier because of the weird call signature # and return signature function threads_pl(f::typeof(boundarymap), bd, t, particles) intervals = arcintervals(bd) ret = _retinit(f, particles) Threads.@threads for i in 1:length(particles) @inbounds ret[i] = f(particles[i], bd, t, intervals)[1] end return ret, intervals end function pmap_pl(f::typeof(boundarymap), bd, t, particles) intervals = arcintervals(bd) g(p) = f(p, bd, t, intervals) ret = pmap(g, particles) return ret, intervals end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
6106
export bdplot, bdplot! export bdplot_animstep! export bdplot_interactive export bdplot_video export bdplot_boundarymap """ bdplot(x; kwargs...) → fig, ax bdplot!(ax::Axis, x; kwargs...) Plot an object `x` from `DynamicalBilliards` into a given axis (or a new figure). `x` can be an obstacle, a particle, a vector of particles, or a billiard. bdplot!(ax,::Axis, o::Obstacle; kwargs...) Keywords are propagated to `lines!` or `poly!`. Functions `obfill, obcolor, obls, oblw` (not exported) decide global defaults for linecolor, fillcolor, linestyle, linewidth, when plotting obstacles. bdplot!(ax,::Axis, bd::Billiard; clean = true, kwargs...) If `clean = true`, all axis elements are removed and an equal aspect ratio is establised. Other keywords are propagated to the obstacle plots. bdplot!(ax,::Axis, bd::Billiard, xmin, xmax, ymin, ymax; kwargs...) This call signature plots periodic billiards: it plots `bd` along its periodic vectors so that it fills the total amount of space specified by `xmin, xmax, ymin, ymax`. bdplot!(ax,::Axis, ps::Vector{<:AbstractParticle}; kwargs...) Plot particles as a scatter plot (positions) and a quiver plot (velocities). Keywords `particle_size = 5, velocity_size = 0.05` set the size of plotted particles. Keyword `colors = JULIADYNAMICS_CMAP` decides the color of the particles, and can be either a colormap or a vector of colors with equal length to `ps`. The rest of the keywords are propagated to the scatter plot of the particles. """ function bdplot end """ bdplot!(ax, args...; kwargs...) See [`bdplot`](@ref). """ function bdplot! end """ bdplot_boundarymap(bmap, intervals; figkwargs = NamedTuple(), kwargs...) Plot the output of [`DynamicalBilliards.boundarymap`](@ref) into an axis that correctly displays information about obstacle arclengths. Return `figure, axis`. Also works for the parallelized version of boundary map. ## Keyword Arguments * `figkwargs = NamedTuple()` keywords propagated to `Figure`. * `color` : The color to use for the plotted points. Can be either a single color or a vector of colors of length `length(bmap)`, in order to give each initial condition a different color (for parallelized version). * All other keywords propagated to `scatter!`. """ function bdplot_boundarymap end """ bdplot_interactive(bd::Billiard, ps::Vector{<:AbstractParticle}; kwargs...) Create a new figure with `bd` plotted, and in it initialize various data for animating the evolution of `ps` in `bd`. Return `fig, phs, chs`, where `fig` is a figure instance and `phs, chs` can be used for making custom animations, see below. ## Keywords (interactivity-related) * `playback_controls = true`: If true, add controls that allow live-interaction with the figure, such as pause/play, reset, and creating new particles by clicking and dragging on the billiard plot. ## Keywords (visualization-related) * `dt = 0.001`: The animation always occurs in steps of time `dt`. A slider can decide how many steps `dt` to evolve before updating the plots. * `plot_bmap = false`: If true, add a second plot with the boundary map. * `colors = JULIADYNAMICS_CMAP` : If a symbol (colormap name) each particle gets a color from the map. If Vector of length `N`, each particle gets a color form the vector. If Vector with length < `N`, linear interpolation across contained colors is done. * `tail_length = 1000`: The last `tail_length` positions of each particle are visualized. * `tail_width = 1`: Width of the dtail plot. * `fade = true`: Tail color fades away. * `plot_particles = true`: Besides their tails, also plot the particles as a scatter and quiver plot. * `particle_size = 5`: Marker size for particle scatter plot. * `velocity_size = 0.05`: Multiplication of particle velocity before plotted as quiver. * `bmap_size = 4`: Marker size of boundary map scatter plot. * `figure = NamedTuple()`: Keywords propagated to `Figure` creation. * `kwargs...`: Remaining keywords are propagated to the billiard plotting. ## Custom Animations Two helper structures are defined for each particle: 1. `ParticleHelper`: Contains quantities that are updated each `dt` step: the particle, time elapsed since last collision, total time ellapsed, tail (positions in the last `tail_length` `dt`-sized steps). 2. `CollisionHelper`: Contains quantities that are only updated at collisions: index of obstacle to be collided with, time to next collision, total collisions so far, boundary map point at upcoming collision. These two helpers are necessary to transform the simulation into real-time stepping (1 step = `dt` time), instead of the traditional DynamicalBilliards.jl setup of discrete time stepping (1 step = 1 collision). The returned `phs, chs` are two observables, one having vector of `ParticleHelpers`, the other having vector of `CollisionHelpers`. Every plotted element is lifted from these observables. An exported high-level function `bdplot_animstep!(phs, chs, bd, dt; update, intervals)` progresses the simulation for one `dt` step. Users should be using `bdplot_animstep!` for custom-made animations, examples are shown in the documentation online. The only thing the `update` keyword does is `notify!(phs)`. You can use `false` for it if you want to step for several `dt` steps before updating plot elements. Notice that `chs` is always notified when collisions occur irrespectively of `update`. They keyword `intervals` is `nothing` by default, but if it is `arcintervals(bd)` instead, then the boundary map field of `chs` is also updated at collisions. """ function bdplot_interactive end """ bdplot_video(file::String, bd::Billiard, ps::Vector{<:AbstractParticle}; kwargs...) Create an animation of `ps` evolving in `bd` and save it into `file`. This function shares all visualization-related keywords with [`bdplot_interactive`](@ref). Other keywords are: * `steps = 10`: How many `dt`-steps are taken between producing a new frame. * `frames = 1000`: How many frames to produce in total. * `framerate = 60`. """ function bdplot_video end function bdplot_animstep! end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
3629
export psos """ psos(bd::Billiard, plane::InfiniteWall, t, particles) Compute the Poincaré section of the `particles` with the given `plane`, by evolving each one for time `t` (either integer or float) inside `bd`. The `plane` can be an [`InfiniteWall`](@ref) of *any* orientation, however only crossings of the `plane` such that `dot(velocity, normal) < 0` are allowed, with `normal` the normal unit vector of the `plane`. `particles` can be: * A single particle. * A `Vector` of particles. * An integer `n` optionally followed by an angular velocity `ω`. Return the positions `poss` and velocities `vels` at the instances of crossing the `plane`. If given more than one particle, the result is a vector of vectors of vectors. *Notice* - This function can handle pinned particles. If a pinned particle can intersect with the `plane`, then an intersection is returned. If however it can't then empty vectors are returned. """ function psos( bd::Billiard{T}, plane::InfiniteWall{T}, t, par::AbstractParticle{T}) where {T} p = copy(par) rpos = SV{T}[] rvel = SV{T}[] count = zero(t) periodic = isperiodic(bd) check_for_pinned = typeof(p) <: MagneticParticle check_for_pinned && (cyclotron_time = 2π/abs(p.omega)) t_to_write = zero(T) while count < t # compute collision times i::Int, tmin::T, cp = next_collision(p, bd) tplane, = collision(p, plane) # if tplane is smaller, I intersect the section if tplane ≥ 0.0 && tplane < tmin && tplane != Inf psos_pos, psos_vel = propagate_posvel(p.pos, p, tplane) if dot(psos_vel, plane.normal) < 0 # only write crossings with 1 direction push!(rpos, psos_pos); push!(rvel, psos_vel) end end if check_for_pinned if isperiodic(i, bd) t_to_write += tmin else t_to_write = zero(T) end end tmin == Inf && break # Now "bounce" the particle normally: relocate!(p, bd[i], tmin, cp) resolvecollision!(p, bd[i]) typeof(par) <: MagneticParticle && (p.center = find_cyclotron(p)) if check_for_pinned && t_to_write ≥ cyclotron_time tplane, = collision(p, plane) if tplane == Inf if length(rpos) > 0 return [rpos[1]], [rvel[1]] else return rpos, rvel end else psos_pos, psos_vel = propagate_posvel(p.pos, p, tplane) return [psos_pos], [psos_vel] end end count += increment_counter(t, tmin) end return rpos, rvel end function psos(bd::Billiard{T}, plane::InfiniteWall{T}, t, pars::Vector{<:AbstractParticle{T}}) where {T} retpos = Vector{SV{T}}[] retvel = Vector{SV{T}}[] for p ∈ pars rpos, rvel = psos(bd, plane, t, p) push!(retpos, rpos); push!(retvel, rvel) end return retpos, retvel end psos(bd, plane, t, n::Integer) = psos(bd, plane, t, [randominside(bd) for i=1:n]) psos(bd, plane, t, n::Integer, ω::Real) = psos(bd, plane, t, [randominside(bd, ω) for i=1:n]) propagate_posvel(pos, p::Particle{T}, t) where {T} = (SV{T}(pos[1] + p.vel[1]*t, pos[2] + p.vel[2]*t), p.vel) function propagate_posvel(pos, p::MagneticParticle{T}, t) where {T} ω = p.omega φ0 = atan(p.vel[2], p.vel[1]) s0, c0 = sincos(φ0) sωφ0, cωφ0 = sincos(ω*t + φ0) ppos = SV{T}(sωφ0/ω - s0/ω, -cωφ0/ω + c0/ω) psos_vel = SV{T}(cωφ0, sωφ0) return pos + ppos, psos_vel end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
15210
export isphysical, reset_billiard! export RaySplitter, raysplit_indices export law_of_refraction ##################################################################################### # RaySplitter structures ##################################################################################### """ RaySplitter(idxs, transmission, refraction [, newangular]; affect) Return a `RaySplitter` instance, used to perform raysplitting. `idxs` is a `Vector{Int}` with the indices of the obstacles that this `RaySplitter` corresponds to. `transmission`, `refraction` and `newangular` are **functions**. Let `φ` be the angle of incidence and `ω` be the angular velocity and `pflag` the propagation flag (before transmission). The functions have the following signatures: 1. `transmission(φ, pflag, ω) -> T`, transmission probability. 2. `refraction(φ, pflag, ω) -> θ`, refraction angle. This angle is *relative* to the normal vector. 3. `newangular(ω, pflag) -> newω`, new angular velocity after transmission. The above three functions use the **same convention**: the argument `pflag` is the one the obstacle has **before transmission**. For example, if a particle is outside an [`Antidot`](@ref) (with `pflag = true` here) and is transmitted inside the `Antidot` (`pflag` becomes `false` here), then all three functions will be given their second argument (the Boolean one) as `true`! `affect` is a function, and denotes which obstacles of the billiard are affected when transmission occurs at obstacle `i` (for which obstacles should the field `pflag` be reversed). Defaults to `idxs = (i) -> i`, i.e. only the colliding obstacle is affected. If you want many obstacles to be affected you could write `idxs = (i) -> SVector(2,3,5)`, etc. Keep in mind that the only values of `i` that can be passed into this function are the ones that are given in the argument `idxs`! """ struct RaySplitter{T, Φ, Ω, A} oidx::Vector{Int} transmission::T refraction::Φ newω::Ω affect::A end @inline default_affect(i) = i @inline default_angular(ω, pflag) = ω function RaySplitter(idxs, tr, ref, newangular = default_angular; affect = default_affect) for i ∈ idxs i ∈ affect(i) || throw(ArgumentError( "All indices that correspond to this RaySplitter must also be affected!")) end typeof(idxs) == Int && (idxs = [idxs]) return RaySplitter(sort(idxs), tr, ref, newangular, affect) end #pretty print: function Base.show(io::IO, ::MIME"text/plain", ray::RaySplitter) ps = 15 angtext = ray.newω == default_angular ? "default" : "$(ray.newω)" afftext = ray.affect == default_affect ? "default" : "$(ray.affect)" print(io, "RaySplitter for indices $(ray.oidx)"*"\n", rpad(" transmission: ", ps)*"$(ray.transmission)\n", rpad(" refraction: ", ps)*"$(ray.refraction)\n", rpad(" new angular: ", ps)*angtext*"\n", rpad(" affect: ", ps)*afftext*"\n" ) end function Base.show(io::IO, ray::RaySplitter) print(io, "RaySplitter for indices $(ray.oidx)") end """ raysplit_indices(bd::Billiard, raysplitters::Tuple) Create a vector of integers. The `i`th entry tells you which entry of the `raysplitters` tuple is associated with the `i`th obstacle of the billiard. If the `i`th entry is `0`, this means that the obstacle does not do raysplitting. """ function raysplit_indices(bd::Billiard, raysplitters::Tuple) O = zeros(Int, length(bd.obstacles)) for (k, rayspl) ∈ enumerate(raysplitters) O[rayspl.oidx] .= k end return O end allaffected(ray::RaySplitter) = union(ray.affect(i) for i in ray.oidx) """ acceptable_raysplitter(raysplitters, bd::Billiard) Return `true` if the given `raysplitters` can be used in conjuction with given billiard `bd`. """ function acceptable_raysplitter(raysplitters::Tuple, bd::Billiard) for ray in raysplitters for i in (ray.oidx ∪ ray.affect(ray.oidx)) if !supports_raysplitting(bd[i]) error("Obstacle at index $i of given billiard table"* " does not have a field `pflag`"* " and therefore does not support ray-splitting."* " However a `RaySplitter` uses it!") end end end idx = raysplit_indices(bd, raysplitters) # Make sure that no indices are shared in the corresponding obstacles vecs = [ray.oidx for ray in raysplitters] if length(unique(vcat(vecs...))) != sum(length.(vecs)) error("Different `RaySplitter`s cannot correspond to the same "* "obstacles!") end true end ##################################################################################### # Resolve collisions ##################################################################################### timeprec_rayspl(::Particle{T}) where {T} = timeprec(T) timeprec_rayspl(::MagneticParticle{T}) where {T} = timeprec_forward(T) const CLAMPING_ANGLE = 0.1 angleclamp(φ::T) where {T} = clamp(φ, -π/2 + T(CLAMPING_ANGLE), π/2 - T(CLAMPING_ANGLE)) function incidence_angle(p::AbstractParticle{T}, a::Obstacle{T})::T where {T} # Raysplit Algorithm step 1: Determine incidence angle (0 < φ < π/4) n = normalvec(a, p.pos) inverse_dot = clamp(dot(p.vel, -n), -1.0, 1.0) φ = acos(inverse_dot) # Raysplit Algorithm step 2: get correct sign if cross2D(p.vel, n) < 0 φ *= -1 end return φ end function istransmitted(p::AbstractParticle{T}, a::Obstacle{T}, Tr::F) where {T, F} ω = typeof(p) <: MagneticParticle ? p.omega : zero(T) φ = incidence_angle(p, a) # Raysplit Algorithm step 3: check transmission probability trans = Tr(φ, a.pflag, ω) > rand() end # Raysplit Algorithm step 4: relocate the particle _inside_ the obstacle # if ray-splitting happens (see `ineq` variable) function relocate_rayspl!(p::AbstractParticle{T}, o::Obstacle{T}, trans::Bool = false) where {T} ineq = 2trans - 1 d = distance(p.pos, o) notokay = ineq*d > 0.0 if notokay n = normalvec(o, p.pos) p.pos -= d * n end return notokay end function resolvecollision!(p::AbstractParticle{T}, bd::Billiard{T}, colidx::Int, trans::Bool, rayspl::RaySplitter) where {T<:AbstractFloat} a = bd[colidx] ismagnetic = typeof(p) <: MagneticParticle ω = ismagnetic ? p.omega : T(0) # Raysplit Algorithm step 5: recompute angle of incidence φ = incidence_angle(p, a) if trans #perform raysplitting # Raysplit Algorithm step 6: find transmission angle in relative angles theta = angleclamp(rayspl.refraction(φ, a.pflag, ω)) # Raysplit Algorithm step 7: reverse the Obstacle propagation flag # for all obstacles dictated by the RaySplitter # (this also reverses `normalvec` !) for oi ∈ rayspl.affect(colidx) bd[oi].pflag = ! bd[oi].pflag end # Raysplit Algorithm step 8: find transmission angle in real-space angles n = normalvec(a, p.pos) #notice that this is reversed! It's the new normalvec! Θ = theta + atan(n[2], n[1]) # Raysplit Algorithm step 9: Perform refraction p.vel = SVector{2,T}(cos(Θ), sin(Θ)) # Raysplit Algorithm step 10: Set new angular velocity if ismagnetic ω = rayspl.newω(p.omega, !a.pflag) # notice the exclamation mark p.omega = ω p.r = abs(1/ω) end else # No ray-splitting: #perform specular specular!(p, a) end return end # Ray-splitting version of bounce! # raysplitters is a tuple of RaySplitter. raysidx is a vector that given the obstacle # index it tells you which raysplitter to choose from the tuple OR to not # do raysplitting at all (for returned index 0) function bounce!(p::AbstractParticle{T}, bd::Billiard{T}, raysidx::Vector{Int}, raysplitters::Tuple) where {T} i::Int, tmin::T, cp::SV{T} = next_collision(p, bd) if tmin == Inf return i, tmin, p.pos, p.vel elseif raysidx[i] != 0 propagate!(p, cp, tmin) trans::Bool = istransmitted(p, bd[i], raysplitters[raysidx[i]].transmission) relocate_rayspl!(p, bd[i], trans) resolvecollision!(p, bd, i, trans, raysplitters[raysidx[i]]) else relocate!(p, bd[i], tmin, cp) resolvecollision!(p, bd[i]) end typeof(p) <: MagneticParticle && (p.center = find_cyclotron(p)) return i, tmin, p.pos, p.vel end ##################################################################################### # Evolve raysplitting ##################################################################################### @inline raysplit_indices(bd, ::Nothing) = nothing @inline bounce!(p, bd, ::Nothing, ::Nothing) = bounce!(p, bd) @inline acceptable_raysplitter(::Nothing, bd::Billiard) = true evolve!(p, bd, t, ray::RaySplitter; warning = false) = evolve!(p, bd, t, (ray, ); warning = warning) function evolve!(p::Matrix{T}, bd::Billiard{T}, t, raysplitters::Tuple; warning = false) where {T} if t <= 0 throw(ArgumentError("`evolve!()` cannot evolve backwards in time.")) end # Check if raysplitters are acceptable acceptable_raysplitter(raysplitters, bd) ismagnetic = typeof(p) <: MagneticParticle raysidx = raysplit_indices(bd, raysplitters) rt = T[]; push!(rt, 0) rpos = SVector{2,T}[]; push!(rpos, p.pos) rvel = SVector{2,T}[]; push!(rvel, p.vel) ismagnetic && (omegas = T[]; push!(omegas, p.omega)) count = zero(t) t_to_write = zero(T) while count < t i, tmin, pos, vel = bounce!(p, bd, raysidx, raysplitters) t_to_write += tmin if ismagnetic && tmin == Inf warning && warn("Pinned particle in evolve! (Inf. col. t)") push!(rpos, pos); push!(rvel, vel) push!(rt, tmin); push!(omegas, p.omega) return (rt, rpos, rvel, omegas) end if isperiodic(bd) && i ∈ bd.peridx # Pinned particle: if ismagnetic && t_to_write ≥ 2π/absω warning && warn("Pinned particle in evolve! (completed circle)") push!(rpos, pos); push!(rvel, vel) push!(rt, tmin); push!(omegas, p.omega) return (rt, rpos, rvel, omegas) end #If not pinned, continue (do not write for PeriodicWall) continue else push!(rpos, p.pos + p.current_cell) push!(rvel, p.vel); push!(rt, t_to_write); ismagnetic && push!(omegas, p.omega) count += increment_counter(t, t_to_write) t_to_write = zero(T) end end#time loop if ismagnetic return (rt, rpos, rvel, omegas) else return (rt, rpos, rvel) end end ######################## # is physical, etc. ######################## function supports_raysplitting(obst::Obstacle) n = fieldnames(typeof(obst)) in(:pflag, n) end """ reset_billiard!(bd) Sets the `pflag` field of all ray-splitting obstacles of a billiard table to `true`. """ function reset_billiard!(bd::Billiard) for obst in bd supports_raysplitting(obst) && (obst.pflag = true) end end """ isphysical(raysplitter(s)) Return `true` if the given `raysplitters` have physically plausible properties. Specifically, check if (φ is the incidence angle, θ the refraction angle): * Critical angle means total reflection: If θ(φ) ≥ π/2 then Tr(φ) = 0 * Transmission probability is even function: Tr(φ) ≈ Tr(-φ) at ω = 0 * Refraction angle is odd function: θ(φ) ≈ -θ(-φ) at ω = 0 * Ray reversal is true: θ(θ(φ, pflag, ω), !pflag, ω) ≈ φ * Magnetic conservation is true: (ω_new(ω_new(ω, pflag), !pflag) ≈ ω """ isphysical(ray::RaySplitter) = isphysical((ray,)) function isphysical(rays::Tuple) for (i, ray) in enumerate(rays) scatter = ray.refraction tr = ray.transmission om = ray.newω range = -1.5:0.01:1.5 orange = -1.0:0.1:1.0 for pflag in (true, false) for ω in orange for φ in range # Calculate refraction angle: θ = scatter(φ, pflag, ω) # Calculate transmission probability: T = tr(φ, pflag, ω) # Check critical angle: if θ >= π/2 && T > 0 es = "Refraction angle ≥ π/2 and T > 0 !\n" es*= "For index = $i, tested with φ = $φ, pflag = $pflag, ω = $ω" println(es) return false end # Check symmetry: if ω==0 if !isapprox(θ, -scatter(-φ, pflag, ω)) es = "Scattering angle function is not odd!\n" es *="For index = $i, tested with φ = $φ, pflag = $pflag, ω = $ω" println(es) return false end if !isapprox(T, tr(-φ, pflag, ω)) es = "Transmission probability function is not even!\n" es *="For index = $i, tested with φ = $φ, pflag = $pflag, ω = $ω" println(es) return false end end # Check ray-reversal: if !isapprox(scatter(θ, !pflag, ω), φ) es = "Ray-reversal does not hold!\n" es *="For index = $i, tested with φ = $φ, pflag = $pflag, ω = $ω" println(es) return false end if !isapprox(om(om(ω, pflag), !pflag), ω) es = "Magnetic reversal does not hold!\n" es *="For index = $i, tested with φ = $φ, pflag = $pflag, ω = $ω" println(es) return false end end#φ range end#ω range end#pflag range end#obstacle range return true end ################################################################################ """ law_of_refraction(n1, n2 = 1.0) -> t, r Create transmission and refraction functions `t, r` that follow Snell's law, i.e. the transmission probability is set to 1.0 except for the case of total internal reflection. `n1` is the index of refraction for the `pflag = false` side of an obstacle, while `n2` is the index of refraction for `pflag = true`. """ function law_of_refraction(n1, n2 = 1.0) # n1 is "inside" the obstacle, n2 is "outside" if n1 < 1.0 || n2 < 1.0 error("You have just given a physicist a headache.") end # Snell's law refraction(φ, pflag, ω) = asin(clamp((pflag ? (n2/n1) : (n1/n2) )* sin(φ), -1.0, 1.0)) # total internal reflection function transmission(φ, pflag, ω) nratio = pflag ? (n1/n2) : (n2/n1) if abs(nratio) < 1 && abs(φ) >= asin(nratio) return 0.0 else return 1.0 end end return transmission, refraction end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
5861
module Testing using DynamicalBilliards, Test using DynamicalBilliards: isperiodic export tag, omnibilliard, finitehorizon, testparticles, isperiodic export acclevel using DynamicalBilliards: distance, cellsize export distance, cellsize CONCAVE = Union{Semicircle} tag(p::Particle) = "[STRAIGHT]" tag(p::MagneticParticle) = "[MAGNETIC]" function tag(bd::Billiard) s = DynamicalBilliards.isperiodic(bd) ? "[PERIODIC]" : "" if length(unique(map(x -> typeof(x), bd))) > 7 s *= "[OMNI]" elseif any(o -> typeof(o) <: CONCAVE, bd) s *= "[CONCAVE]" end return s end tag(t::Union{<: RaySplitter, <: Tuple}) = "[RAYSPLIT]" tag(args...) = join([tag(a) for a in args]) acclevel(::Particle{T}) where {T} = eps(T)^(3/4) acclevel(::MagneticParticle{T}) where {T} = eps(T)^(3/4) acclevel(bd::Billiard{T}) where {T} = isperiodic(bd) ? eps(T)^(3/5) : eps(T)^(3/4) acclevel(t::Union{<: RaySplitter, <: Tuple}) = eps()^(3/4) acclevel(args...) = maximum(acclevel(a) for a in args) function omnibilliard() pref = 3 # how big is the frame with respect to the Disks h = pref*1.0; α = pref*0.8; r = 0.3; off = pref*0.25 cos6 = cos(π/6) β = (h - cos6*α)/cos6 t = α + 2β center_of_mass = [0.0, √3*t/6] startloc = [-α/2, 0.0] # create directions of the hexagonal 6: hexvert = [(cos(2π*i/6), sin(2π*i/6)) for i in 1:6] dirs = [SVector{2}(hexvert[i] .- hexvert[mod1(i+1, 6)]) for i in 1:6] frame = Obstacle{Float64}[] sp = startloc ep = startloc + α*dirs[1] normal = (w = ep .- sp; [-w[2], w[1]]) push!(frame, Semicircle((sp+ep)/2, α/2, normal)) for i in 2:6 s = iseven(i) ? β : α x = mod(i, 4) T = if x == 1 RandomWall elseif x == 2 FiniteWall elseif x == 3 SplitterWall elseif x == 0 InfiniteWall end sp = i != 2 ? frame[i-1].ep : startloc + α*dirs[1] ep = sp + s*dirs[i] normal = (w = ep .- sp; [-w[2], w[1]]) push!(frame, T(sp, ep, normal)) end # Radii of circles that compose the Julia logo offset = [0.0, off] R = [cos(2π/3) -sin(2π/3); sin(2π/3) cos(2π/3)] green = Disk(center_of_mass .+ offset, r, "green") red = Antidot(center_of_mass .+ R*offset, r, "red") purple = RandomDisk(center_of_mass .+ R*R*offset, r, "purple") bd = Billiard(green, red, purple, frame...) end finitehorizon(r = 0.5) = billiard_hexagonal_sinai(0.5; setting = "periodic") function testparticles() p = Particle(0.31, 0.51, 2π*rand()) mp = MagneticParticle(0.31, 0.51, 2π*rand(), 0.5) return p, mp end function all_tests(f, args...) omni_tests(f, args...) periodic_tests(f, args...) end function simple_tests(f, args...) ergodic_tests(f, args...) periodic_tests(f, args...) end function omni_tests(f, args...) bd = omnibilliard() p, mp = testparticles() e = Ellipse([0.68, 1.53], 0.3, 0.2) bd2 = Billiard(bd..., e) f(p, bd2, args...) f(mp, bd, args...) end function omni_tests_noellipse(f, args...) bd = omnibilliard() p, mp = testparticles() f(p, bd, args...) f(mp, bd, args...) end export omni_tests_noellipse function periodic_tests(f, args...) bd = finitehorizon() p, mp = testparticles() f(p, bd, args...) f(mp, bd, args...) end function ergodic_tests(f, args...) for bd in (billiard_sinai(), billiard_stadium()) p = Particle(0.1, 0.1, 2π*rand()) mp = MagneticParticle(p, 1.0) f(p, bd, args...) f(mp, bd, args...) end end """ billiards_testset(description, f, args...; caller = all_tests) Wrap a testset around `caller(f, args...)` which times the result and separates the test from others (`println`). """ function billiards_testset(d, f, args...; caller = all_tests) println(">> TEST: $(d)") t = time() @testset "$(d)" begin caller(f, args...) end println("Required time: $(round(time()-t, digits=3)) sec.") separator() end separator() = println("\n", "- "^30, "\n") export all_tests, simple_tests, omni_tests, periodic_tests, billiards_testset export ergodic_tests function basic_ray(ellipse) bd = billiard_rectangle() d = Antidot([0.25, 0.5], 0.15) if ellipse e = Ellipse([0.75, 0.5], 0.15, 0.25) bd = Billiard(bd..., d, e) else bd = Billiard(bd..., d) end sa = (φ, pflag, ω) -> pflag ? 0.5φ : 2.0φ newoantidot = ((x, bool) -> bool ? -0.5x : -2.0x) Tp = (p) -> (φ, pflag, ω) -> begin if pflag p else abs(φ) < π/4 ? (1-p) : 0.0 end end ray = RaySplitter(ellipse ? [5, 6] : [5], Tp(0.5), sa, newoantidot) return bd, (ray,) end function extreme_ray(ellipse) x = 2.0; y = 1.0 bdr = billiard_rectangle(2.0, 1.0) sw = SplitterWall([x/2, 0.0], [x/2,y], [-1,0], true) a1 = Antidot([x/4, y/2], 0.25, "Left Antidot") if ellipse a2 = Ellipse([3x/4, y/2], 0.25, 0.2, true, "Ellipse") else a2 = Antidot([3x/4, y/2], 0.25, "Right Antidot") end sa(φ, pflag, ω) = pflag ? 2.0φ : 0.5φ function Tp(φ, pflag, ω) if pflag abs(φ) < π/4 ? 0.9 : 0.0 else 0.9 end end newoantidot = ((x, bool) -> bool ? -0.5x : -2.0x) raywall = RaySplitter([3], Tp, sa, newoantidot) raya = RaySplitter([1, 2], Tp, sa, newoantidot) return Billiard(a1, a2, sw, bdr...), (raywall, raya) end function ray_tests(f, args...) bd, ray = basic_ray(true) p = randominside(bd) @testset "$(tag(p, bd, ray))" begin; f(p, bd, ray, args...); end bd, ray = basic_ray(false) p = randominside(bd, 1.0) @testset "$(tag(p, bd, ray))" begin; f(p, bd, ray, args...); end end export basic_ray, extreme_ray, ray_tests end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
5590
export Billiard, randominside, randominside_xyφ ####################################################################################### ## Billiard Table ####################################################################################### struct Billiard{T, D, O<:Tuple, Y} obstacles::O peridx::Y end @inline isperiodic(::Billiard{T,D,<:Tuple,Vector{Int}}) where {T,D} = true @inline isperiodic(::Billiard{T,D,<:Tuple,Nothing}) where {T,D} = false @inline isperiodic(i::Int, ::Billiard{T,D,O,Nothing}) where {T,D,O} = false @inline isperiodic(i::Int, bd::Billiard{T,D,<:Tuple,Vector{Int}}) where {T,D} = i ∈ bd.peridx #pretty print: _get_name(o::Obstacle) = :name ∈ fieldnames(typeof(o)) ? o.name : string(typeof(o)) function Base.show(io::IO, bd::Billiard{T,D,BT}) where {T, D, BT} s = "Billiard{$T} with $D obstacles:" bd.peridx != nothing && (s = "Periodic "*s) for i in 1:min(10, length(bd)) s*="\n $(_get_name(bd[i]))" end print(io, s) length(bd) > 10 && print(io, "\n ...") end """ Billiard(obstacles...) Construct a `Billiard` from given `obstacles` (tuple, vector, varargs). For functions like [`boundarymap`](@ref), it is expected (if possible) that the obstacles of the billiard are sorted, such that the arc-coordinate `ξ` around the billiard is increasing counter-clockwise. `ξ` is measured as: * the distance from start point to end point in `Wall`s * the arc length measured counterclockwise from the open face in `Semicircle`s * the arc length measured counterclockwise from the rightmost point in `Circular`s """ function Billiard(bd::Union{AbstractVector, Tuple}) T = eltype(bd[1]) D = length(bd) # Assert that all elements of `bd` are of same type: for i in 2:D eltype(bd[i]) != T && throw(ArgumentError( "All obstacles of the billiard must have same type of numbers. Found $T and $(eltype(bd[i])) instead." )) end tup = Tuple(bd) peridx = findall(x -> typeof(x) <: PeriodicWall, tup) if isodd(length(peridx)) throw(ArgumentError( "A billiard can only have an even number of `PeriodicWall`s, "* "since they have to come in pairs." )) end if !any(x -> x isa PeriodicWall, bd) return Billiard{T, D, typeof(tup), Nothing}(tup, nothing) else return Billiard{T, D, typeof(tup), Vector{Int}}(tup, peridx) end end function Billiard(bd::Vararg{Obstacle}) tup = (bd...,) return Billiard(tup) end Base.getindex(bd::Billiard, i) = bd.obstacles[i] Base.lastindex(bd::Billiard) = length(bd.obstacles) Base.firstindex(bd::Billiard) = 1 # Iteration: Base.iterate(bd::Billiard) = iterate(bd.obstacles) Base.iterate(bd::Billiard, state) = iterate(bd.obstacles, state) Base.length(::Billiard{T, L}) where {T, L} = L Base.eltype(::Billiard{T}) where {T} = T ####################################################################################### ## Distances ####################################################################################### for f in (:distance, :distance_init) @eval $(f)(p::AbstractParticle, bd::Billiard) = $(f)(p.pos, bd.obstacles) @eval $(f)(pos::SV{T}, bd::Billiard) where {T} = $(f)(pos, bd.obstacles) end for f in (:distance, :distance_init) @eval begin function ($f)(p::SV{T}, bd::Tuple)::T where {T} dmin::T = T(Inf) for obst in bd d::T = distance(p, obst) d < dmin && (dmin = d) end return dmin end end end ####################################################################################### ## randominside ####################################################################################### function cellsize( bd::Union{Vector{<:Obstacle{T}}, Billiard{T}}) where {T<:AbstractFloat} xmin::T = ymin::T = T(Inf) xmax::T = ymax::T = T(-Inf) for obst ∈ bd xs::T, ys::T, xm::T, ym::T = cellsize(obst) xmin = xmin > xs ? xs : xmin ymin = ymin > ys ? ys : ymin xmax = xmax < xm ? xm : xmax ymax = ymax < ym ? ym : ymax end return xmin, ymin, xmax, ymax end """ randominside(bd::Billiard [, ω]) → p Return a particle `p` with random allowed initial conditions inside the given billiard. If supplied with a second argument the type of the returned particle is `MagneticParticle`, with angular velocity `ω`. **WARNING** : `randominside` works for any **convex** billiard but it does not work for non-convex billiards. (this is because it uses `distance`) """ randominside(bd::Billiard, ω::Nothing = nothing) = Particle(_randominside(bd)...) randominside(bd::Billiard{T}, ω::Real) where {T} = MagneticParticle(_randominside(bd)..., T(ω)) """ randominside_xyφ(bd::Billiard) → x, y, φ Same as [`randominside`](@ref) but only returns position and direction. """ function randominside_xyφ(bd::Billiard{T}) where {T<:AbstractFloat} xmin::T, ymin::T, xmax::T, ymax::T = cellsize(bd) xp = T(rand())*(xmax-xmin) + xmin yp = T(rand())*(ymax-ymin) + ymin pos = SV{T}(xp, yp) dist = distance_init(pos, bd) while dist <= sqrt(eps(T)) xp = T(rand())*(xmax-xmin) + xmin yp = T(rand())*(ymax-ymin) + ymin pos = SV{T}(xp, yp) dist = distance_init(pos, bd) end return pos[1], pos[2], T(2π*rand()) end function _randominside(bd::Billiard{T}) where {T<:AbstractFloat} x, y, φ = randominside_xyφ(bd) pos = SV{T}(x, y) vel = SV{T}(sincos(φ)...) return pos, vel, zero(SV{T}) # this zero is the `current_cell` end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
21891
export Obstacle, Disk, Antidot, RandomDisk, Wall, Circular, InfiniteWall, PeriodicWall, RandomWall, SplitterWall, FiniteWall, FiniteSplitterWall, Semicircle, Ellipse export translate using InteractiveUtils ####################################################################################### ## Circles ####################################################################################### """ Obstacle{<:AbstractFloat} Obstacle supertype. """ abstract type Obstacle{T<:AbstractFloat} end eltype(o::Obstacle{T}) where {T} = T """ Circular{T<:AbstractFloat} <: Obstacle{T} Circular obstacle supertype. """ abstract type Circular{T<:AbstractFloat} <: Obstacle{T} end """ Disk{T<:AbstractFloat} <: Circular{T} Disk-like obstacle with propagation allowed outside of the circle (immutable type). ### Fields: * `c::SVector{2,T}` : Center. * `r::T` : Radius. * `name::String` : Some name given for user convenience. Defaults to "Disk". """ struct Disk{T<:AbstractFloat} <: Circular{T} c::SVector{2,T} r::T name::String end function Disk(c::AbstractVector{T}, r::Real, name::String = "Disk") where {T<:Real} S = T <: Integer ? Float64 : T return Disk{S}(SVector{2,S}(c), convert(S, abs(r)), name) end Disk{T}(args...) where {T} = Disk(args...) """ RandomDisk{T<:AbstractFloat} <: Circular{T} Disk-like obstacle that randomly (and uniformly) reflects colliding particles. The propagation is allowed outside of the circle. ### Fields: * `c::SVector{2,T}` : Center. * `r::T` : Radius. * `name::String` : Some name given for user convenience. Defaults to "Random disk". """ struct RandomDisk{T<:AbstractFloat} <: Circular{T} c::SVector{2,T} r::T name::String end function RandomDisk( c::AbstractVector{T}, r::Real, name::String = "RandomDisk") where {T<:Real} S = T <: Integer ? Float64 : T return RandomDisk{S}(SVector{2,S}(c), convert(S, abs(r)), name) end RandomDisk{T}(args...) where {T} = RandomDisk(args...) """ Antidot{T<:AbstractFloat} <: Circular{T} Disk-like obstacle that allows propagation both inside and outside of the disk (mutable type). Used in ray-splitting billiards. ### Fields: * `c::SVector{2,T}` : Center. * `r::T` : Radius. * `pflag::Bool` : Flag that keeps track of where the particle is currently propagating (`pflag` = propagation-flag). `true` stands for *outside* the disk, `false` for *inside* the disk. Defaults to `true`. * `name::String` : Name of the obstacle given for user convenience. Defaults to "Antidot". """ mutable struct Antidot{T<:AbstractFloat} <: Circular{T} c::SVector{2,T} r::T pflag::Bool name::String end function Antidot(c::AbstractVector{T}, r::Real, pflag::Bool = true, name::String = "Antidot") where {T<:Real} S = T <: Integer ? Float64 : T return Antidot{S}(SVector{2,S}(c), convert(S, abs(r)), pflag, name) end Antidot(c, r, name::String = "Antidot") = Antidot(c, r, true, name) Antidot{T}(args...) where {T} = Antidot(args...) """ Semicircle{T<:AbstractFloat} <: Circular{T} Obstacle that represents half a circle. Propagation is allowed only inside the semicircle. ### Fields: * `c::SVector{2,T}` : Center. * `r::T` : Radius. * `facedir::SVector{2,T}` : Direction where the open face of the Semicircle is facing. * `name::String` : Name of the obstacle given for user convenience. Defaults to "Semicircle". """ struct Semicircle{T<:AbstractFloat} <: Circular{T} c::SVector{2,T} r::T facedir::SVector{2,T} name::String end function Semicircle( c::AbstractVector{T}, r::Real, facedir, name = "Semicircle") where {T<:Real} S = T <: Integer ? Float64 : T return Semicircle{S}( SV(c), convert(S, abs(r)), SV(normalize(facedir)), name) end show(io::IO, w::Circular{T}) where {T} = print(io, "$(w.name) {$T}\n", "center: $(w.c)\nradius: $(w.r)") show(io::IO, w::Semicircle{T}) where {T} = print(io, "$(w.name) {$T}\n", "center: $(w.c)\nradius: $(w.r)\nfacedir: $(w.facedir)") ####################################################################################### ## Walls ####################################################################################### """ Wall{T<:AbstractFloat} <: Obstacle{T} Wall obstacle supertype. All `Wall` subtypes (except `PeriodicWall`) can be called as `Wall(sp, ep)`, in which case the normal vector is computed automatically to point to the left of `v = ep - sp`. """ abstract type Wall{T<:AbstractFloat} <: Obstacle{T} end """ InfiniteWall{T<:AbstractFloat} <: Wall{T} Wall obstacle imposing specular reflection during collision (immutable type). Faster than [`FiniteWall`](@ref), meant to be used for convex billiards. ### Fields: * `sp::SVector{2,T}` : Starting point of the Wall. * `ep::SVector{2,T}` : Ending point of the Wall. * `normal::SVector{2,T}` : Normal vector to the wall, pointing to where the particle *will come from before a collision* (pointing towards the inside of the billiard). The size of the vector is irrelevant since it is internally normalized. * `name::String` : Name of the obstacle, given for user convenience. Defaults to "Wall". """ struct InfiniteWall{T<:AbstractFloat} <: Wall{T} sp::SVector{2,T} ep::SVector{2,T} normal::SVector{2,T} name::String end function InfiniteWall(sp::AbstractVector, ep::AbstractVector, n::AbstractVector, name::String = "Wall") T = eltype(sp) n = normalize(n) d = dot(n, ep-sp) if abs(d) > 10eps(T) error("Normal vector is not actually normal to the wall") end T = eltype(sp) <: Integer ? Float64 : eltype(sp) return InfiniteWall{T}(SVector{2,T}(sp), SVector{2,T}(ep), SVector{2,T}(n), name) end """ FiniteWall{T<:AbstractFloat} <: Wall{T} Wall obstacle imposing specular reflection during collision (immutable type). Slower than [`InfiniteWall`](@ref), meant to be used for non-convex billiards. Giving a `true` value to the field `isdoor` designates this obstacle to be a `Door`. This is used in [`escapetime`](@ref) function. A `Door` is a obstacle of the billiard that the particle can escape from, thus enabling calculations of escape times. ### Fields: * `sp::SVector{2,T}` : Starting point of the Wall. * `ep::SVector{2,T}` : Ending point of the Wall. * `normal::SVector{2,T}` : Normal vector to the wall, pointing to where the particle *will come from before a collision* (pointing towards the inside of the billiard). The size of the vector is irrelevant since it is internally normalized. * `isdoor::Bool` : Flag of whether this `FiniteWall` instance is a "Door". Defaults to `false`. * `name::String` : Name of the obstacle, given for user convenience. Defaults to "Finite Wall". """ struct FiniteWall{T<:AbstractFloat} <: Wall{T} sp::SVector{2,T} ep::SVector{2,T} normal::SVector{2,T} width::T center::SVector{2,T} isdoor::Bool name::String end function FiniteWall(sp::AbstractVector, ep::AbstractVector, n::AbstractVector, isdoor::Bool = false, name::String = "Finite Wall") T = eltype(sp) n = normalize(n) d = dot(n, ep-sp) if abs(d) > 10eps(T) error("Normal vector is not actually normal to the wall: dot = $d") end T = eltype(sp) <: Integer ? Float64 : eltype(sp) w = norm(ep - sp) center = @. (ep+sp)/2 return FiniteWall{T}(SVector{2,T}(sp), SVector{2,T}(ep), SVector{2,T}(n), w, SVector{2,T}(center), isdoor, name) end FiniteWall(a, b, c, n::String) = FiniteWall(a, b, c, false, n) isdoor(w) = w.isdoor """ RandomWall{T<:AbstractFloat} <: Wall{T} Wall obstacle imposing (uniformly) random reflection during collision (immutable type). ### Fields: * `sp::SVector{2,T}` : Starting point of the Wall. * `ep::SVector{2,T}` : Ending point of the Wall. * `normal::SVector{2,T}` : Normal vector to the wall, pointing to where the particle *is expected to come from* (pointing towards the inside of the billiard). * `name::String` : Name of the obstacle, given for user convenience. Defaults to "Random wall". """ struct RandomWall{T<:AbstractFloat} <: Wall{T} sp::SVector{2,T} ep::SVector{2,T} normal::SVector{2,T} name::String end function RandomWall(sp::AbstractVector, ep::AbstractVector, n::AbstractVector, name::String = "Random wall") T = eltype(sp) <: Integer ? Float64 : eltype(sp) n = normalize(n) d = dot(n, ep-sp) if abs(d) > 10eps(T) error("Normal vector is not actually normal to the wall") end return RandomWall{T}(SVector{2,T}(sp), SVector{2,T}(ep), SVector{2,T}(n), name) end """ PeriodicWall{T<:AbstractFloat} <: Wall{T} Wall obstacle that imposes periodic boundary conditions upon collision (immutable type). ### Fields: * `sp::SVector{2,T}` : Starting point of the Wall. * `ep::SVector{2,T}` : Ending point of the Wall. * `normal::SVector{2,T}` : Normal vector to the wall, pointing to where the particle *will come from* (to the inside the billiard). The size of the vector is **important**! This vector is added to a particle's `pos` during collision. Therefore the size of the normal vector must be correctly associated with the size of the periodic cell. * `name::String` : Name of the obstacle, given for user convenience. Defaults to "Periodic wall". """ struct PeriodicWall{T<:AbstractFloat} <: Wall{T} sp::SVector{2,T} ep::SVector{2,T} normal::SVector{2,T} name::String end function PeriodicWall(sp::AbstractVector, ep::AbstractVector, n::AbstractVector, name::String = "Periodic wall") T = eltype(sp) d = dot(n, ep-sp) if abs(d) > 10eps(T) error("Normal vector is not actually normal to the wall") end T = eltype(sp) <: Integer ? Float64 : eltype(sp) return PeriodicWall{T}(SVector{2,T}(sp), SVector{2,T}(ep), SVector{2,T}(n), name) end """ SplitterWall{T<:AbstractFloat} <: Wall{T} Wall obstacle imposing allowing for ray-splitting (mutable type). ### Fields: * `sp::SVector{2,T}` : Starting point of the Wall. * `ep::SVector{2,T}` : Ending point of the Wall. * `normal::SVector{2,T}` : Normal vector to the wall, pointing to where the particle *will come from before a collision*. The size of the vector is irrelevant. * `pflag::Bool` : Flag that keeps track of where the particle is currently propagating (`pflag` = propagation flag). `true` is associated with the `normal` vector the wall is instantiated with. Defaults to `true`. * `name::String` : Name of the obstacle, given for user convenience. Defaults to "Splitter wall". """ mutable struct SplitterWall{T<:AbstractFloat} <: Wall{T} sp::SVector{2,T} ep::SVector{2,T} normal::SVector{2,T} pflag::Bool name::String end function SplitterWall(sp::AbstractVector, ep::AbstractVector, normal::AbstractVector, pflag::Bool = true, name::String = "Splitter wall") T = eltype(sp) n = normalize(normal) d = dot(n, ep-sp) if abs(d) > 10eps(T) error("Normal vector is not actually normal to the wall") end T = eltype(sp) <: Integer ? Float64 : eltype(sp) return SplitterWall{T}( SVector{2,T}(sp), SVector{2,T}(ep), SVector{2,T}(n), pflag, name) end SplitterWall(sp, ep, n, name::String = "Splitter wall") = SplitterWall(sp, ep, n, true, name) """ FiniteSplitterWall{T<:AbstractFloat} <: Wall{T} Finite wall obstacle allowing fow ray-splitting (mutable type). ### Fields: * `sp::SVector{2,T}` : Starting point of the Wall. * `ep::SVector{2,T}` : Ending point of the Wall. * `normal::SVector{2,T}` : Normal vector to the wall, pointing to where the particle *will come from before a collision* (pointing towards the inside of the billiard). The size of the vector is irrelevant since it is internally normalized. * `isdoor::Bool` : Flag of whether this `FiniteSplitterWall` instance is a "Door". Defaults to `false`. * `pflag::Bool` : Flag that keeps track of where the particle is currently propagating (`pflag` = propagation flag). `true` is associated with the `normal` vector the wall is instantiated with. Defaults to `true`. * `name::String` : Name of the obstacle, given for user convenience. Defaults to "Finite Splitter Wall". """ mutable struct FiniteSplitterWall{T<:AbstractFloat} <: Wall{T} sp::SVector{2,T} ep::SVector{2,T} normal::SVector{2,T} width::T center::SVector{2,T} isdoor::Bool pflag::Bool name::String end function FiniteSplitterWall(sp::AbstractVector, ep::AbstractVector, n::AbstractVector, isdoor::Bool = false, pflag::Bool = true, name::String = "Finite Splitter Wall") T = eltype(sp) n = normalize(n) d = dot(n, ep-sp) if abs(d) > 10eps(T) error("Normal vector is not actually normal to the wall: dot = $d") end T = eltype(sp) <: Integer ? Float64 : eltype(sp) w = norm(ep - sp) center = @. (ep+sp)/2 return FiniteSplitterWall{T}(SVector{2,T}(sp), SVector{2,T}(ep), SVector{2,T}(n), w, SVector{2,T}(center), isdoor, pflag, name) end FiniteSplitterWall(a, b, c, n::String) = FiniteSplitterWall(a, b, c, false, true, n) #pretty print: show(io::IO, w::Wall{T}) where {T} = print(io, "$(w.name) {$T}\n", "start point: $(w.sp)\nend point: $(w.ep)\nnormal vector: $(w.normal)") """ default_normal(sp, ep) Return a vector to `v = ep - sp`, pointing to the left of `v`. """ function default_normal(sp, ep) T = eltype(sp) (x, y) = ep .- sp return SV{T}(-y, x) end for WT in (:InfiniteWall, :FiniteWall, :RandomWall, :SplitterWall) @eval $(WT)(sp, ep) = $(WT)(sp, ep, default_normal(sp, ep)) end ####################################################################################### ## Others: Ellipses ####################################################################################### """ Ellipse{T<:AbstractFloat} <: Obstacle{T} Ellipse obstacle that also allows ray-splitting. The ellipse is always oriented on the x and y axis (although you can make whichever you want the major one). ### Fields: * `c::SVector{2,T}` : Center. * `a::T` : x semi-axis. * `b::T` : y semi-axis. * `pflag::Bool` : Flag that keeps track of where the particle is currently propagating. `true` (default) is associated with being outside the ellipse. * `name::String` : Some name given for user convenience. Defaults to `"Ellipse"`. The ellipse equation is given by ```math \\left(\\frac{x - c[1]}{a} \\right)^2+ \\left(\\frac{y - c[2]}{b}\\right)^2 = 1 ``` """ mutable struct Ellipse{T<:AbstractFloat} <: Obstacle{T} c::SVector{2,T} a::T b::T pflag::Bool name::String arc::T # arclength of one quadrant of the ellipse end """ ellipse_arclength(θ, e::Ellipse) Return the arclength of the ellipse that spans angle `θ` (in normal coordinates, not in the ellipse parameterization). Expects `θ` to be in `[0, 2π]`. After properly calculating the ```math d=b\\,E\\bigl(\\tan^{-1}(a/b\\,\\tan(\\theta))\\,\\big|\\,1-(a/b)^2\\bigr) ``` """ function ellipse_arclength(θ, e::Ellipse) n, θ = divrem(θ, π/2) a = e.a; b = e.b if a/b > 1.0 θ = π/2 - θ return (n + 1.0)*e.arc - proper_ellipse_arclength(θ, b, a) else return n*e.arc + proper_ellipse_arclength(θ, a, b) end end proper_ellipse_arclength(θ, a, b) = b*Elliptic.E(atan(a*tan(θ)/b), 1.0 - (a/b)^2) export ellipse_arclength function Ellipse(c::AbstractVector{T}, a, b, pflag = true, name::String = "Ellipse") where {T<:Real} S = T <: Integer ? Float64 : T return Ellipse{S}(SVector{2,S}(c), convert(S, abs(a)), convert(S, abs(b)), pflag, name, proper_ellipse_arclength(π/2, min(a, b), max(a, b)) ) end Ellipse{T}(args...) where {T} = Ellipse(args...) ####################################################################################### ## Normal vectors ####################################################################################### """ normalvec(obst::Obstacle, position) Return the vector normal to the obstacle's boundary at the given position (which is assumed to be very close to the obstacle's boundary). """ @inline normalvec(wall::Wall, pos) = wall.normal @inline normalvec(w::PeriodicWall, pos) = normalize(w.normal) @inline normalvec(w::SplitterWall, pos) = w.pflag ? w.normal : -w.normal @inline normalvec(w::FiniteSplitterWall, pos) = w.pflag ? w.normal : -w.normal @inline normalvec(disk::Circular, pos) = normalize(pos - disk.c) @inline normalvec(a::Antidot, pos) = a.pflag ? normalize(pos - a.c) : -normalize(pos - a.c) @inline normalvec(d::Semicircle, pos) = normalize(d.c - pos) @inline function normalvec(e::Ellipse{T}, pos) where {T} # from https://www.algebra.com/algebra/homework/ # Quadratic-relations-and-conic-sections/Tangent-lines-to-an-ellipse.lesson x₀, y₀ = pos h, k = e.c s = e.pflag ? one(T) : -one(T) return s*normalize(SV((x₀-h)/(e.a*e.a), (y₀-k)/(e.b*e.b))) end ####################################################################################### ## Distances ####################################################################################### """ project_to_line(point, c, n) Project given `point` to line that contains point `c` and has **normal vector** `n`. """ @inline function project_to_line(point, c, n) posdot = dot(c - point, n) intersection = point + posdot*n end """ distance(p::AbstractParticle, o::Obstacle) Return the **signed** distance between particle `p` and obstacle `o`, based on `p.pos`. Positive distance corresponds to the particle being on the *allowed* region of the `Obstacle`. E.g. for a `Disk`, the distance is positive when the particle is outside of the disk, negative otherwise. distance(p::AbstractParticle, bd::Billiard) Return minimum `distance(p, obst)` for all `obst` in `bd`. If the `distance(p, bd)` is negative and `bd` is convex, this means that the particle is outside the billiard. **WARNING** : `distance(p, bd)` may give negative values for non-convex billiards, or billiards that are composed of several connected sub-billiards. All `distance` functions can also be given a position (vector) instead of a particle. """ (distance(p::AbstractParticle{T}, obst::Obstacle{T})::T) where {T} = distance(p.pos, obst) @inline function distance(pos::AbstractVector{T}, w::Wall{T})::T where {T} v1 = pos - w.sp dot(v1, normalvec(w, pos)) end # no new distance needed for SplitterWall because the `pflag` field # has the necessary information to give the correct dinstance, # since the distance is calculated through the normalvec. @inline distance(pos::AbstractVector{T}, d::Circular{T}) where {T} = norm(pos - d.c) - d.r @inline function distance( pos::AbstractVector{T}, a::Antidot{T})::T where {T} d = norm(pos - a.c) - a.r a.pflag ? d : -d end function distance(pos::AbstractVector{T}, s::Semicircle{T}) where {T} # Check on which half of circle is the particle v1 = pos - s.c nn = dot(v1, s.facedir) if nn ≤ 0 # I am "inside" semicircle return s.r - norm(pos - s.c) else # I am on the "other side" # end1 = SV(s.c[1] + s.r*s.facedir[2], s.c[2] - s.r*s.facedir[1]) # end2 = SV(s.c[1] - s.r*s.facedir[2], s.c[2] + s.r*s.facedir[1]) # return min(norm(pos - end1), norm(pos - end2)) return one(T) end end function distance(pos::SV, e::Ellipse{T})::T where {T} d = ((pos[1] - e.c[1])/e.a)^2 + ((pos[2]-e.c[2])/e.b)^2 - 1.0 e.pflag ? d : -d end # The entire functionality of `distance_init` is necessary only for # FiniteWall and FiniteSplitterWall !!! distance_init(p::AbstractParticle, a::Obstacle) = distance_init(p.pos, a) distance_init(pos::SVector, a::Obstacle) = distance(pos, a) function distance_init(pos::SVector{2,T}, w::Union{FiniteWall{T}, FiniteSplitterWall{T}})::T where {T} n = normalvec(w, pos) posdot = dot(w.sp .- pos, n) if posdot ≥ 0 # I am behind wall intersection = project_to_line(pos, w.center, n) dfc = norm(intersection - w.center) if dfc > w.width/2 return +1.0 # but not directly behind else return -1.0 end end v1 = pos .- w.sp dot(v1, n) end #################################################### ## Initial Conditions #################################################### """ cellsize(bd) Return the delimiters `xmin, ymin, xmax, ymax` of the given obstacle/billiard. Used in `randominside()`, error checking and plotting. """ function cellsize(d::Circular{T}) where {T} xmin = ymin = T(Inf) xmax = ymax = T(-Inf) return xmin, ymin, xmax, ymax end function cellsize(w::Wall) xmin = min(w.sp[1], w.ep[1]) xmax = max(w.sp[1], w.ep[1]) ymin = min(w.sp[2], w.ep[2]) ymax = max(w.sp[2], w.ep[2]) return xmin, ymin, xmax, ymax end function cellsize(a::Antidot{T}) where {T} if a.pflag xmin = ymin = T(Inf) xmax = ymax = T(-Inf) else xmin, ymin = a.c .- a.r xmax, ymax = a.c .+ a.r end return xmin, ymin, xmax, ymax end function cellsize(e::Ellipse{T}) where {T} if e.pflag xmin = ymin = T(Inf) xmax = ymax = T(-Inf) else xmin = e.c[1] .- e.a; ymin = e.c[2] .- e.b xmax = e.c[1] .+ e.a; ymax = e.c[2] .+ e.b end return xmin, ymin, xmax, ymax end function cellsize(a::Semicircle{T}) where {T} xmin, ymin = a.c .- a.r xmax, ymax = a.c .+ a.r return xmin, ymin, xmax, ymax end #################################################### ## Translations #################################################### """ translate(obst::Obstacle, vector) Create a copy of the given obstacle with its position translated by `vector`. """ function translate end for T in subtypes(Circular) @eval translate(d::$T, vec) = ($T)(d.c + vec, d.r) end for T in subtypes(Wall) @eval translate(w::$T, vec) = ($T)(w.sp + vec, w.ep + vec, w.normal) end translate(e::Ellipse, vec) = Ellipse(e.c + vec, e.a, e.b)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
5333
export AbstractParticle, Particle, MagneticParticle, particlebeam #################################################### ## Particle #################################################### """ AbstractParticle Particle supertype. """ abstract type AbstractParticle{T<:AbstractFloat} end eltype(p::AbstractParticle{T}) where {T} = T """ ```julia Particle(ic::Vector{T}) #where ic = [x0, y0, φ0] Particle(x0, y0, φ0) Particle(pos::SVector, vel::SVector) ``` Create a particle with initial conditions `x0, y0, φ0`. It propagates as a straight line. The field `current_cell` shows at which cell of a periodic billiard is the particle currently located. """ mutable struct Particle{T<:AbstractFloat} <: AbstractParticle{T} pos::SVector{2,T} vel::SVector{2,T} current_cell::SVector{2,T} function Particle( pos::SVector{2,T}, vel::SVector{2,T}, cc::SVector{2,T}) where{T<:AbstractFloat} new{T}(pos, normalize(vel), cc) end end Base.copy(p::Particle) = Particle(p.pos, p.vel, p.current_cell) function Particle(ic::AbstractVector{S}) where {S<:Real} T = S<:Integer ? Float64 : S φ0 = ic[3] pos = SVector{2,T}(ic[1:2]); vel = SVector{2,T}(cossin(φ0)...) return Particle(pos, vel, SVector{2,T}(0,0)) end Particle(x::Real, y::Real, φ::Real) = Particle(collect(promote(x,y,φ))) Particle() = Particle(rand(), rand(), rand()*2π) function Particle(pos::SV{T}, vel::SV{T}) where {T} S = T<:Integer ? Float64 : T return Particle(pos, vel, SVector{2,S}(0.0, 0.0)) end show(io::IO, p::Particle{T}) where {T} = print(io, "Particle{$T}\n", "position: $(p.pos+p.current_cell)\nvelocity: $(p.vel)") #################################################### ## MagneticParticle #################################################### """ ```julia MagneticParticle(ic::AbstractVector{T}, ω::Real) # where ic = [x0, y0, φ0] MagneticParticle(x0, y0, φ0, ω) MagneticParticle(pos::SVector, vel::SVector, ω) MagneticParticle(p::AbstractParticle, ω) ``` Create a *magnetic* particle with initial conditions `x0, y0, φ0` and angular velocity `ω`. It propagates as a circle instead of a line, with radius `1/abs(ω)`. The field `current_cell` shows at which cell of a periodic billiard is the particle currently located. """ mutable struct MagneticParticle{T<:AbstractFloat} <: AbstractParticle{T} pos::SVector{2,T} vel::SVector{2,T} current_cell::SVector{2,T} omega::T r::T center::SVector{2, T} function MagneticParticle(pos::SVector{2,T}, vel::SVector{2,T}, current_cell::SVector{2,T}, ω::T) where {T<:AbstractFloat} if ω==0 throw(ArgumentError("Angular velocity of magnetic particle cannot be 0.")) end r = 1/ω c::SV{T} = pos - r*SV{T}(vel[2], -vel[1]) new{T}(pos, normalize(vel), current_cell, ω, abs(1/ω), c) end end ismagnetic(x) = false ismagnetic(x::MagneticParticle) = true function Base.getproperty(p::MagneticParticle, s::Symbol) if s == :ω return Base.getfield(p, :omega) else return Base.getfield(p, s) end end Base.copy(p::MagneticParticle{T}) where {T} = MagneticParticle(p.pos, p.vel, p.current_cell, p.omega) function MagneticParticle(ic::AbstractVector{T}, ω::Real) where {T<:Real} φ0 = ic[3] S = T<:Integer ? Float64 : T pos = SVector{2,S}(ic[1:2]); vel = SVector{2,S}(cossin(φ0)...) return MagneticParticle(pos, vel, SVector{2,S}(0,0), convert(S,ω)) end function MagneticParticle(x0::Real, y0::Real, φ0::Real, ω::Real) a = collect(promote(x0, y0, φ0, ω)) MagneticParticle(a[1:3], a[4]) end MagneticParticle() = MagneticParticle([rand(), rand(), rand()*2π], 1.0) function MagneticParticle(pos::SV{T}, vel::SV{T}, ω::T) where {T} S = T<:Integer ? Float64 : T return MagneticParticle(pos, vel, SVector{2,S}(0,0), convert(S,ω)) end MagneticParticle(p::AbstractParticle, ω) = MagneticParticle(p.pos, p.vel, p.current_cell, ω) show(io::IO, p::MagneticParticle{T}) where {T} = print(io, "MagneticParticle{$T}\n", "position: $(p.pos+p.current_cell)\nvelocity: $(p.vel)\nang. velocity: $(p.omega)") """ find_cyclotron(p::MagneticParticle) Return the center of cyclotron motion of the particle. """ @inline find_cyclotron(p::MagneticParticle{T}) where {T} = c::SV{T} = p.pos - (1/p.omega)*SV{T}(p.vel[2], -p.vel[1]) @inline cyclotron(p) = p.center, p.r function cyclotron(p, use_cell) pos = use_cell ? p.pos + p.current_cell : p.pos return pos, p.r end #################################################### ## Aux #################################################### """ particlebeam(x0, y0, φ, N, dx, ω = nothing, T = eltype(x0)) → ps Make `N` particles, all with direction `φ`, starting at `x0, y0`. The particles don't all have the same position, but are instead spread by up to `dx` in the direction normal to `φ`. The particle element type is `T`. """ function particlebeam(x0, y0, φ, N, dx, ω = nothing, T = eltype(x0)) n = cossin(φ) if N > 1 xyφs = [ T.((x0 - i*dx*n[2]/N, y0 + i*dx*n[1]/N, φ)) for i in range(-N/2, N/2; length = N) ] elseif N == 1 xyφs = [T.((x0, y0, φ))] else error("must be N ≥ 1") end if isnothing(ω) ps = [Particle(z...) for z in xyφs] else ps = [MagneticParticle(z..., T(ω)) for z in xyφs] end end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
13935
using StaticArrays export billiard_rectangle, billiard_sinai, billiard_polygon, billiard_lorentz, billiard_raysplitting_showcase, billiard_hexagonal_sinai, billiard_bunimovich, billiard_stadium, billiard_mushroom, billiard_logo, billiard_vertices, polygon_vertices #################################################### ## Famous/Standard Billiards #################################################### """ billiard_rectangle(x=1.0, y=1.0; setting = "standard") Return a vector of obstacles that defines a rectangle billiard of size (`x`, `y`). ### Settings * "standard" : Specular reflection occurs during collision. * "periodic" : The walls are `PeriodicWall` type, enforcing periodicity at the boundaries * "random" : The velocity is randomized upon collision. * "ray-splitting" : All obstacles in the billiard allow for ray-splitting. """ function billiard_rectangle(x′ = 1.0, y′ = 1.0; x = x′, y = y′, setting::String = "standard") x = convert(AbstractFloat, x) x, y = promote(x,y) o = typeof(x)(0.0) if setting == "standard" sp = [o,y]; ep = [o, o]; n = [x,o] leftw = InfiniteWall(sp, ep, n, "Left wall") sp = [x,o]; ep = [x, y]; n = [-x,o] rightw = InfiniteWall(sp, ep, n, "Right wall") sp = [x,y]; ep = [o, y]; n = [o,-y] topw = InfiniteWall(sp, ep, n, "Top wall") sp = [o,o]; ep = [x, o]; n = [o,y] botw = InfiniteWall(sp, ep, n, "Bottom wall") elseif setting == "periodic" sp = [o,y]; ep = [o, o]; n = [x,o] leftw = PeriodicWall(sp, ep, n, "Left periodic boundary") sp = [x,o]; ep = [x, y]; n = [-x,o] rightw = PeriodicWall(sp, ep, n, "Right periodic boundary") sp = [x,y]; ep = [o, y]; n = [o,-y] topw = PeriodicWall(sp, ep, n, "Top periodic boundary") sp = [o,o]; ep = [x, o]; n = [o,y] botw = PeriodicWall(sp, ep, n, "Bottom periodic boundary") elseif setting == "random" sp = [o,y]; ep = [o, o]; n = [x,o] leftw = RandomWall(sp, ep, n, "Left random wall") sp = [x,o]; ep = [x, y]; n = [-x,o] rightw = RandomWall(sp, ep, n, "Right random wall") sp = [x,y]; ep = [o, y]; n = [o,-y] topw = RandomWall(sp, ep, n, "Top random wall") sp = [o,o]; ep = [x, o]; n = [o,y] botw = RandomWall(sp, ep, n, "Bottom random wall") elseif setting == "ray-splitting" sp = [o,y]; ep = [o, o]; n = [x,o] leftw = SplitterWall(sp, ep, n, "Left ray-splitting wall") sp = [x,o]; ep = [x, y]; n = [-x,o] rightw = SplitterWall(sp, ep, n, "Right ray-splitting wall") sp = [x,y]; ep = [o, y]; n = [o,-y] topw = SplitterWall(sp, ep, n, "Top ray-splitting wall") sp = [o,o]; ep = [x, o]; n = [o,y] botw = SplitterWall(sp, ep, n, "Bottom ray-splitting wall") else throw(ArgumentError("The given setting=$setting is unknown.")) end return Billiard(botw, rightw, topw, leftw) end """ billiard_sinai(r=0.25, x=1.0, y=1.0; setting = "standard") Return a vector of obstacles that defines a Sinai billiard of size (`x`, `y`) with a disk in its center, of radius `r`. In the periodic case, the system is also known as "Lorentz Gas". ### Settings * "standard" : Specular reflection occurs during collision. * "periodic" : The walls are `PeriodicWall` type, enforcing periodicity at the boundaries * "random" : The velocity is randomized upon collision. * "ray-splitting" : All obstacles in the billiard allow for ray-splitting. """ function billiard_sinai(r′ = 0.25, x′ = 1.0, y′ = 1.0; r = r′, x = x′, y = y′, setting = "standard") if (setting == "periodic") && (r>=x/2 || r>=y/2) es = "Disk radius too big for a periodic Sinai billiard.\n" es*= "Obstacles must not overlap with `PeriodicWall`s." error(es) end r, x, y = promote(r,x,y) bdr = billiard_rectangle(x, y; setting = setting) c = [x/2, y/2] if setting == "random" centerdisk = RandomDisk(c, r, "Random disk") elseif setting == "ray-splitting" centerdisk = Antidot(c, r, "Antidot") else centerdisk = Disk(c, r, "Disk") end return Billiard(centerdisk, bdr...) end """ billiard_lorentz(r=0.25, x=1.0, y=1.0) Alias for `billiard_sinai(r,x,y; setting = "periodic")`. """ billiard_lorentz(r=0.25, x=1.0, y=1.0) = billiard_sinai(r,x,y; setting = "periodic") """ billiard_polygon(n::Int, R, center = [0,0]; setting = "standard") Return a vector of obstacles that defines a regular-polygonal billiard with `n` sides, radius `r` and given `center`. Note: `R` denotes the so-called outer radius, not the inner one. ### Settings * "standard" : Specular reflection occurs during collision. * "periodic" : The walls are `PeriodicWall` type, enforcing periodicity at the boundaries. Only available for `n=4` or `n=6`. * "random" : The velocity is randomized upon collision. """ function billiard_polygon(sides′::Int, r′::Real, center′ = [0,0]; sides::Int = sides′, r = r′, center = center′, setting = "standard") S = typeof(convert(AbstractFloat, r)) bd = Obstacle{S}[] verteces = polygon_vertices(r, sides, center) if setting == "standard" T = InfiniteWall wallname = "wall" elseif setting == "periodic" if sides != 4 && sides != 6 error("Polygonal and periodic billiard can exist only for `n=4` or `n=6`") end T = PeriodicWall wallname = "periodic wall" inr = S(r*cos(π/sides)) elseif setting == "random" T = RandomWall wallname = "random wall" end for i in eachindex(verteces) starting = verteces[i] ending = verteces[mod1(i+1, sides)] # Normal vector must look at where the particle is coming from w = ending - starting if setting == "periodic" normal = 2inr*normalize([-w[2], w[1]]) wall = T(starting, ending, normal, wallname*" $i") else normal = [-w[2], w[1]] wall = T(starting, ending, normal, wallname*" $i") end push!(bd, wall) end return Billiard(bd) end """ polygon_vertices(r, sides, center = [0, 0], θ=0) -> v Return the vertices that define a regular polygon with `sides` sides and radius `r`, centered at `center`. Optionally rotate by `θ` degrees. """ function polygon_vertices(r, sides, center = [0, 0.0], θ = 0) S = typeof(convert(AbstractFloat, r)) [S[r*cos(θ + 2π*i/sides), r*sin(θ + 2π*i/sides)] .+ center for i in 1:sides] end """ billiard_hexagonal_sinai(r, R, center = [0,0]; setting = "standard") Create a sinai-like billiard, which is a hexagon of outer radius `R`, containing at its center (given by `center`) a disk of radius `r`. The `setting` keyword is passed to `billiard_polygon`. """ function billiard_hexagonal_sinai(r′::Real = 0.5, R′::Real = 1.0, center′ = [0,0]; r = r′, R = R′, center = center′, setting = "standard") r, R = promote(r, R) T = typeof(r); center = T[center...] bdr = billiard_polygon(6, R, center; setting = setting) DT = setting == "random" ? RandomDisk : Disk return Billiard(Disk(center, r), bdr...) end """ billiard_raysplitting_showcase(x=2.0, y=1.0, r1=0.3, r2=0.2) -> bd, rayspl Showcase example billiard for ray-splitting processes. A rectangle `(x,y)` with a SplitterWall at `x/2` and two disks at each side, with respective radii `r1`, `r2`. **Notice**: This function returns a billiard `bd` as well as a `rayspl` dictionary! """ function billiard_raysplitting_showcase(x=2.0, y=1.0, r1=0.3, r2=0.2) r1≥x/4 || r2≥x/4 && throw(ArgumentError("Disks overlap with walls!")) bdr = billiard_rectangle(x, y) sw = SplitterWall([x/2, 0.0], [x/2,y], [-1,0], true) a1 = Antidot([x/4, y/2], r1, "Left Antidot") a2 = Antidot([3x/4, y/2], r2, "Right Antidot") sa = (φ, pflag, ω) -> pflag ? 0.5φ : 2.0φ Tp = (p) -> (φ, pflag, ω) -> begin if pflag p*exp(-(φ)^2/2(π/8)^2) else abs(φ) < π/4 ? (1-p)*exp(-(φ)^2/2(π/4)^2) : 0.0 end end newoantidot = ((x, bool) -> bool ? -0.5x : -2.0x) newowall = ((x, bool) -> bool ? 0.5x : 2.0x) # I Need 3 ray-splitters because I want different affect for # different antidots raywall = RaySplitter([3], Tp(0.5), sa, newowall) raya = RaySplitter([1, 2], Tp(0.64), sa, newoantidot) return Billiard(a1, a2, sw, bdr...), (raywall, raya) end """ billiard_mushroom(sl = 1.0, sw = 0.2, cr = 1.0, sloc = 0.0; door = true) Create a mushroom billiard with stem length `sl`, stem width `sw` and cap radius `cr`. The center of the cap (which is Semicircle) is always at `[0, sl]`. The center of the stem is located at `sloc`. Optionally, the bottom-most `Wall` is a `Door` (see [`escapetime`](@ref)). """ function billiard_mushroom(stem_length = 1.0, stem_width=0.2, cap_radious=1.0, stem_location = 0.0; sl = stem_length, sw = stem_width, cr = cap_radious, sloc = stem_location, door = true) abs(sloc) + sw/2 > cr && error("Stem is outside the mushroom cap!") sl, sw, cr, sloc = promote(sl, sw, cr, sloc) T = eltype(sl) leftcorn = SV(-sw/2 + sloc, 0) rightcorn = SV(sw/2 + sloc, 0) upleftcorn = SV(-sw/2 + sloc, sl) uprightcorn = SV(sw/2 + sloc, sl) stembot = FiniteWall(leftcorn, rightcorn, SV(0, sw), door, "Stem bottom") stemleft = FiniteWall(upleftcorn, leftcorn, SV(sw, 0), false, "Stem left") stemright = FiniteWall(rightcorn, uprightcorn, SV(-sw, 0), false, "Stem right") farleft = SV(-cr, sl) farright = SV(cr, sl) capbotleft = FiniteWall( farleft, upleftcorn, SV(0, sw), false, "Cap bottom left") capbotright = FiniteWall( uprightcorn, farright, SV(0, sw), false, "Cap bottom right") cap = Semicircle([0, sl], cr, [0, -T(1.0)], "Mushroom cap") return Billiard(stembot, stemright, capbotright, cap, capbotleft, stemleft) end """ billiard_bunimovich(l=1.0, w=1.0) Return a vector of `Obstacle`s that define a Buminovich billiard, also called a stadium. The length is considered *without* the attached semicircles, meaning that the full length of the billiard is `l + w`. The left and right edges of the stadium are [`Semicircle`](@ref)s. `billiard_stadium` is an alias of `billiard_bunimovich`. """ function billiard_bunimovich(l′=1.0, w′=1.0; l = l′, w = w′) l = convert(AbstractFloat, l) l, w = promote(l,w) o = typeof(l)(0.0) bw = InfiniteWall([o,o], [l,o], [o, w], "Bottom wall") tw = InfiniteWall([l,w], [o,w], [o, -w], "Top wall") leftc = Semicircle([o, w/2], w/2, [l, o], "Left semicircle") rightc = Semicircle([l, w/2], w/2, [-l, o], "Right semicircle") return Billiard(bw, rightc, tw, leftc) end billiard_stadium = billiard_bunimovich """ billiard_logo(;h=1.0, α=0.8, r=0.18, off=0.25, T = Float64) -> bd, ray Create the billiard used as logo of `DynamicalBilliards` and return it along with the tuple of raysplitters. """ function billiard_logo(;h=1.0, α=0.8, r=0.18, off=0.25, T = Float64) cos6 = cos(π/6) β = (h - cos6*α)/cos6 t = α + 2β (α, r, h, off, cos6, β, t) = T.((α, r, h, off, cos6, β, t)) center_of_mass = T[0.0, √3*t/6] startloc = T[-α/2, 0.0] # create directions of the hexagonal 6: hexvert = [T.((cos(2π*i/6), sin(2π*i/6))) for i in 1:6] dirs = [SVector{2}(hexvert[i] .- hexvert[mod1(i+1, 6)]) for i in 1:6] frame = Obstacle{T}[] sp = startloc ep = startloc + α*dirs[1] normal = (w = ep .- sp; [-w[2], w[1]]) push!(frame, InfiniteWall(sp, ep, normal, "frame 1")) for i in 2:6 s = iseven(i) ? β : α WT = InfiniteWall #iseven(i) ? RandomWall : InfiniteWall sp = frame[i-1].ep ep = sp + s*dirs[i] normal = (w = ep .- sp; [-w[2], w[1]]) push!(frame, WT(sp, ep, normal, "frame $(i)")) end # Radii of circles that compose the Julia logo offset = T[0.0, off] R = T[cos(2π/3) -sin(2π/3); sin(2π/3) cos(2π/3)] green = Disk(center_of_mass .+ offset, r, "green") red = Antidot(center_of_mass .+ R*offset, r, "red") purple = RandomDisk(center_of_mass .+ R*R*offset, r, "purple") bd = Billiard(green, red, purple, frame...) # %% Raysplitting functions for the red circle: refraction = (φ, pflag, ω) -> pflag ? 0.5φ : 2.0φ transmission_p = (p) -> (φ, pflag, ω) -> begin if pflag p*exp(-(φ)^2/2(π/8)^2) else abs(φ) < π/4 ? (1-p)*exp(-(φ)^2/2(π/4)^2) : 0.0 end end newoantidot = ((x, bool) -> bool ? -2.0x : -0.5x) raya = RaySplitter([2], transmission_p(0.8), refraction, newoantidot) return bd, raya end export billiard_iris """ billiard_iris(a=0.2, b=0.4, w=1.0; setting = "standard") Return a billiard that is a square of side `w` enclosing at its center an ellipse with semi axes `a`, `b`. """ function billiard_iris(a′ = 0.2, b′ = 0.4, w′ = 1.0; setting = "standard", a = a′, b = b′, w = w′) rec = billiard_rectangle(w, w; setting = setting) e = Ellipse([w/2, w/2], a, b, true, "Ellipse") return Billiard(e, rec.obstacles...) end """ billiard_vertices(v, type = FiniteWall) Construct a polygon billiard that connects the given vertices `v` (vector of 2-vectors). The vertices should construct a billiard in a counter-clockwise orientation (i.e. the normal vector always points to the left of `v[i+1] - v[i]`.). `type` decides what kind of walls to use. Ths function assumes that the first entry of `v` should be connected with the last. """ function billiard_vertices(vertices, type = FiniteWall) @assert vertices[end] != vertices[1] obs = type[] for i in 1:length(vertices)-1 sp, ep = vertices[i], vertices[i+1] push!(obs, type(sp, ep)) end sp, ep = vertices[end], vertices[1] push!(obs, type(sp, ep)) return Billiard(obs) end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
7117
export to_bcoords, from_bcoords, arcintervals, totallength export boundarymap ####################################################################################### ## Arclengths ####################################################################################### """ totallength(o::Obstacle) Return the total boundary length of `o`. """ @inline totallength(o::Wall) = norm(o.ep - o.sp) @inline totallength(o::Semicircle) = π*o.r @inline totallength(o::Circular) = 2π*o.r @inline totallength(e::Ellipse) = 4e.arc @inline totallength(bd::Billiard) = sum(totallength(x) for x in bd.obstacles) """ arcintervals(bd::Billiard) -> s Generate a vector `s`, with entries being the delimiters of the arclengths of the obstacles of the billiard. The arclength from `s[i]` to `s[i+1]` is the arclength spanned by the `i`th obstacle. `s` is used to transform an arc-coordinate `ξ` from local to global and vice-versa. A local `ξ` becomes global by adding `s[i]` (where `i` is the index of current obstacle). A global `ξ` becomes local by subtracting `s[i]`. See also [`boundarymap`](@ref), [`to_bcoords`](@ref), [`from_bcoords`](@ref). """ function arcintervals(bd::Billiard{T, D}) where {T, D} intervals = SVector{D+1,T}(0, map(x->totallength(x), bd.obstacles)...) return cumsum(intervals) end ################################################################################ ## Coordinate systems ################################################################################ """ to_bcoords(pos, vel, o::Obstacle) -> ξ, sφ Convert the real coordinates `pos, vel` to boundary coordinates (also known as Birkhoff coordinates) `ξ, sφ`, assuming that `pos` is on the obstacle. `ξ` is the arc-coordinate, i.e. it parameterizes the arclength of the obstacle. `sφ` is the sine of the angle between the velocity vector and the vector normal to the obstacle. The arc-coordinate `ξ` is measured as: * the distance from start point to end point in `Wall`s * the arc length measured counterclockwise from the open face in `Semicircle`s * the arc length measured counterclockwise from the rightmost point in `Circular`/`Ellipse`s Notice that this function returns the *local* arclength. To get the global arclength parameterizing an entire billiard, simply do `ξ += arcintervals(bd)[i]` if the index of obstacle `o` is `i`. See also [`from_bcoords`](@ref), which is the inverse function. """ to_bcoords(p::AbstractParticle, o::Obstacle) = to_bcoords(p.pos, p.vel, o) function to_bcoords(pos::SV, vel::SV, o::Obstacle) n = normalvec(o, pos) sinφ = cross2D(vel, n) ξ = _ξ(pos, o) return ξ, sinφ end # Internal function ξ is simply returning the boundary "arc-coordinate" _ξ(pos::SV, o::Wall) = norm(pos - o.sp) function _ξ(pos::SV{T}, o::Semicircle{T}) where {T<:AbstractFloat} #project pos on open face chrd = SV{T}(-o.facedir[2],o.facedir[1]) d = (pos - o.c)/o.r x = dot(d, chrd) r = acos(clamp(x, -1, 1))*o.r return r end function _ξ(pos::SV{T}, o::Circular{T}) where {T<:AbstractFloat} d = (pos - o.c)/o.r if d[2] > 0 r = acos(clamp(d[1], -1, 1)) else r = π + acos(-clamp(d[1], -1, 1)) end return r*o.r end function _ξ(pos::SV{T}, o::Ellipse{T}) where {T<:AbstractFloat} θ = atan(pos[2] - o.c[2], pos[1] - o.c[1]) + π return ellipse_arclength(θ, o) end """ from_bcoords(ξ, sφ, o::Obstacle) -> pos, vel Convert the boundary coordinates `ξ, sφ` on the obstacle to real coordinates `pos, vel`. Note that `vel` always points away from the obstacle. This function is the inverse of [`to_bcoords`](@ref). """ function from_bcoords(ξ::T, sφ::T, o::Obstacle{T}) where {T} pos = real_pos(ξ, o) cφ = sqrt(1-sφ^2) # = cos(asin(sφ)) n = normalvec(o, pos) vel = SV{T}(n[1]*cφ + n[2]*sφ, -n[1]*sφ + n[2]*cφ) return pos, vel end """ real_pos(ξ, o::Obstacle) Converts the arclength coordinate `ξ` relative to the obstacle `o` into a real space position vector. """ real_pos(ξ, o::Wall) = o.sp + ξ*normalize(o.ep - o.sp) function real_pos(ξ, o::Semicircle{T}) where T sξ, cξ = sincos(ξ/o.r) chrd = SV{T}(-o.facedir[2], o.facedir[1]) return o.c - o.r*(sξ*o.facedir - cξ*chrd) end real_pos(ξ, o::Circular{T}) where T = o.c .+ o.r * SV{T}(cossin(ξ/o.r)) function real_pos(ξ, o::Ellipse{T}) where T error("`from_bcoords` is not implemented for Ellipse. If you know of a way "* "to find a point (2-vector) on an ellipse given an arclength ξ, please let us know!") return nothing end """ from_bcoords(ξ, sφ, bd::Billiard, intervals = arcintervals(bd)) Same as above, but now `ξ` is considered to be the global arclength, parameterizing the entire billiard, instead of a single obstacle. """ function from_bcoords(ξ, sφ, bd::Billiard{T}, intervals = arcintervals(bd)) where T for (i, obst) ∈ enumerate(bd) if ξ <= intervals[i+1] pos, vel = from_bcoords(ξ - intervals[i], sφ, obst) return pos, vel, i end end throw(DomainError(ξ ,"ξ is too large for this billiard!")) end ####################################################################################### ## Boundary Map ####################################################################################### """ boundarymap(p, bd, t [,intervals]) → bmap, arclengths Compute the boundary map of the particle `p` in the billiard `bd` by evolving the particle for total amount `t` (either float for time or integer for collision number). Return a vector of 2-vectors `bmap` and also `arclengths(bd)`. The first entry of each element of `bmap` is the arc-coordinate at collisions ``\\xi``, while the second is the sine of incidence angle ``\\sin(\\phi_n)``. The measurement direction of the arclengths of the individual obstacles is dictated by their order in `bd`. The sine of the angle is computed *after* specular reflection has taken place. The returned values of this function can be used in conjuction with the function [`bdplot_boundarymap`](@ref) (requires `using PyPlot`) to plot the boundary map in an intuitive way. *Notice* - this function only works for normal specular reflection. Random reflections or ray-splitting will give unexpected results. See also [`to_bcoords`](@ref), [`boundarymap_portion`](@ref). See [`parallelize`](@ref) for a parallelized version. """ function boundarymap(par::AbstractParticle{T}, bd::Billiard{T}, t, intervals = arcintervals(bd)) where {T} p = copy(par) bmap = SV{T}[] if typeof(t) == Int sizehint!(bmap, t) end count = zero(t); t_to_write = zero(T) while count < t i, tmin = bounce!(p,bd) t_to_write += tmin if isperiodic(i, bd) continue # do not write output if collision with with PeriodicWall else ξ, sφ = to_bcoords(p, bd[i]) @inbounds push!(bmap, SV{T}(ξ + intervals[i], sφ)) # set counter count += increment_counter(t, t_to_write) t_to_write = zero(T) end end #time, or collision number, loop return bmap, intervals end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
3883
################################################################################ ## ## This file contains boxcounting methods to analyse phase space volume ## ratios in 2D billiard maps and 3D billiard flows. ## ################################################################################ export boundarymap_portion, phasespace_portion ####################################################################################### ## Boundary Map Portion ####################################################################################### """ boundarymap_portion(bd::Billiard, t, p::AbstractParticle, δξ, δφ = δξ) Calculate the portion of the boundary map of the billiard `bd` covered by the particle `p` when it is evolved for time `t` (float or integer). Notice that the The boundary map is partitioned into boxes of size `(δξ, δφ)` and as the particle evolves visited boxes are counted. The returned ratio is this count divided by the total boxes of size `(δξ, δφ)` needed to cover the boundary map. **Important:** This portion **does not** equate the portion the particle's orbit covers on the full, three dimensional phase space. Use the function [`phasespace_portion`](@ref) for that! """ function boundarymap_portion(bd::Billiard{T}, t, par::AbstractParticle{T}, δξ, δφ = δξ; intervals = arcintervals(bd)) where {T} p = copy(par) count = zero(T) t_to_write = zero(T) d = Dict{SV{Int}, Int}() while count < t i, tmin = bounce!(p,bd) t_to_write += tmin if typeof(bd[i]) <: PeriodicWall continue # do not write output if collision with with PeriodicWall else ξ, sφ = to_bcoords(p, bd[i]) ξ += intervals[i] ind = SV{Int}(floor(Int, ξ/δξ), floor(Int, (sφ + 1)/δφ)) d[ind] = get(d, ind, 0) + 1 count += increment_counter(t, t_to_write) t_to_write = zero(T) end end #time or collision number loop total_boxes = ceil(Int, totallength(bd)/δξ) * ceil(Int, 2/δφ) ratio = length(keys(d))/total_boxes return ratio, d end ####################################################################################### ## Phase Space Portion ####################################################################################### """ phasespace_portion(bd::Billiard, t, p::AbstractParticle, δξ, δφ = δξ) Calculate the portion of the phase space of the billiard `bd` covered by the particle `p` when it is evolved for time `t` (float or integer). This function extends [`boundarymap_portion`](@ref) using a novel approach. For each visited box of the boundary map, [`bounce!`](@ref) attributes a third dimension (the collision time, equal to collision distance) which expands the two dimensions of the boundary map to the three dimensions of the phase space. The true phase space portion is then the weighted portion of boxes visited by the particle, divided by the total weighted sum of boxes. The weights of the boxes are the collision times. """ function phasespace_portion(bd::Billiard{T}, t, par::AbstractParticle{T}, δξ, δφ = δξ) where {T} r, dict = boundarymap_portion(bd, t, par, δξ, δφ, intervals = arcintervals(bd)) ints = arcintervals(bd) maxξ = ceil(Int, totallength(bd)/δξ) maxφ = ceil(Int, 2/δφ) dummy = copy(par) total = zero(T); visited = zero(T) for ξcell ∈ 1:maxξ-1, φcell ∈ 1:maxφ-1 #get center position ξc = (ξcell - 0.5)*δξ φc = (φcell - 0.5)*δφ - 1 pos, vel, i = from_bcoords(ξc, φc, bd, ints) dummy.pos = pos dummy.vel = vel _, τ = next_collision(dummy,bd) total += τ (haskey(dict, SV{Int64}(ξcell, φcell))) && (visited += τ) end return visited/total end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
11513
export collision, next_collision ##################################################################################### # Accuracy & Convenience Functions ##################################################################################### """ Approximate arccos(1 - x) for x very close to 0. """ @inline (acos1mx(x::T)::T) where {T} = sqrt(2x) + sqrt(x)^3/sixsqrt const sixsqrt = 6sqrt(2) @inline cross2D(a, b) = a[1]*b[2] - a[2]*b[1] @inline accuracy(::Type{T}) where {T} = sqrt(eps(T)) @inline accuracy(::Type{BigFloat}) = BigFloat(1e-32) @inline nocollision(::Type{T}) where {T} = (T(Inf), SV{T}(0.0, 0.0)) ####################################################################################### ## Particle ####################################################################################### """ collision(p::AbstractParticle, o::Obstacle) → t, cp Find the collision (if any) between given particle and obstacle. Return the time until collision and the estimated collision point `cp`. Return `Inf, SV(0, 0)` if the collision is not possible *or* if the collision happens backwards in time. **It is the duty of `collision` to avoid incorrect collisions when the particle is on top of the obstacle (or very close).** """ function collision(p::Particle{T}, w::Wall{T}) where {T} n = normalvec(w, p.pos) denom = dot(p.vel, n) if denom ≥ 0.0 return nocollision(T) else t = dot(w.sp - p.pos, n)/denom return t, p.pos + t*p.vel end end function collision(p::Particle{T}, w::Union{FiniteWall{T}, FiniteSplitterWall{T}}) where {T} n = normalvec(w, p.pos) denom = dot(p.vel, n) # case of velocity pointing away of wall: denom ≥ 0.0 && return nocollision(T) posdot = dot(w.sp-p.pos, n) # Case of particle starting behind finite wall: posdot ≥ 0.0 && return nocollision(T) colt = posdot/denom i = p.pos + colt * p.vel dfc = norm(i - w.center) if dfc > w.width/2 return nocollision(T) else return colt, i end end function collision(p::Particle{T}, d::Circular{T}) where {T} dotp = dot(p.vel, normalvec(d, p.pos)) dotp ≥ 0.0 && return nocollision(T) dc = p.pos - d.c B = dot(p.vel, dc) #pointing towards circle center: B < 0 C = dot(dc, dc) - d.r*d.r #being outside of circle: C > 0 Δ = B*B - C Δ ≤ 0.0 && return nocollision(T) sqrtD = sqrt(Δ) # Closest point: t = -B - sqrtD return t, p.pos + t*p.vel end function collision(p::Particle{T}, d::Antidot{T}) where {T} dotp = dot(p.vel, normalvec(d, p.pos)) if d.pflag == true dotp ≥ 0 && return nocollision(T) end dc = p.pos - d.c B = dot(p.vel, dc) #velocity towards circle center: B < 0 C = dot(dc, dc) - d.r*d.r #being outside of circle: C > 0 Δ = B^2 - C Δ ≤ 0 && return nocollision(T) sqrtD = sqrt(Δ) # Closest point (may be in negative time): if dotp < 0 t = -B - sqrtD else t = -B + sqrtD end t ≤ 0.0 ? nocollision(T) : (t, p.pos + t*p.vel) end function collision(p::Particle{T}, d::Semicircle{T}) where {T} dc = p.pos - d.c B = dot(p.vel, dc) #velocity towards circle center: B > 0 C = dot(dc, dc) - d.r*d.r #being outside of circle: C > 0 Δ = B^2 - C Δ ≤ 0 && return nocollision(T) sqrtD = sqrt(Δ) nn = dot(dc, d.facedir) if nn ≥ 0 # I am NOT inside semicircle # Return most positive time t = -B + sqrtD else # I am inside semicircle: t = -B - sqrtD # these lines make sure that the code works for ANY starting position: if t ≤ 0 || distance(p, d) ≤ accuracy(T) t = -B + sqrtD end end # This check is necessary to not collide with the non-existing side newpos = p.pos + p.vel * t if dot(newpos - d.c, d.facedir) ≥ 0 # collision point on BAD HALF; return nocollision(T) end # If collision time is negative, return Inf: t ≤ 0.0 ? nocollision(T) : (t, p.pos + t*p.vel) end function collision(p::Particle{T}, e::Ellipse{T}) where {T} # First check if particle is "looking at" eclipse if it is outside if e.pflag # These lines may be "not accurate enough" but so far all is good dotp = dot(p.vel, normalvec(e, p.pos)) dotp ≥ 0.0 && return nocollision(T) end # http://www.ambrsoft.com/TrigoCalc/Circles2/Ellipse/EllipseLine.htm a = e.a; b = e.b # Translate particle with ellipse center (so that ellipse lies on [0, 0]) pc = p.pos - e.c # Find μ, ψ for line equation y = μx + ψ describing particle μ = p.vel[2]/p.vel[1] ψ = pc[2] - μ*pc[1] # Determinant and intersection points follow from the link denomin = a*a*μ*μ + b*b Δ² = denomin - ψ*ψ Δ² ≤ 0 && return nocollision(T) Δ = sqrt(Δ²); f1 = -a*a*μ*ψ; f2 = b*b*ψ # just factors I1 = SV(f1 + a*b*Δ, f2 + a*b*μ*Δ)/denomin I2 = SV(f1 - a*b*Δ, f2 - a*b*μ*Δ)/denomin d1 = norm(pc - I1); d2 = norm(pc - I2) if e.pflag return d1 < d2 ? (d1, I1 + e.c) : (d2, I2 + e.c) else # inside the ellipse: one collision is _always_ valid if d1 < d2 dmin, Imin = d1, I1 dmax, Imax = d2, I2 else dmin, Imin = d2, I2 dmax, Imax = d1, I1 end if dmin < accuracy(T) # special case for being very close to ellipse dotp = dot(p.vel, normalvec(e, Imin)) dotp ≥ 0 && return (dmax, Imax + e.c) end # check which of the two points is ahead or behind the obstacle z1 = dot(pc - Imax, p.vel) return z1 < 0 ? (dmax, Imax + e.c) : (dmin, Imin + e.c) end end ####################################################################################### ## Magnetic particle ####################################################################################### function collision(p::MagneticParticle{T}, w::Wall{T}) where {T} ω = p.omega pc, pr = cyclotron(p) P0 = p.pos P2P1 = w.ep - w.sp P1P3 = w.sp - pc # Solve quadratic: a = dot(P2P1, P2P1) b = 2*dot(P2P1, P1P3) c = dot(P1P3, P1P3) - pr*pr Δ = b^2 -4*a*c # Check if line is completely outside (or tangent) of the circle: Δ ≤ 0.0 && return nocollision(T) # Intersection coefficients: u1 = (-b - sqrt(Δ))/2a u2 = (-b + sqrt(Δ))/2a cond1 = 0.0 ≤ u1 ≤ 1.0 cond2 = 0.0 ≤ u2 ≤ 1.0 # Check if the line (wall) is completely inside the circle: θ, I = nocollision(T) if cond1 || cond2 dw = w.ep - w.sp for (u, cond) in ((u1, cond1), (u2, cond2)) Y = w.sp + u*dw if cond φ = realangle(p, w, Y) φ < θ && (θ = φ; I = Y) end end end # Collision time = arc-length until collision point return θ*pr, I end function collision(p::MagneticParticle{T}, o::Circular{T}) where {T} ω = p.omega pc, rc = cyclotron(p) p1 = o.c r1 = o.r d = norm(p1-pc) if (d >= rc + r1) || (d <= abs(rc-r1)) return nocollision(T) end # Solve quadratic: a = (rc^2 - r1^2 + d^2)/2d h = sqrt(rc^2 - a^2) # Collision points (always 2): I1 = SVector{2, T}( pc[1] + a*(p1[1] - pc[1])/d + h*(p1[2] - pc[2])/d, pc[2] + a*(p1[2] - pc[2])/d - h*(p1[1] - pc[1])/d ) I2 = SVector{2, T}( pc[1] + a*(p1[1] - pc[1])/d - h*(p1[2] - pc[2])/d, pc[2] + a*(p1[2] - pc[2])/d + h*(p1[1] - pc[1])/d ) # Calculate real time until intersection: θ1 = realangle(p, o, I1) θ2 = realangle(p, o, I2) # Collision time, equiv. to arc-length until collision point: return θ1 < θ2 ? (θ1*rc, I1) : (θ2*rc, I2) end function collision(p::MagneticParticle{T}, o::Semicircle{T}) where {T} ω = p.omega pc, rc = cyclotron(p) p1 = o.c r1 = o.r d = norm(p1-pc) if (d >= rc + r1) || (d <= abs(rc-r1)) return nocollision(T) end # Solve quadratic: a = (rc^2 - r1^2 + d^2)/2d h = sqrt(rc^2 - a^2) # Collision points (always 2): I1 = SVector{2, T}( pc[1] + a*(p1[1] - pc[1])/d + h*(p1[2] - pc[2])/d, pc[2] + a*(p1[2] - pc[2])/d - h*(p1[1] - pc[1])/d ) I2 = SVector{2, T}( pc[1] + a*(p1[1] - pc[1])/d - h*(p1[2] - pc[2])/d, pc[2] + a*(p1[2] - pc[2])/d + h*(p1[1] - pc[1])/d ) # Only consider intersections on the "correct" side of Semicircle: cond1 = dot(I1-o.c, o.facedir) < 0 cond2 = dot(I2-o.c, o.facedir) < 0 # Collision time, equiv. to arc-length until collision point: θ, I = nocollision(T) if cond1 || cond2 for (Y, cond) in ((I1, cond1), (I2, cond2)) if cond φ = realangle(p, o, Y) φ < θ && (θ = φ; I = Y) end end end # Collision time = arc-length until collision point return θ*rc, I end collision(p::MagneticParticle, e::Ellipse) = error( "Magnetic propagation for Ellipse is not supported :( Consider contributing a "* "method to `collision(p::MagneticParticle, e::Ellipse)`!") """ realangle(p::MagneticParticle, o::Obstacle, I) -> θ Given the intersection point `I` of the trajectory of a magnetic particle `p` with some obstacle `o`, find the real angle that will be spanned until the particle collides with the obstacle. The function also takes care of problems that may arise when particles are very close to the obstacle's boundaries, due to floating-point precision. """ function realangle(p::MagneticParticle{T}, o::Obstacle{T}, i::SV{T})::T where {T} pc = p.center; pr = p.r; ω = p.omega P0 = p.pos PC = pc - P0 d2 = dot(i-P0,i-P0) #distance of particle from intersection point # Check dot product for close points: if d2 ≤ accuracy(T)*accuracy(T) dotp = dot(p.vel, normalvec(o, p.pos)) # Case where velocity points away from obstacle: dotp ≥ 0 && return T(Inf) end d2r = (d2/(2pr^2)) d2r > 2 && (d2r = T(2.0)) # Correct angle value for small arguments (between 0 and π/2): θprime = d2r < 1e-3 ? acos1mx(d2r) : acos(1.0 - d2r) # Get "side" of i: PI = i - P0 side = cross2D(PI, PC)*ω # Get angle until i (positive number between 0 and 2π) side < 0 && (θprime = T(2π-θprime)) return θprime end ####################################################################################### ## next_collision ####################################################################################### """ next_collision(p::AbstractParticle, bd::Billiard) -> i, tmin, cp Compute the [`collision`](@ref) across all obstacles in `bd` and find the minimum one. Return the index of colliding obstacle, the time and the collision point. """ function next_collision end @generated function next_collision(p, bd::Billiard{T, L, BT}) where {T, L, BT} out = :(ind = 0; tmin = T(Inf); cp = SV{T}(0.0, 0.0)) for j=1:L push!(out.args, quote let x = bd[$j] tcol, pcol = collision(p, x) # Set minimum time: if tcol < tmin tmin = tcol ind = $j cp = pcol end end end ) end push!(out.args, :(return ind, tmin, cp)) return out end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
5217
export escapetime, meancollisiontime export escapetime!, meancollisiontime! export visited_obstacles, visited_obstacles! """ escapetime([p,] bd, t; warning = false) Calculate the escape time of a particle `p` in the billiard `bd`, which is the time until colliding with any "door" in `bd`. As a "door" is considered any [`FiniteWall`](@ref) with field `isdoor = true`. If the particle evolves for more than `t` (integer or float) without colliding with the `Door` (i.e. escaping) the returned result is `Inf`. A warning can be thrown if the result is `Inf`. Enable this using the keyword `warning = true`. If a particle is not given, a random one is picked through [`randominside`](@ref). See [`parallelize`](@ref) for a parallelized version. """ escapetime(p, bd, t; warning = false) = escapetime!(copy(p), bd, t; warning = warning) escapetime(bd::Billiard, t; kwargs...) = escapetime(randominside(bd), bd, t; kwargs...) function escapetime!(p::AbstractParticle{T}, bd::Billiard{T}, t, raysplitters = nothing; warning::Bool=false)::T where {T<:AbstractFloat} ei = escapeind(bd) if length(ei) == 0 error("""The billiard does not have any "doors"!""") end totalt = zero(T); count = zero(t); t_to_write = zero(T) isray = !isa(raysplitters, Nothing) isray && acceptable_raysplitter(raysplitters, bd) raysidx = raysplit_indices(bd, raysplitters) while count < t i, tmin, pos, vel = bounce!(p, bd, raysidx, raysplitters) t_to_write += tmin if isperiodic(i, bd) continue else totalt += t_to_write i ∈ ei && break # the collision happens with a Door! # set counter count += increment_counter(t, t_to_write) t_to_write = zero(T) end end#time, or collision number, loop if count ≥ t warning && warn("Particle did not escape within max-iter window.") return T(Inf) end return totalt end function escapeind(bd) j = Int[] for (i, obst) in enumerate(bd) if typeof(obst) <: FiniteWall && obst.isdoor == true push!(j, i) end end return j end """ meancollisiontime([p,] bd, t) → κ Compute the mean collision time `κ` of the particle `p` in the billiard `bd` by evolving for total amount `t` (either float for time or integer for collision number). Collision times are counted only between obstacles that are *not* [`PeriodicWall`](@ref). If a particle is not given, a random one is picked through [`randominside`](@ref). See [`parallelize`](@ref) for a parallelized version. """ meancollisiontime(p, bd, t) = meancollisiontime!(copy(p), bd, t) meancollisiontime(bd::Billiard, t) = meancollisiontime(randominside(bd), bd, t) function meancollisiontime!(p::AbstractParticle{T}, bd::Billiard{T}, t)::T where {T} ispinned(p, bd) && return Inf ismagnetic = typeof(p) <: MagneticParticle ismagnetic && (absω = abs(p.omega)) tmin, i = next_collision(p, bd) tmin == Inf && return Inf κ = zero(T); count = zero(t); t_to_write = zero(T); colcount = 0 while count < t i, tmin, pos, vel = bounce!(p, bd) t_to_write += tmin if isperiodic(bd) && i ∈ bd.peridx continue else κ += t_to_write colcount += 1 # set counter count += increment_counter(t, t_to_write) t_to_write = zero(T) end end return κ/colcount end """ visited_obstacles(p, args...) Same as [`visited_obstacles!`](@ref) but copies the particle instead. """ visited_obstacles(p::AbstractParticle, args...) = visited_obstacles!(copy(p), args...) visited_obstacles(bd::Billiard, args...; kwargs...) = visited_obstacles!(randominside(bd), bd, args...; kwargs...) """ visited_obstacles!([p::AbstractParticle,] bd::Billiard, t) Evolve the given particle `p` inside the billiard `bd` exactly like [`evolve!`](@ref). However return only: * `ts::Vector{T}` : Vector of time points of when each collision occured. * `obst::Vector{Int}` : Vector of obstacle indices in `bd` that the particle collided with at the time points in `ts`. The first entries are `0.0` and `0`. Similarly with [`evolve!`](@ref) the function does not record collisions with periodic walls. Currently does not support raysplitting. Returns empty arrays for pinned particles. """ function visited_obstacles!( p::AbstractParticle{T}, bd::Billiard{T}, t) where {T<:AbstractFloat} if t ≤ 0 throw(ArgumentError("cannot evolve backwards in time.")) end if ispinned(p, bd) return T[], Int[] end ts = T[0.0]; obst = Int[0] count = zero(t); t_to_write = zero(T) if typeof(t) == Int for zzz in (ts, obst) sizehint!(zzz, t) end end while count < t i, tmin, pos, vel = bounce!(p, bd) t_to_write += tmin if isperiodic(i, bd) continue else count += increment_counter(t, tmin) push!(ts, t_to_write + ts[end]); push!(obst, i) t_to_write = zero(T) end end#time, or collision number, loop return ts, obst end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
6940
export bounce!, ispinned, propagate! @inline increment_counter(::Int, t_to_write) = 1 @inline increment_counter(::T, t_to_write) where {T<:AbstractFloat} = t_to_write ##################################################################################### # Bounce ##################################################################################### """ bounce!(p::AbstractParticle, bd::Billiard) → i, t, pos, vel "Bounce" the particle (advance for one collision) in the billiard. Takes care of finite-precision issues. Return: * index of the obstacle that the particle just collided with * the time from the previous collision until the current collision `t` * position and velocity of the particle at the current collision (*after* the collision has been resolved!). The position is given in the unit cell of periodic billiards. Do `pos += p.current_cell` for the position in real space. ```julia bounce!(p, bd, raysplit) → i, t, pos, vel ``` Ray-splitting version of `bounce!`. """ @inline function bounce!(p::AbstractParticle{T}, bd::Billiard{T}) where {T} i::Int, tmin::T, cp::SV{T} = next_collision(p, bd) if tmin != T(Inf) o = bd[i] relocate!(p, o, tmin, cp) resolvecollision!(p, o) end typeof(p) <: MagneticParticle && (p.center = find_cyclotron(p)) return i, tmin, p.pos, p.vel end ##################################################################################### # Relocate ##################################################################################### """ relocate!(p::AbstractParticle, o::Obstacle, t, cp) Propagate the particle to `cp` and propagate velocities for time `t`. Check if it is on the correct side of the obstacle. If not, change the particle position by [`distance`](@ref) along the [`normalvec`](@ref) of the obstacle. """ function relocate!(p::AbstractParticle{T}, o::Obstacle{T}, tmin::T, cp::SV{T}) where {T} propagate!(p, cp, tmin) # propagate to collision point okay = _correct_pos!(p, o) return okay end function _correct_pos!(p, o) d = distance(p.pos, o) okay = _okay(d, o) if !okay n = normalvec(o, p.pos) p.pos -= d * n # due to finite precision this does not always give positive distance # but collision takes care of it, as it does not care about collisions # very close to the point. end return okay end _okay(d, o::Obstacle) = d ≥ 0.0 _okay(d, o::PeriodicWall) = d ≤ 0.0 """ propagate!(p::AbstractParticle, t) Propagate the particle `p` for given time `t`, changing appropriately the the `p.pos` and `p.vel` fields. propagate!(p, position, t) Do the same, but take advantage of the already calculated `position` that the particle should end up at. """ @inline function propagate!(p::Particle{T}, t::Real) where {T} p.pos += SV{T}(p.vel[1]*t, p.vel[2]*t) end @inline propagate!(p::Particle, newpos::SV, t::Real) = (p.pos = newpos) @inline function propagate!(p::MagneticParticle{T}, t::Real) where {T} ω = p.omega; r = 1/ω φ0 = atan(p.vel[2], p.vel[1]) sinωtφ, cosωtφ = sincos(ω*t + φ0) p.pos += SV{T}((sinωtφ - sin(φ0))*r, (-cosωtφ + cos(φ0))*r) p.vel = SV{T}(cosωtφ, sinωtφ) return end @inline function propagate!( p::MagneticParticle{T}, newpos::SV{T}, t) where {T} ω = p.omega; φ0 = atan(p.vel[2], p.vel[1]) p.pos = newpos p.vel = SV{T}(cossin(ω*t + φ0)) return end ##################################################################################### # Resolve Collisions ##################################################################################### """ specular!(p::AbstractParticle, o::Obstacle) Perform specular reflection based on the normal vector of the Obstacle. In the case where the given obstacle is a `RandomObstacle`, the specular reflection randomizes the velocity instead (within -π/2+ε to π/2-ε of the normal vector). """ @inline function specular!(p::AbstractParticle{T}, o::Obstacle{T})::Nothing where {T} n = normalvec(o, p.pos) p.vel = p.vel - 2*dot(n, p.vel)*n return nothing end @inline function specular!(p::AbstractParticle{T}, r::RandomDisk{T})::Nothing where {T} n = normalvec(r, p.pos) φ = atan(n[2], n[1]) + 0.95(π*rand() - π/2) #this cannot be exactly π/2 p.vel = SVector{2,T}(cos(φ), sin(φ)) return nothing end @inline function specular!(p::AbstractParticle{T}, r::RandomWall{T})::Nothing where {T} n = normalvec(r, p.pos) φ = atan(n[2], n[1]) + 0.95(π*rand() - π/2) #this cannot be exactly π/2 p.vel = SVector{2,T}(cossin(φ)) return nothing end """ periodicity!(p::AbstractParticle, w::PeriodicWall) Perform periodicity conditions of `w` on `p`. """ @inline function periodicity!(p::AbstractParticle, w::PeriodicWall)::Nothing p.pos += w.normal p.current_cell -= w.normal return nothing end @inline function periodicity!(p::MagneticParticle, w::PeriodicWall)::Nothing p.pos += w.normal p.center += w.normal p.current_cell -= w.normal return nothing end """ resolvecollision!(p::AbstractParticle, o::Obstacle) Resolve the collision between particle `p` and obstacle `o`, depending on the type of `o` (do `specular!` or `periodicity!`). resolvecollision!(p, o, T::Function, θ::Function, new_ω::Function) This is the ray-splitting implementation. The three functions given are drawn from the ray-splitting dictionary that is passed directly to `evolve!()`. For a calculated incidence angle φ, if T(φ) > rand(), ray-splitting occurs. """ @inline resolvecollision!(p::Particle, o::Obstacle) = specular!(p, o) @inline resolvecollision!(p::Particle, o::PeriodicWall) = periodicity!(p, o) @inline resolvecollision!(p::MagneticParticle, o::Obstacle) = specular!(p, o) resolvecollision!(p::MagneticParticle, o::PeriodicWall) = periodicity!(p, o) """ ispinned(p::MagneticParticle, bd::Billiard) Return `true` if the particle is pinned with respect to the billiard. Pinned particles either have no valid collisions (go in circles forever) or all their valid collisions are with periodic walls, which again means that they go in cirles for ever. """ ispinned(p::Particle, bd) = false function _reset_ispinned(p, pos, vel, cc) p.pos = pos; p.vel = vel p.current_cell = cc; p.center = find_cyclotron(p) end function ispinned(p::MagneticParticle, bd::Billiard) pos, vel, cc = p.pos, p.vel, p.current_cell i, t = bounce!(p, bd) if t == Inf; _reset_ispinned(p, pos, vel, cc); return true; end if !isperiodic(bd); _reset_ispinned(p, pos, vel, cc); return false; end peridx = bd.peridx if i ∉ peridx; _reset_ispinned(p, pos, vel, cc); return false; end # propagate until 2π/ω counter = t; limit = 2π/abs(p.omega) while counter ≤ limit i, t = bounce!(p, bd) if i ∉ peridx; _reset_ispinned(p, pos, vel, cc); return false; end counter += t end _reset_ispinned(p, pos, vel, cc); return true end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
10365
# This file must be loaded _after_ raysplitting export evolve!, evolve, timeseries!, timeseries """ evolve!([p::AbstractParticle,] bd::Billiard, t) Evolve the given particle `p` inside the billiard `bd`. If `t` is of type `AbstractFloat`, evolve for as much time as `t`. If however `t` is of type `Int`, evolve for as many collisions as `t`. Return the states of the particle between collisions. This function mutates the particle, use `evolve` otherwise. If a particle is not given, a random one is picked through [`randominside`](@ref). ### Return * `ct::Vector{T}` : Collision times. * `poss::Vector{SVector{2,T}}` : Positions at the collisions. * `vels::Vector{SVector{2,T}})` : Velocities exactly after the collisions. * `ω`, either `T` or `Vector{T}` : Angular velocity/ies (returned only for magnetic particles). The time `ct[i+1]` is the time necessary to reach state `poss[i+1], vels[i+1]` starting from the state `poss[i], vels[i]`. That is why `ct[1]` is always 0 since `poss[1], vels[1]` are the initial conditions. The angular velocity `ω[i]` is the one the particle has while propagating from state `poss[i], vels[i]` to `i+1`. Notice that at any point, the velocity vector `vels[i]` is the one obdained *after* the specular reflection of the `i-1`th collision. ### Ray-splitting billiards evolve!(p, bd, t, raysplitters) To implement ray-splitting, the `evolve!` function is supplemented with a fourth argument, `raysplitters` which is a tuple of [`RaySplitter`](@ref) instances. Notice that `evolve` **always mutates the billiard** if ray-splitting is used! For more information and instructions on using ray-splitting please visit the official documentation. """ function evolve!(p::AbstractParticle{T}, bd::Billiard{T}, t, raysplitters = nothing; warning = false) where {T<:AbstractFloat} if t ≤ 0 throw(ArgumentError("`evolve!()` cannot evolve backwards in time.")) end if ispinned(p, bd) push!(rpos, p.pos) push!(rvel, p.vel) push!(rt, Inf) return (rt, rpos, rvel, p.ω) end ismagnetic = p isa MagneticParticle isray = !isa(raysplitters, Nothing) isray && acceptable_raysplitter(raysplitters, bd) raysidx = raysplit_indices(bd, raysplitters) ismagnetic && isray && (omegas = [p.ω]) rt = T[0.0]; rpos = [p.pos]; rvel = [p.vel] count = zero(t) flight = zero(T) if typeof(t) == Int for zzz in (rt, rpos, rvel) sizehint!(zzz, t) end end while count < t i, tmin, pos, vel = bounce!(p, bd, raysidx, raysplitters) flight += tmin if isperiodic(i, bd) continue else push!(rpos, pos + p.current_cell) push!(rvel, vel) push!(rt, flight) ismagnetic && isray && push!(omegas, p.ω) # set counter count += increment_counter(t, flight) flight = zero(T) end end#time, or collision number, loop # Return stuff if ismagnetic && isray return (rt, rpos, rvel, omegas) elseif ismagnetic return (rt, rpos, rvel, p.ω) else return (rt, rpos, rvel) end end """ evolve(p, args...) Same as [`evolve!`](@ref) but copies the particle instead. """ evolve(p::AbstractParticle, args...) = evolve!(copy(p), args...) evolve(bd::Billiard, args...; kwargs...) = evolve!(randominside(bd), bd, args...; kwargs...) ##################################################################################### # Timeseries ##################################################################################### """ timeseries!([p::AbstractParticle,] bd::Billiard, t; dt, warning) Evolve the given particle `p` inside the billiard `bd` for the condition `t` and return the x, y, vx, vy timeseries and the time vector. If `t` is of type `AbstractFloat`, then evolve for as much time as `t`. If however `t` is of type `Int`, evolve for as many collisions as `t`. Otherwise, `t` can be any function, that takes as an input `t(n, τ, i, p)` and returns `true` when the evolution should terminate. Here `n` is the amount of obstacles collided with so far, `τ` the amount time evolved so far, `i` the obstacle just collided with and `p` the particle (so you can access e.g. `p.pos`). This function mutates the particle, use `timeseries` otherwise. If a particle is not given, a random one is picked through [`randominside`](@ref). The keyword argument `dt` is the time step used for interpolating the time series in between collisions. `dt` is capped by the collision time, as the interpolation _always_ stops at collisions. For straight propagation `dt = Inf`, while for magnetic `dt = 0.01`. For pinned magnetic particles, `timeseries!` issues a warning and returns the trajectory of the particle. If `t` is integer, the trajectory is evolved for one full circle only. Internally uses [`DynamicalBilliards.extrapolate`](@ref). ### Ray-splitting billiards timeseries!(p, bd, t, raysplitters; ...) To implement ray-splitting, the `timeseries!` function is supplemented with a fourth argument, `raysplitters` which is a tuple of [`RaySplitter`](@ref) instances. Notice that `timeseries` **always mutates the billiard** if ray-splitting is used! For more information and instructions on using ray-splitting please visit the official documentation. """ function timeseries!(p::AbstractParticle{T}, bd::Billiard{T}, f, raysplitters = nothing; dt = typeof(p) <: Particle ? T(Inf) : T(0.01), warning::Bool = true) where {T} ts = [zero(T)] x = [p.pos[1]]; y = [p.pos[2]] vx = [p.vel[1]]; vy = [p.vel[2]] ismagnetic = p isa MagneticParticle prevω = ismagnetic ? p.ω : T(0) isray = !isa(raysplitters, Nothing) isray && acceptable_raysplitter(raysplitters, bd) raysidx = raysplit_indices(bd, raysplitters) n, i, t, flight = 0, 0, zero(T), zero(T) prevpos = p.pos + p.current_cell prevvel = p.vel if ispinned(p, bd) warning && @warn "Pinned particle detected!" #return one cycle if t is a collision number t_ret = typeof(t) <: Integer ? 2π/p.ω : T(t) nx, ny, nvx, nvy, nts = extrapolate(p, prevpos, prevvel, t_ret, dt, p.ω) append!(ts, nts[2:end] .+ t) append!(x, nx[2:end]); append!(vx, nvx[2:end]) append!(y, ny[2:end]); append!(vy, nvy[2:end]) return x, y, vx, vy, ts end @inbounds while check_condition(f, n, t, i, p) # count < t i, ct = bounce!(p, bd, raysidx, raysplitters) flight += ct if isperiodic(i, bd) # do nothing at periodic obstacles continue else if flight ≤ dt # push collision point only push!(ts, flight + t) push!(x, p.pos[1] + p.current_cell[1]) push!(y, p.pos[2] + p.current_cell[2]) push!(vx, p.vel[1]); push!(vy, p.vel[2]) else nx, ny, nvx, nvy, nts = extrapolate(p, prevpos, prevvel, flight, dt, prevω) append!(ts, nts[2:end] .+ t) append!(x, nx[2:end]); append!(vx, nvx[2:end]) append!(y, ny[2:end]); append!(vy, nvy[2:end]) end prevpos = p.pos + p.current_cell prevvel = p.vel t += flight; n += 1 flight = zero(T) ismagnetic && isray && (prevω = p.ω) end end return x, y, vx, vy, ts end check_condition(f::Int, n, t, i, p) = f > n check_condition(f::AbstractFloat, n, t, i, p) = f > t check_condition(f, n, t, i, p) = !f(n, t, i, p) """ extrapolate(particle, prevpos, prevvel, ct, dt[, ω]) → x, y, vx, vy, t Create the timeseries that connect a `particle`'s previous position and velocity `prevpos, prevvel` with the `particle`'s current position and velocity, provided that the collision time between previous and current state is `ct`. `dt` is the sampling time and if the `particle` is `MagneticParticle` then you should provide `ω`, the angular velocity that governed the free flight. Here is how this function is used (for example) ```julia prevpos, prevvel = p.pos + p.current_cell, p.vel for _ in 1:5 i, ct, pos, vel = bounce!(p, bd) x, y, x, vy, t = extrapolate(p, prevpos, prevvel, ct, 0.1) # append x, y, ... to other vectors or do whatever with them prevpos, prevvel = p.pos + p.current_cell, p.vel end ``` """ function extrapolate(p::MagneticParticle{T}, prevpos::SV{T}, prevvel::SV{T}, ct::T, dt::T, ω::T = p.ω) where {T <: AbstractFloat} φ0 = atan(prevvel[2], prevvel[1]) s0, c0 = sincos(φ0) tvec = collect(0:dt:ct) x = Vector{T}(undef, length(tvec)) y = Vector{T}(undef, length(tvec)) vx = Vector{T}(undef, length(tvec)) vy = Vector{T}(undef, length(tvec)) @inbounds for (i,t) ∈ enumerate(tvec) s,c = sincos(ω*t + φ0) x[i] = s/ω + prevpos[1] - s0/ω y[i] = -c/ω + prevpos[2] + c0/ω vx[i] = c; vy[i] = s end # finish with ct @inbounds if tvec[end] != ct push!(tvec, ct) push!(x, p.pos[1] + p.current_cell[1]) push!(y, p.pos[2] + p.current_cell[2]) push!(vx, p.vel[1]); push!(vy, p.vel[2]) end return x, y, vx, vy, tvec end extrapolate(p::Particle, a, b, c, d, ω) = extrapolate(p::Particle, a, b, c, d) function extrapolate(p::Particle{T}, prevpos::SV{T}, prevvel::SV{T}, ct::T, dt::T) where {T <: AbstractFloat} tvec = collect(0:dt:ct) x = Vector{T}(undef, length(tvec)) y = Vector{T}(undef, length(tvec)) vx = Vector{T}(undef, length(tvec)) vy = Vector{T}(undef, length(tvec)) @inbounds for (i,t) ∈ enumerate(tvec) x[i] = prevpos[1] + t*prevvel[1] y[i] = prevpos[2] + t*prevvel[2] vx[i], vy[i] = prevvel end # finish with ct @inbounds if tvec[end] != ct push!(tvec, ct) push!(x, p.pos[1] + p.current_cell[1]) push!(y, p.pos[2] + p.current_cell[2]) push!(vx, p.vel[1]); push!(vy, p.vel[2]) end return x, y, vx, vy, tvec end # non-mutating version """ timeseries(p, args...; kwargs...) Non-mutating version of [`DynamicalBilliards.timeseries!`](@ref) """ @inline timeseries(p::AbstractParticle, args...; kwargs...) = timeseries!(copy(p), args...; kwargs...)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
2130
using Test using DynamicalBilliards using DynamicalBilliards.Testing function test_finite_collisions(p, bd, N = 1e6) n = 0 i, t = next_collision(p, bd) s = Set(i) @testset "$(tag(p)) 0 < t < Inf" begin while n < N i, t = bounce!(p, bd) if 0 < t < Inf @test true else error("$(tag(p, bd)) collision time $(t) with obst.index $(i)") end n += 1 push!(s, i) end end if typeof(p) <: Particle && !isperiodic(bd) iprev = 0 n = 0 @testset "collide with each obstacle ONCE!" begin while n < 1000 i, t = bounce!(p, bd) if i != 4 if i != iprev @test true else error("$(tag(p)) consecutive collisions with $(i)") end end iprev = i n += 1 end end end @testset "$(tag(p, bd)) collided with all obstacles" begin @test s == Set(1:length(bd)) end end function test_maximum_distance(p, bd, thres = 1e-12, N = 1e6) acc = acclevel(p, bd) n = 0 t, i = next_collision(p, bd) maxds = fill(-Inf, length(bd)) minds = fill(Inf, length(bd)) thresholds = fill(0, length(bd)) isp = isperiodic(bd) @testset "$(tag(p, bd)) max/min distance" begin while n < N i, t, cp = next_collision(p, bd) d = distance(cp, bd[i]) d < minds[i] && (minds[i] = d) d > maxds[i] && (maxds[i] = d) i, t = bounce!(p, bd) @test abs(d) < acc abs(d) > thres && (thresholds[i] += 1) n += 1 end println(tag(p, bd)) println("minds: ", minds) println("maxds: ", maxds) println("more than $(thres): ", thresholds, " (acc = $(acc))") println() end end billiards_testset("Finite Collision time", test_finite_collisions) billiards_testset("min/max distance", test_maximum_distance, 1e-12)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
2659
using Test using DynamicalBilliards using DynamicalBilliards.Testing function test_no_escape(p, bd, N = 1e4) xmin, ymin, xmax, ymax = cellsize(bd) xt, yt, vyt, vxt, tvec = timeseries(p, bd, Int(N); dt = Inf) @test length(xt) == N + 1 @test typeof(xt) == typeof(tvec) == Vector{eltype(p)} @testset "$(tag(p, bd)) correct tvector" begin for i in 2:length(tvec) @test tvec[i] > tvec[i-1] end end dx1 = minimum(xt) - xmin dx2 = xmax - maximum(xt) dy1 = minimum(yt) - ymin dy2 = ymax - maximum(yt) println(tag(p, bd)) println("dx1: ", dx1, " dx2: ", dx2) println("dy1: ", dy1, " dy2: ", dy2) println() @testset "$(tag(p, bd)) no escape" begin for d in (dx1, dx2, dy1, dy2) @test d ≥ -acclevel(p, bd) end end end billiards_testset("No escape", test_no_escape; caller = ergodic_tests) function test_visited_obstacles(p, bd, N = 50) ts, obst = visited_obstacles(p, bd, N) cts, = evolve(p, bd, N) @test length(ts) == length(cts) cc = cumsum(cts) for i in eachindex(cc) @test cc[i] ≈ ts[i] atol = 1e-12 end end billiards_testset("Visited obstacles", test_visited_obstacles; caller = ergodic_tests) function test_predicate_ts(p, bd, N = 1e3) xmin, ymin, xmax, ymax = cellsize(bd[1]) f(n, t, i, p) = i == 1 xt, yt = timeseries(p, bd, Int(N), dt = Inf) @test (xt[end] == xmin || xt[end] == xmax) @test (yt[end] == ymin || yt[end] == ymax) end billiards_testset("Predicate function", test_visited_obstacles; caller = ergodic_tests) function test_movin_periodic(p, bd, N = 1e3) xmin, ymin, xmax, ymax = cellsize(bd) xt, yt = timeseries(p, bd, Int(N), dt = Inf) @test length(xt) == N + 1 @test typeof(xt) == typeof(xt) == Vector{eltype(p)} dx1 = minimum(xt) - xmin dx2 = xmax - maximum(xt) dy1 = minimum(yt) - ymin dy2 = ymax - maximum(yt) @test maximum(abs.((dx1, dx2))) > xmax - xmin @test maximum(abs.((dy1, dy2))) > ymax - ymin end billiards_testset("movin periodic", test_movin_periodic; caller = periodic_tests) function test_raysplit_ts_inside(p, bd, ray, N = 1e4) xmin, ymin, xmax, ymax = cellsize(bd) xt, yt = timeseries(p, bd, Int(N), ray, dt = Inf) @test length(xt) == N + 1 @test typeof(xt) == typeof(xt) == Vector{eltype(p)} dx1 = minimum(xt) - xmin dx2 = xmax - maximum(xt) dy1 = minimum(yt) - ymin dy2 = ymax - maximum(yt) for d in (dx1, dx2, dy1, dy2) @test d ≥ -acclevel(p, bd) end end billiards_testset("timeseries raysplit", test_raysplit_ts_inside; caller = ray_tests)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
3166
using Test using DynamicalBilliards using DynamicalBilliards.Testing function test_lyapunov_spectrum(p, bd, t = 1e6, error_level = 1e-2) # calculate spectrum exps = lyapunovspectrum!(p, bd, t) sumpair = exps[1] + exps[4] # these properties should be true for all billiards @testset "λ₁ + λ₄ ≈ 0" begin @test abs(sumpair) < error_level end @testset "λ₂ ≈ 0, λ₃ ≈ 0" begin @test abs(exps[2]) < error_level @test abs(exps[3]) < error_level end exps = lyapunovspectrum!(p, bd, 10000) sumpair = exps[1] + exps[4] # these properties should be true for all billiards @testset "λ₁ + λ₄ ≈ 0" begin @test abs(sumpair) < error_level end @testset "λ₂ ≈ 0, λ₃ ≈ 0" begin @test abs(exps[2]) < error_level @test abs(exps[3]) < error_level end end billiards_testset("Properties of Lyapunov spectrum", test_lyapunov_spectrum; caller = simple_tests) function test_lyapunov_magnetic_limit(args...) bd = billiard_bunimovich(0.1) t = 1e5 error_level = 5e-2 for j ∈ 1:10 pmag = randominside(bd, 1e-3) plin = Particle(pmag.pos, pmag.vel, SVector{2,Float64}(0,0)) exp_mag = lyapunovspectrum!(pmag, bd, t) exp_lin = lyapunovspectrum!(plin, bd, t) @test exp_mag[1] - exp_lin[1] < error_level end end billiards_testset("Lyapunov spectrum for small B", identity; caller=test_lyapunov_magnetic_limit) function test_lyapunov_values(args...) t = 20000.0 radius = 1.0 spaces = [2.0, 2.5, 3.0, 3.5, 4.0] # based on Gaspard et al (see docs) & DynamicalBilliards v2.5 expected_values = [3.6, 1.4, 0.8, 0.6, 0.5] error_level = 0.2 for (i, space) in enumerate(spaces) bd = billiard_polygon(6, space/(sqrt(3)); setting = "periodic") disc = Disk([0., 0.], radius) billiard = Billiard(bd.obstacles..., disc) p = randominside(billiard) λ = lyapunovspectrum(p, billiard, t)[1] @test abs(λ - expected_values[i]) < error_level end end billiards_testset("Lyapunov numerical values", identity, caller=test_lyapunov_values) using LinearAlgebra function test_perturbationgrowth(p, bd) tmax = 100.0 error_level = 2e-1 t, R, o = perturbationgrowth(p, bd, tmax) λ = lyapunovspectrum(p, bd, tmax) Δ = perturbationevolution(R) norms = log.(norm.(Δ)) actual = norms[end]; i = length(norms) - 1 while isinf(actual) actual = norms[i] i -= 1 end λ_estimate = actual/t[i] @test abs(λ[1] - λ_estimate) < error_level nmax = 500 t, R, o = perturbationgrowth(p, bd, nmax) λ = lyapunovspectrum(p, bd, nmax) Δ = perturbationevolution(R) @test length(t) == 2*nmax norms = log.(norm.(Δ)) actual = norms[end]; i = length(norms) - 1 while isinf(actual) actual = norms[i] i -= 1 end λ_estimate = actual/t[i] @test abs(λ[1] - λ_estimate) < error_level end billiards_testset("Compare Lyapunovs and perturbation growth", test_perturbationgrowth; caller=ergodic_tests)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
4410
using Test using DynamicalBilliards using DynamicalBilliards.Testing function coordinate_invariance(p, bd, args...) @testset "$(tag(p, bd)) Coordinate change" begin for t in 1:2e4 i, tmin = bounce!(p, bd) ξ, sφ = to_bcoords(p, bd[i]) pos, vel = from_bcoords(ξ, sφ, bd[i]) @test *(isapprox.(p.pos, pos, atol=1e-4)...) @test *(isapprox.(p.vel, vel, atol=1e-4)...) end end end billiards_testset("Coordinate change invariance", coordinate_invariance; caller = omni_tests_noellipse) function cut_psos(args...) t = 1000 bt = billiard_sinai(0.25) plane = InfiniteWall([0.5, 0.0], [0.5, 1.0], [-1.0, 0.0]) @testset "PSOS: pinned particle" begin # case of pinned that crosses plane but not walls p = MagneticParticle(0.2, 0.5, -π/2, 1/0.3) a, b = psos(bt, plane, t, p) @test typeof(a) <: Vector{<:SVector} @test length(a) == length(b) == 1 # case of pinned that doesn't cross anything p = MagneticParticle(0.1, 0.5, -π/2, 1/0.05) a, b = psos(bt,plane, t, p) @test typeof(a) <: Vector{<:SVector} @test length(a) == length(b) == 0 # case of pinned but does cross periodic walls *and* section bd = billiard_sinai(;setting = "periodic") p = MagneticParticle(0.25, 0.25, -π/2 + π/4, 0.44*2) a, b = psos(bd, plane, t, p) @test typeof(a) <: Vector{<:SVector} @test length(a) == length(b) == 1 end for ω ∈ [0.0, 1.0] p = ω == 0 ? randominside(bt) : randominside(bt, ω) @testset "$(tag(p, bt)) psos" begin a, b = psos(bt, plane, t, p) for j in 1:length(a) @test a[j][1] ≈ 0.5 @test 0 < a[j][2] < 1 @test -1 < b[j][1] < 1 @test -1 < b[j][2] < 1 end end end @testset "many particles" begin a, b = psos(bt, plane, 1000, 10) for i in 1:length(a) @test length(a[i]) == length(b[i]) end end end billiards_testset("PSOS", identity; caller = cut_psos) function fills_boundarymap(p, bd) @testset "$(tag(p, bd)) Fills boundary map" begin bmap, = boundarymap(p, bd, 10000) ξs = [b[1] for b in bmap]; sφs = [b[2] for b in bmap] partition = (10,10) # partition size A = falses(partition) l = totallength(bd) ε = (l/partition[1], 2/partition[2]) # box size c = 0 for point ∈ zip(ξs, sφs) id = clamp.(ceil.(Int, (point .- (0, -1))./ε), (1,1), partition) if !A[id...] A[id...] = true c += 1 if c == partition[1]*partition[2] break end end end for a in A @test a end end end billiards_testset("Fills boundary map", fills_boundarymap; caller = ergodic_tests) function phasespace_ratio(f, g) @testset "Bunimovich" begin t = 100000.0 bt = billiard_bunimovich() for ω in [0.0, 0.1] p = ω == 0 ? randominside(bt) : randominside(bt, ω) @testset "$(tag(p, bt))" begin φ = π/4 * rand() # so that we never find bouncing walls p.vel = (cos(φ), sin(φ)) ratio, = f(bt,t, randominside(bt), 0.1) @test ratio == 1.0 end end end t = 1000000.0 l = 1.0; r = 1.0 @testset "Mushroom w=$(w)" for w ∈ [0.2, 0.4] bt = billiard_mushroom(l, w, r) @testset "regular" begin p = MushroomTools.randomregular(l, w, r) ratio, = f(bt,t, p, 0.1) trueratio = 1 - g(l,w,r) # Only one regular particle covers very small amount of space: @test ratio < trueratio end @testset "chaotic" begin p = MushroomTools.randomchaotic(l, w, r) ratio, = f(bt, t, p, 0.1) trueratio = g(l,w,r) @test trueratio - 0.1 ≤ ratio ≤ trueratio + 0.1 end end end ratio_caller(x, f, g) = phasespace_ratio(f, g) billiards_testset("2D Phasespace Ratio", identity, boundarymap_portion, MushroomTools.g_c_2D; caller = ratio_caller) billiards_testset("3D Phasespace Ratio", identity, phasespace_portion, MushroomTools.g_c_3D; caller = ratio_caller)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
5080
using Test using DynamicalBilliards using DynamicalBilliards.Testing # %% Basic tests function simple_raysplit(f, args...) bd, ray = basic_ray(true) p = randominside(bd) f(p, bd, ray, args...) bd, ray = basic_ray(false) mp = randominside(bd, 2.0) f(mp, bd, ray, args...) end function test_finite_collisions_ray(p, bd, ray, N = 5e5) n = 0 i, t = next_collision(p, bd) s = Set(i) raysidx = DynamicalBilliards.raysplit_indices(bd, ray) @testset "$(tag(p)) 0 < t < Inf" begin while n < N i, t = bounce!(p, bd, raysidx, ray) if 0 < t < Inf @test true else error("$(tag(p, bd, ray)) collision time $(t) with obst.index $(i)") end n += 1 push!(s, i) end end @testset "$(tag(p, bd)) collided with all obstacles" begin @test s == Set(1:length(bd)) end end function ray_maximum_distance(p, bd, ray, thres = 1e-13, N = 5e5) acc = acclevel(p, bd, ray) n = 0 t, i = next_collision(p, bd) maxds = fill(-Inf, length(bd)) minds = fill(Inf, length(bd)) thresholds = fill(0, length(bd)) isp = isperiodic(bd) raysidx = DynamicalBilliards.raysplit_indices(bd, ray) @testset "$(tag(p, bd, ray)) max/min distance" begin while n < N i, t, cp = next_collision(p, bd) d = distance(cp, bd[i]) d < minds[i] && (minds[i] = d) d > maxds[i] && (maxds[i] = d) i, t = bounce!(p, bd, raysidx, ray) @test abs(d) < acc abs(d) > thres && (thresholds[i] += 1) n += 1 end println(tag(p, bd)) println("minds: ", minds) println("maxds: ", maxds) println("more than $(thres): ", thresholds, " (acc = $(acc))") println() end end billiards_testset("Ray Collision time", test_finite_collisions_ray; caller = simple_raysplit) billiards_testset("Ray min/max distance", ray_maximum_distance; caller = simple_raysplit) # %% Extreme angles test function extreme_raysplit(f, args...) bd, ray = extreme_ray(true) p = randominside(bd) f(p, bd, ray, args...) bd, ray = extreme_ray(false) mp = randominside(bd, 2.0) f(mp, bd, ray, args...) end billiards_testset("ERay Collision time", test_finite_collisions_ray; caller = extreme_raysplit) billiards_testset("ERay min/max distance", ray_maximum_distance; caller = extreme_raysplit) # %% Totally brutal tests function inside_antidot(args...) bd, ray = extreme_ray(true) pa = randominside(bd) mp = randominside(bd, 1.0) isray(i) = (i == 1 || i == 2) raysidx = DynamicalBilliards.raysplit_indices(bd, ray) for p in (pa, mp); @testset "$(tag(p, bd, ray)) BRUTAL" begin bd, ray = extreme_ray(typeof(p) <: Particle) n = 0 iprev = 0 check = false while n < 5e5 i, t = bounce!(p, bd, raysidx, ray) if check @test i == iprev end check = isray(i) && !(bd[i].pflag) iprev = i n += 1 end end; end end billiards_testset("RAY Stays inside", identity; caller = inside_antidot) test_refraction(ϕ, pflag, ω) = pflag ? 0.5ϕ : 2.0ϕ test_transmission(ϕ, pflag, ω) = begin if pflag 0.5*exp(-(ϕ)^2/2(π/8)^2) else abs(ϕ) < π/4 ? 0.5*exp(-(ϕ)^2/2(π/4)^2) : 0.0 end end @testset "FiniteSplitterWall" begin bdr = billiard_rectangle(1.0, 1.0) splitter = FiniteSplitterWall([0.5,0.0], [0.5,1.0], [-1.0,0.0]) bd = Billiard(splitter, bdr...) N = 500 rs = (RaySplitter([1], test_transmission, test_refraction),) ps = particlebeam(0.01, 0.5, 0, N, 0) positions = [] for p in ps ct, pos, vel = evolve!(p, bd, 2, rs) push!(positions, pos[end][1]) reset_billiard!(bd) end particles_on_left = length(filter(x ->x < 0.4, positions)) particles_on_right = length(filter(x -> x > 0.6, positions)) particles_in_middle = length(filter(x -> 0.4 <= x <= 0.6, positions)) @test 0.3N < particles_on_left < 0.7N @test 0.3N < particles_on_right < 0.7N @test particles_in_middle == 0 end @testset "Ray-splitting escapetime" begin verts = [[0.0,0.0], [0.0,1.0], [1.0,1.0], [1.0,0.0]] bdr = [] # create rect billiard where vertical walls are doors for i in eachindex(verts) s = verts[i] e = verts[mod1(i+1, length(verts))] w = s - e n = [-w[2], w[1]] push!(bdr, FiniteWall(s, e, n, mod1(i, 2)==1)) end splitter = FiniteSplitterWall([0.75,0.0], [0.75,1.0], [-1.0,0.0]) bd = Billiard(splitter, bdr...) N = 500 rs = (RaySplitter([1], test_transmission, test_refraction),) ps = particlebeam(0.01, 0.5, 0, N, 0) ts = [] for p in ps push!(ts, escapetime!(p, bd, 3, rs)) reset_billiard!(bd) end mean_t = +(ts...)/N expected_mean_t = 0.5 * 1 + 0.5 * 0.75 * 2 @test abs(expected_mean_t - mean_t) < 0.2 end
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
568
using DynamicalBilliards using Test using DynamicalBilliards.Testing print("DynamicalBilliards tests start now.") timetime = time() include("basic_tests.jl") include("extended_tests.jl") include("various_tests.jl") include("type_stability.jl") include("phasespaces_tests.jl") include("raysplt_tests.jl") include("lyapunov.jl") print("\nDynamicalBilliards tests ended (successfully)!") timetime = time() - timetime println("Total time required was:") println(round(timetime, digits = 3), " seconds, or ", round(timetime/60, digits=3), " minutes")
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
1278
using Test using DynamicalBilliards using DynamicalBilliards.Testing Floats = [Float16, Float32, Float64, BigFloat] function alltypes(f, args...) r = 0.25; x = y = 1.0 for T ∈ Floats bd = billiard_sinai(T(r), T(x), T(y)) @test eltype(bd) == T p = randominside(bd) @test eltype(p) == T f(p, bd, args...) p = randominside(bd, T(1.0)) @test eltype(p) == T f(p, bd, args...) end end function type_stability(p, bd) @testset "$(tag(p))" begin T = eltype(bd) for o in bd t, cp = collision(p, o) @test typeof(t) == T @test eltype(cp) == T end i, t, cp = next_collision(p, bd) @test typeof(t) == T @test eltype(cp) == T ct, poss, vels = evolve(p, bd, 5) @test eltype(ct) == T @test eltype(poss[1]) == eltype(vels[1]) == T ct, poss, vels = evolve(p, bd, 5.0) @test eltype(ct) == T @test eltype(poss[1]) == eltype(vels[1]) == T xt, yt, vxt, vyt, tt = timeseries(p, bd, T(10.0); dt = T(0.1)) for x in (xt, yt, vxt, vyt, tt) @test eltype(x) == T end end end billiards_testset("type stability", type_stability; caller = alltypes)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
code
2919
using Test using DynamicalBilliards using DynamicalBilliards.Testing function escapetest(args...) l = 1.0; w = 0.2; r = 1.0 bd = billiard_mushroom(l, w, r) for i in 1:20 p = MushroomTools.randomchaotic(l, w, r) t = escapetime(p, bd, Int(1e6)) @test t < Inf p = MushroomTools.randomregular(l, w, r) t = escapetime(p, bd, Int(1e6)) @test t == Inf end end billiards_testset("escape time", identity; caller = escapetest) function meancoltest(args...) p = Particle(0.1, 0.1, 0.1) @testset "Sinai" begin for r in [0.25, 0.35] bd = billiard_sinai(r) a = π*(1 - π*(r)^2)/(4 + 2π*r) m = meancollisiontime(p, bd, Int(1e6)) @test a ≈ m rtol = 0.1 end end @testset "Stadium" begin l = 1.0; w = 1.0 bd = billiard_stadium(l, w) a = π*(w*l + π*(w/2)^2)/(2l + π*w) m = meancollisiontime(p, bd, Int(1e6)) @test a ≈ m rtol = 0.1 end @testset "Stadium" begin l = 1.0; w = 1.0 bd = billiard_stadium(l, w) p = MagneticParticle(0.1, 0.1, 0.1, 1.0) a = π*(w*l + π*(w/2)^2)/(2l + π*w) m = meancollisiontime(p, bd, Int(1e6)) @test a ≈ m rtol = 0.1 end end billiards_testset("mean collision time", identity; caller = meancoltest) function noparticle_interafaces(args...) bd = billiard_mushroom() @test typeof(escapetime(bd, 100)) == Float64 @test typeof(meancollisiontime(bd, 100)) == Float64 @test typeof(evolve(bd, 100)[1][1]) == Float64 # @test typeof(lyapunovspectrum(bd, 100.0)[1]) == Float64 end billiards_testset("no-particle interface", identity; caller = noparticle_interafaces) function ispinned_tests(args...) bd = billiard_sinai(;setting = "periodic") # case of pinned that crosses plane but not walls p = MagneticParticle(0.2, 0.5, -π/2, 1/0.3) @test ispinned(p, bd) # case of pinned that doesn't cross anything p = MagneticParticle(0.1, 0.5, -π/2, 1/0.05) @test ispinned(p, bd) # case of pinned but does cross periodic walls *and* section p = MagneticParticle(0.0, 1.0, -π/2, 0.44*2) @test ispinned(p, bd) # Sanity check for 2 nonpinned particles @test !ispinned(randominside(bd), bd) p = MagneticParticle(0.2, 0.8, -π/2, 1/0.3) @test !ispinned(p, bd) end billiards_testset("ispinned", identity; caller = ispinned_tests) # Quick an sloppy parallelization test function test_parallelized(args...) bd = billiard_mushroom() N = 100 particles = [randominside(bd) for i in 1:N] for f in (meancollisiontime!, escapetime!, lyapunovspectrum!) res = parallelize(f, bd, N, particles) @test length(res) == N end res, ai = parallelize(boundarymap, bd, N, particles) @test length(res) == N end billiards_testset("parallelize", identity; caller = test_parallelized)
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
11636
# 3.12.0 * New `FiniteSplitterWall` structure. # 3.11.0 * `particlebeam` and `randominside_xyφ` functions. # 3.10.0 * It is now possible in `timeseries!` to evolve a particle until a certain boolean condition is met. # 3.9.0 * It is now possible to create animations as gifs. # 3.8.0 * Walls can have their normal vector automatically calculated, pointing to the left of the endpoint - startpoint. * New function `billiard_vertices` that creates a billiard out of vertices. # 3.7.0 * `extrapolate` is now mentioned in the documentation and has a docstring. # 3.6.3 * Bugfix of `timeseries` function where if the `dt` was larger than the collision time, the returned timevector was wrong. # 3.6 * Keyword `particle_Kwargs` of `animate_evolution` can now conveniently be `nothing`, in which case the particles are not plotted, only their trajectories. # 3.5 * New function `visited_obstacles!`. * 2D and 3D chaotic phase space volumes now in `MushroomTools`. # 3.4 * Lyapunov computation and perturbation growth can now accept integer time (which means amount of collisions). # 3.3 * Replaced all instances of `pertubation` with `perturbation`. A deprecation is thrown. # 3.2 * New perturbation growth functions. # 3.1 * `law_of_refraction` : new function that returns transmission and refraction functions based on Snell's law and refractive indices. * Plenty of doc corrections. # 3.0 ## Breaking changes * Plotting functions now overload `plot` instead. There is no more `plot_obstacle`, `plot_billiard` and `plot_particle`. `plot_boundarymap` and `animate_evolution` remain the same though. * `construct` is removed. * `boundarymap` call signature and return values are reworked. ## Enhancements / new features * Brand new evolution animation function (replaced the old). It now animates in real-time!!! (you can use `dt = Inf` to obtain the old behavior). In addition it supports animating the evolution of multiple particles in parallel!!! * New function `timeseries` creates the timeseries of the particle evolution in a billiard. This does pretty much what `construct(evolve...)` used to do. * New obstacle: `Ellipse`. * Much more robust propagation algorithm that is less prone to errors and "weird behaviors"! * Test suite reworked almost from scratch: More tests, more specific tests, more robust tests, easier to debug tests! * `totallength` is exported. * `plot(bd, x, y)` (using the timeseries of `timeseries`) now also works for non-periodic billiards as well, for convenience. * Automatic parallelization is now possible for some functions, given by the `parallelize` function. ## Low-Level changes These changes are not actually breaking, unless someone used the low-level interface. The docs also changed and much less than the low level interface is exposed. * Renamed `collisiontime` to just `collision`, since now it returns both the time and the estimated collision point. * Many low-level functions are not exported any more, for safety and because it didn't make much sense: `normvalvec, distance, cellsize, ``propagate!`, `relocate!`, `resolvecollision!`, `periodicity!`, `specular!` `realangle`. For the low level interface only `propagate!`, `bounce!`, `collision` and `next_collision` are exposed. Only `bounce!` is exposed as public API. The low level interface is _still_ documented though. * Change of the internal propagation algorithm: 1. the function `collision` (previously `collisiontime`) returns both the time until collision *as well as* the collision point (most methods computed it already anyways). 2. The `timeprec` and all those nonsense are removed. It is the duty of `collision` to return `Inf` if the particle is very close to the collision point (`realangle` uses `accuracy`, while for straight propagation the direction of travel is enough). 3. The particle is then "teleported" to this point by setting its `pos`. For the case of magnetic propagation the velocity is propagated by the collision time. This brings very high accuracy, as the velocity vector is not multiplied with time and then added to the position vector. 4. The `distance` is checked. If it has wrong sign, a `relocation` simply relocates the particle in the direction of the `normalvec`, for amount `(1+eps())*distance`. 5. Specular reflection / periodicity is done. * Renamed `distancecheck` to `accuracy` # v2.3 * Now you can write `p.ω` as well as `p.omega` for magnetic particles. * New `ispinned` function that returns Bool of whether a particle is pinned or not. Also works with periodic billiards. # v2.2 * Standard billiards can now also be created with keyword arguments. * Logo billiard is now exported by the function `billiard_logo`. # v2.1 * Better limits of axis for periodic rectangular billiards. * Added some methods for high level functions (like e.g. `evolve`) that if not given a particle they pick on from `randominside`. * Documentation improvements. * Bug fix in the expressions for the chaotic phase space volume of mushrooms. # v2.0 ## New Features! * **3 orders of magnitude performance gains on all functions!!!** * Reduced a lot of allocations done all over the place. In most places allocations done are now exactly zero! ZEROOOOOOOOOOOO * Fixed many instances of broadcasting with static vectors (which is bad). * Utilized metaprogramming to manually unroll some loops. * If a billiard is periodic it is now known at compile time. This gives massive performance benefits in functions like `evolve`, which have to check if the collision occured with periodic walls. * **Symver will now be properly respected from 2.0 onwards**. * Automatic saving of animations to video via `ffmpeg`!!! * Hexagonal periodic plotting. * Lyapunov exponents for magnetic particles are now possible! * Added boundary map computation function which works for any billiard and any particle. It assumes that the obstacles are sorted counter clockwise. * Added `to_bcoords`, `totallength` * Added `plot_boundarymap` that plots the boundary map and the obstacle boundaries. * Added robust coordinate change transformation from 3D real space to 2D boundary space, see `to_bcoords`, `from_bcoords` and `arclengths`. * Added two novel high-level functions that compute the phase-space portion an orbit covers as the particle evolves: `boundarymap_portion` and `phasespace_portion`. * Added Poincare surface of section function, which computes intersections with arbitrary planes! * It is now possible to affect many different obstacles during ray-splitting! * Plotting is now available the moment the user does `using PyPlot`. Done through the `Requires` module. The function `enableplotting()` does not exist anymore! * Re-organized all source code into a much more readable state, and as a result significantly reduced the total lines of code. * added `evolve` function that simply deepcopies particle. * Added convenience function to compute the mean collision time in a billiard. * New low-level function `bounce!` that propagates a particle from one collision to the next. In essence does what `evolve!` does with `t=1`, but without creating a bunch of saving stuff. All high level functions use `bounce!`. ## Syntax and other breaking changes * Default colors for plotting have been changed (random obstacles are purple, particle orbit is `"C0"`). * **[BREAKING]** Overhauled what a "billiard table" is: Now, called simply `Billiard` is a dedicated struct that stores the obstacles as a tuple. This means that all functions do not accept a `Vector{Obstacle}` anymore but rather a `Billiard`. * **[BREAKING]** `timeprec` now takes arguments `timeprec(::Particle, ::Obstacle)` to utilize better multiple dispatch and reduce code repetition. * **[BREAKING]** `realangle` now only takes one intersection and simply returns the real angle. * **[BREAKING]** `animate_evolution` now does not have `!` at the end, because it deepcopies the particle. * **[BREAKING]** Re-worked ray-splitting: We now use the `RaySplitter` struct. See docs. --- # v1.6.1 Updated the documentation to reflect the new changes of v1.6.0 # v1.6.0 - WARNING: DOCUMENTATION NOT UPDATED. SEE v1.6.1 * **[BREAKING]** Function `animate_evolution` has been renamed to `animate_evolution!` to remind users that it mutates the particle. * **[BREAKING]** `FiniteWall` has been renamed to `InfiniteWall` and works as before for convex billiards. A new type `FiniteWall` is introduced that can work for non-convex billiards. * `FiniteWall` has some extra fields for enabling this. * `FiniteWall` has a boolean field `isdoor`, that designates the given wall to be `Door`. This is used in `escapetime`. * *MASSIVE*: Added function `escapetime(p, bt)` which calculates the escape time of a particle from a billiard table. The escape time is the time until the particle collides with a `Door` (any `Door`). * `animate_evolution!` can create a new figure and plot the billiard table on user input. This happens by default. * Bugfix: relocation in magnetic case was not adaptive (for the backwards method). * *MASSIVE*: Added a `Semicircle` type! For both types of evolution! * added Bunimovich billiard `billiard_bunimovich` * added mushroom billiard `billiard_mushroom` # v1.5.0 * Added possibility to calculate the Lyapunov spectrum of a billiard system. Currently this is available only for `Particle`s. * use the function `lyapunovspectrum` for the computation. * Changed the relocating algorithm to be geometric. i.e. the time adjusting is done geometrically (self-multiplying the adjustment by 10 at each repeated step). * Magnetic propagation and straight propagation now both use `timeprec(T)` (see below). For both cases the maximum number of geometric iterations is 1 (for the default value of `timeprec(T)`. * This `timeprec` cannot be used PeriodWall and RaySplitting obstacles with MagneticParticles because when magnetic and relocating forward you get extremely shallow angles and you need huge changes in time for even tiny changes in position. * For this special case the function `timeprec_forward(T)` is used instead. This function results to on average 3-5 geometric relocation steps. * Fixed many issues and bugs. # v1.4.0 * All major types defined by `DynamicalBilliards` have been changed to parametric types with parameter `T<:AbstractFloat`. * The above makes the billiard table type annotation be `bt::Vector{<:Obstacle{T}}) where {T<:AbstractFloat}` instead of the old `bt::Vector{Obstacle}`. * Particle evolution algorithm has fundamentally changed. The way the algorithm works now is described in the documentation in the [Physics](https://juliadynamics.github.io/DynamicalBilliards.jl/latest/physics/#numerical-precision) page. * This point with conjuction with the above made the package **much faster**. * Positional argument `warning` of `evolve!()` has been changed to **keyword argument**. * The raysplitting functions must always accept 3 arguments, even in the case of straight propagation. The best way is to have the third argument have a default value. * All `distance` functions can now take a position as an argument (giving a particle simply passes the position). * Removed redundant functions like `magnetic2standard`. * The package is now precompiled. * Tests have been restructured to be faster, more efficient, and use the `@testset` type of syntax. * Documentation has been made more clear. # v1.3.0 Changelog will be kept from this version. See the [releases](https://github.com/JuliaDynamics/DynamicalBilliards.jl/releases) page for info on previous versions.
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
173
# Issue Description # Expected Behavior # MWE MWE stands for Minimal Working Example. Please include a piece of code that can replicate your problem in a simple example.
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
2687
![DynamicalBilliards v3.0 Logo: The Julia billiard](https://github.com/JuliaDynamics/JuliaDynamics/blob/master/videos/billiards/DynamicalBilliards_logo_animated.gif?raw=true) A Julia package for dynamical billiard systems in two dimensions. The goals of the package is to provide a flexible and intuitive framework for fast implementation of billiard systems of arbitrary construction. [![](https://img.shields.io/badge/docs-latest-blue.svg)](https://JuliaDynamics.github.io/DynamicalBilliards.jl/dev) [![](https://img.shields.io/badge/docs-stable-blue.svg)](https://JuliaDynamics.github.io/DynamicalBilliards.jl/stable) [![CI](https://github.com/JuliaDynamics/DynamicalBilliards.jl/workflows/CI/badge.svg)](https://github.com/JuliaDynamics/DynamicalBilliards.jl/actions?query=workflow%3ACI) [![codecov](https://codecov.io/gh/JuliaDynamics/DynamicalBilliards.jl/branch/main/graph/badge.svg)](https://codecov.io/gh/JuliaDynamics/DynamicalBilliards.jl) [![citation](http://joss.theoj.org/papers/753469f6b18c9c38127a7727d13c87cd/status.svg)](http://joss.theoj.org/papers/753469f6b18c9c38127a7727d13c87cd) If you have used this package for research that resulted in a publication, please be kind enough to cite the papers listed in the [CITATION.bib](CITATION.bib) file. ## Features Please see the [documentation](https://JuliaDynamics.github.io/DynamicalBilliards.jl/dev) for list of features, tutorials and installation instructions. ## Acknowledgements This package is mainly developed by George Datseris. However, this development would not have been possible without significant help from other people: 1. [Lukas Hupe](https://github.com/lhupe)(@lhupe) Contributed the lyapunov spectrum calculation for magnetic propagation, implemented the boundary map function and did other contributions in bringing this package to version 2.0 (see [here](https://github.com/JuliaDynamics/DynamicalBilliards.jl/projects/1)). 1. [Diego Tapias](https://github.com/dapias) (@dapias) Contributed the lyapunov spectrum calculation method for straight propagation. 1. [David. P. Sanders](https://github.com/dpsanders) (@dpsanders) and [Ragnar Fleischmann](https://www.ds.mpg.de/person/20199/118124) contributed in fruitful discussions about the programming and physics of Billiard systems all-around. 2. [Christopher Rackauckas](https://github.com/ChrisRackauckas) (@ChrisRackauckas) helped set-up the continuous integration, testing, documentation publishing and all around package development-related concepts. 3. [Tony Kelman](https://github.com/tkelman) (@tkelman) helped significantly in the package publication process, especially in making it work correctly without destroying METADATA.jl.
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
454
--- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: '' --- **Describe the bug** A clear and concise description of what the bug is. **Minimal Working Example** Please provide a piece of code that leads to the bug you encounter. If the code is **runnable**, it will help us identify the problem faster. **Package version** Please provide the version you use (you can do `Pkg.status("DynamicalBilliards")`.
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
502
--- name: Feature request about: Suggest an idea for this project title: '' labels: '' assignees: '' --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Describe alternatives you've considered** A clear and concise description of any alternative solutions or features you've considered.
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
7024
```@meta EditURL = "billiards_visualizations.jl" ``` # [Visualizations and Animations for Billiards](@id visualizations) All plotting and animating for DynamicalBilliards.jl lies within a few well-defined functions that use the [Makie](https://github.com/MakieOrg/Makie.jl) ecosystem. - For static plotting, you can use the function [`bdplot`](@ref) and [`bdplot_boundarymap`](@ref). - For interacting/animating, you can use the function [`bdplot_interactive`](@ref). This function also allows you to create custom animations, see [Custom Billiards Animations](@ref). - For producing videos of time evolution of particles in a billiard, use [`bdplot_video`](@ref). ```@raw html <video width="auto" controls autoplay loop> <source src="https://raw.githubusercontent.com/JuliaDynamics/JuliaDynamics/master/videos/billiards/billiards_app.mp4?raw=true" type="video/mp4"> </video> ``` ## Plotting ```@docs bdplot bdplot_boundarymap ``` ### Plotting an obstacle with keywords ````@example billiards_visualizations using DynamicalBilliards, CairoMakie bd = billiard_sinai() fig, ax = bdplot(bd[2]) bdplot!(ax, bd[4]; color = "blue", linestyle = :dot, linewidth = 5.0) bdplot!(ax, bd[1]; color = "yellow", strokecolor = "black") fig ```` ### Plotting a billiard ````@example billiards_visualizations using DynamicalBilliards, CairoMakie bd = billiard_logo()[1] fig, ax = bdplot(bd) fig ```` ### Plotting some particle trajectories ````@example billiards_visualizations using DynamicalBilliards, CairoMakie timeseries! = DynamicalBilliards.timeseries! bd = billiard_hexagonal_sinai() p1 = randominside(bd) p2 = randominside(bd, 1.0) colors = [:red, :black] markers = [:circle, :rect] fig, ax = bdplot(bd) for (p, c) in zip([p1, p2], colors) x, y = timeseries!(p, bd, 20) lines!(ax, x, y; color = c) end bdplot!(ax, [p1, p2]; colors, particle_size = 10, marker = markers) fig ```` ### Periodic billiard plot Rectangle periodicity: ````@example billiards_visualizations using DynamicalBilliards, CairoMakie r = 0.25 bd = billiard_rectangle(2, 1; setting = "periodic") d = Disk([0.5, 0.5], r) d2 = Ellipse([1.5, 0.5], 1.5r, 2r/3) bd = Billiard(bd.obstacles..., d, d2) p = Particle(1.0, 0.5, 0.1) xt, yt, vxt, vyt, t = DynamicalBilliards.timeseries!(p, bd, 10) fig, ax = bdplot(bd, extrema(xt)..., extrema(yt)...) lines!(ax, xt, yt) bdplot!(ax, p; velocity_size = 0.1) fig ```` Hexagonal periodicity: ````@example billiards_visualizations using DynamicalBilliards, CairoMakie bd = billiard_hexagonal_sinai(0.3, 1.50; setting = "periodic") d = Disk([0.7, 0], 0.2) d2 = Antidot([0.7/2, 0.65], 0.35) bd = Billiard(bd..., d, d2) p = MagneticParticle(-0.5, 0.5, π/5, 1.0) xt, yt = DynamicalBilliards.timeseries(p, bd, 10) fig, ax = bdplot(bd, extrema(xt)..., extrema(yt)...) lines!(ax, xt, yt) bdplot!(ax, p; velocity_size = 0.1) fig ```` ### Boundary map plot ````@example billiards_visualizations using DynamicalBilliards, CairoMakie bd = billiard_mushroom() n = 100 # how many particles to create t = 200 # how long to evolve each one bmap, arcs = parallelize(boundarymap, bd, t, n) randomcolor(args...) = RGBAf(0.9 .* (rand(), rand(), rand())..., 0.75) colors = [randomcolor() for i in 1:n] # random colors fig, ax = bdplot_boundarymap(bmap, arcs, color = colors) fig ```` ## Interactive GUI ```@docs bdplot_interactive ``` ```@raw html <video width="auto" controls autoplay loop> <source src="https://raw.githubusercontent.com/JuliaDynamics/JuliaDynamics/master/videos/billiards/billiards_app.mp4?raw=true" type="video/mp4"> </video> ``` For example, the animation above was done with: ```julia using DynamicalBilliards, GLMakie l, w, r = 0.5, 0.75, 1.0 bd = billiard_mushroom(l, w, r) N = 20 ps = vcat( [MushroomTools.randomchaotic(l, w, r) for i in 1:N], [MushroomTools.randomregular(l, w, r) for i in 1:N], ) colors = [i ≤ N ? RGBf(0.1, 0.4 + 0.3rand(), 0) : RGBf(0.4, 0, 0.6 + 0.4rand()) for i in 1:2N] fig, phs, chs = bdplot_interactive(bd, ps; colors, plot_bmap = true, bmap_size = 8, tail_length = 2000, ); ``` ## Custom Billiards Animations To do custom animations you need to have a good idea of how Makie's animation system works. Have a look [at this tutorial](https://www.youtube.com/watch?v=L-gyDvhjzGQ) if you are not familiar yet. Following the docstring of [`bdplot_interactive`](@ref) let's add a couple of new plots that animate some properties of the particles. We start with creating the billiard plot and obtaining the observables: ````@example billiards_visualizations using DynamicalBilliards, CairoMakie bd = billiard_stadium(1, 1) N = 100 ps = particlebeam(1.0, 0.6, 0, N, 0.001) fig, phs, chs = bdplot_interactive(bd, ps; playback_controls=false) ```` Then, we add some axis ````@example billiards_visualizations layout = fig[2,1] = GridLayout() axd = Axis(layout[1,1]; ylabel = "log(⟨d⟩)", alignmode = Outside()) axs = Axis(layout[2,1]; ylabel = "std", xlabel = "time", alignmode = Outside()) hidexdecorations!(axd; grid = false) rowsize!(fig.layout, 1, Auto(2)) fig ```` Our next step is to create new observables to plot in the new axis, by lifting `phs, chs`. Let's plot the distance between two particles and the std of the particle y position. ````@example billiards_visualizations using Statistics: std # Define observables d_p(phs) = log(sum(sqrt(sum(phs[1].p.pos .- phs[j].p.pos).^2) for j in 2:N)/N) std_p(phs) = std(p.p.pos[1] for p in phs) t = Observable([0.0]) # Time axis d = Observable([d_p(phs[])]) s = Observable([std_p(phs[])]) # Trigger observable updates on(phs) do phs push!(t[], phs[1].T) push!(d[], d_p(phs)) push!(s[], std_p(phs)) notify.((t, d)) autolimits!(axd); autolimits!(axs) end # Plot observables lines!(axd, t, d; color = Cycled(1)) lines!(axs, t, s; color = Cycled(2)) nothing ```` The figure hasn't changed yet of course, but after we step the animation, it does: ````@example billiards_visualizations dt = 0.001 for j in 1:1000 for i in 1:9 bdplot_animstep!(phs, chs, bd, dt; update = false) end bdplot_animstep!(phs, chs, bd, dt; update = true) end fig ```` Of course, you can produce a video of this using Makie's `record` function. ## Video output ```@docs bdplot_video ``` Here is an example that changes plotting defaults to make an animation in the style of [3Blue1Brown](https://www.3blue1brown.com/). ````@example billiards_visualizations using DynamicalBilliards, CairoMakie BLUE = "#7BC3DC" BROWN = "#8D6238" colors = [BLUE, BROWN] # Overwrite default color of obstacles to white (to fit with black background) bd = billiard_stadium(1, 1) ps = particlebeam(1.0, 0.6, 0, 200, 0.01) # Notice that keyword `color = :white` is propagated to billiard plot bdplot_video( "3b1billiard.mp4", bd, ps; frames = 120, colors, dt = 0.01, tail_length = 100, figure = (backgroundcolor = :black,), framerate = 10, color = :white, ) ```` ```@raw html <video width="auto" controls autoplay loop> <source src="../3b1billiard.mp4" type="video/mp4"> </video> ```
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
6743
![DynamicalBilliards v3.0 Logo: The Julia billiard](https://github.com/JuliaDynamics/JuliaDynamics/blob/master/videos/billiards/DynamicalBilliards_logo_animated.gif?raw=true) `DynamicalBilliards` is an easy-to-use, modular and extendable Julia package for dynamical billiards in two dimensions. It is part of [JuliaDynamics](https://juliadynamics.github.io/JuliaDynamics/), an organization dedicated to creating high quality scientific software. !!! info "Latest news" DynamicalBilliards.jl v4.1 needs Julia v1.9+. Plotting is now back in this package via Julia package extensions. InteractiveDynamics.jl is obsolete. ## About Billiards A dynamical billiard is a system where a particle is propagating inside a domain, bouncing from obstacle to obstacle (i.e. the *boundary* of the domain) by a specular reflection at the boundary of the obstacles. This basic idea can be extended in many ways, one of which is replacing the particle orbit from a straight line to a circle. Billiard systems have been used extensively in mathematics, nonlinear dynamics and chaos and played an important role in the development of nonlinear science. The [wikipedia page](https://en.wikipedia.org/wiki/Dynamical_billiards) has many examples of different types of billiards. Also, the [scholarpedia](http://www.scholarpedia.org/article/Dynamical_billiards) entry is a good read on the subject. ## Features * Particles are evolved by solving *exactly* the geometric equations for intersections between lines, circles, ellipses, and other shapes. There are no approximations done regarding the dynamics. * Modular creation of a [Billiard](@ref) from well defined obstacles. Arbitrary billiard shapes can be made and no shape is "hard coded". * Full support for both *straight* and *magnetic* propagation of a particle in a billiard table. * During magnetic propagation the particle orbit is a circle instead of a line! * All features exist for both types of propagation! * See the [High Level API](@ref) to get started! * Support for creating [Random initial conditions](@ref) in an arbitrary billiard. * [Ray-Splitting](@ref): a particle may propagate through an obstacle given arbitrary transmission and refraction laws. This is also known as a "semiclassical billiard". * [Poincaré Sections](@ref) (intersections with arbitrary plane). * [Boundary Maps](@ref). * [Escape Times](@ref) & [Mean Collision Times](@ref). * [Lyapunov Exponents](@ref). * Support for both coordinate systems: 3D real space and boundary coordinates. * Novel algorithms that compute the portion of either the 2D boundary space or the 3D real space that an orbit covers as a particle evolves. See the [Phase Spaces](@ref) section. * Easy to use low-level interface, described at the [Internals](@ref) page. * Specialized tools for mushroom billiards. * Full support for [Visualizations and Animations for Billiards](@ref visualizations). * Brutal tests that confirm the package works and overcomes numerical precision issues. This package does not support finite-sized particles and, as a result, there is also no support for collision between particles. ## Citing If you have used this package for research that resulted in a publication, please be kind enough to cite the software paper associated with `DynamicalBilliards`. The DOI is https://doi.org/10.21105/joss.00458 and you can cite as: > G. Datseris, [The Journal of Open Source Software **2**, 458 (2017)](https://doi.org/10.21105/joss.00458). or if you use BibTeX: ``` @article{Datseris2017, doi = {10.21105/joss.00458}, url = {https://doi.org/10.21105/joss.00458}, year = {2017}, month = {nov}, volume = {2}, number = {19}, pages = {458}, author = {George Datseris}, title = {{DynamicalBilliards}.jl: An easy-to-use, modular and extendable Julia package for Dynamical Billiard systems in two dimensions.}, journal = {The Journal of Open Source Software} } ``` In addition, if you are using the functionality to compute Lyapunov exponents in billiards, then please cite the following Chaos publication: ``` @article{Datseris2019, doi = {10.1063/1.5099446}, url = {https://doi.org/10.1063/1.5099446}, year = {2019}, month = sep, publisher = {{AIP} Publishing}, volume = {29}, number = {9}, pages = {093115}, author = {George Datseris and Lukas Hupe and Ragnar Fleischmann}, title = {Estimating Lyapunov exponents in billiards}, journal = {Chaos: An Interdisciplinary Journal of Nonlinear Science} } ``` ## Installation This package is registered, simply use `]` to get into the package manager mode and then type `add DynamicalBilliards` to install it. The [stable documentation](https://juliadynamics.github.io/DynamicalBilliards.jl/stable/) accompanies the version installed with `add`. To confirm the validity of your installation you can run the tests of `DynamicalBilliards`. This can be done via `] test DynamicalBilliards`. ## How to easily code a Billiard We have created a [Jupyter notebook](https://nbviewer.jupyter.org/github/JuliaDynamics/JuliaDynamics/blob/master/tutorials/Billiards%20Example/billiards_example.ipynb) that showcases how easy it is to simulate a dynamical billiard using Julia. This [notebook](https://nbviewer.jupyter.org/github/JuliaDynamics/JuliaDynamics/blob/master/tutorials/Billiards%20Example/billiards_example.ipynb) is an educative example of both using Multiple Dispatch and of how the internal code of `DynamicalBilliards` works. It also highlights the extendibility of the core code. ## Support If you are having any kind of problems with `DynamicalBilliards` do not hesitate to seek for support! There are numerous ways to do that: 1. Visit our [official chatroom](https://gitter.im/JuliaDynamics/Lobby) on Gitter: https://gitter.im/JuliaDynamics/Lobby 2. Open a new issue at our [GitHub issues page](https://github.com/JuliaDynamics/DynamicalBilliards.jl/issues). ## Contributing Everyone is welcomed to contribute to `DynamicalBilliards`! If you have some new algorithm, types of Obstacles or anything new to add, do not hesitate! For formal questions about e.g. structuring of code it is best to contact us through the [gitter chatroom](https://gitter.im/JuliaDynamics/Lobby) or by opening a new Pull Request and asking for a review of your code. If you would like to help but do not have anything new to contribute, please go ahead and take a look at the [GitHub issues page](https://github.com/JuliaDynamics/DynamicalBilliards.jl/issues) of the package. Some of the existing issues are easy to solve and are there specifically for people that would like to contribute.
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
2472
# Lyapunov Exponents The Finite Time Lyapunov Spectrum (FTLS) for a 2D billiard system consists of a set of 4 numbers $\lambda_i \, , \{ i = 1, ...,4 \}$ that characterize how fast the separation of initially close initial conditions grows. It can be shown theoretically that two of these exponents must be zero ($\lambda_2$ =$\lambda_3$ = 0) and the other two are paired in such a way that they sum up to zero, i.e. $\lambda_1 = -\lambda_4$). The function provided to calculate the FTLS is ```@docs lyapunovspectrum ``` Here its basic use is illustrated ```@example lyaps using DynamicalBilliards radius = 1.0 l = 2.0 bd = Billiard(billiard_polygon(6, l; setting = "periodic")..., Disk([0., 0.], radius)) par = randominside(bd) t = 1000.0 exps = lyapunovspectrum(par, bd, t) ``` In the following example we compute the change of $\lambda_1\$ versus the distance between the disks in a hexagonal periodic billiard. ```@example lyaps using DynamicalBilliards, CairoMakie t = 5000.0 radius = 1.0 spaces = 2.0:0.1:4.4 #Distances between adjacent disks lyap_time = zero(spaces) #Array where the exponents will be stored for (i, space) in enumerate(spaces) bd = billiard_polygon(6, space/(sqrt(3)); setting = "periodic") disc = Disk([0., 0.], radius) billiard = Billiard(bd.obstacles..., disc) p = randominside(billiard) lyap_time[i] = lyapunovspectrum(p, billiard, t)[1] end fig = Figure(); ax = Axis(fig[1,1]; xlabel = L"w", ylabel = L"\lambda_1") lines!(ax,spaces, lyap_time) fig ``` The plot of the maximum exponent can be compared with the results reported by [Gaspard et. al](https://journals.aps.org/pre/abstract/10.1103/PhysRevE.51.5332) (see figure 7), showing that using just `t = 5000.0` is already enough of a statistical averaging. ## Perturbation Growth To be able to inspect the dynamics of perturbation growth in more detail, we also provide the following function: ```@docs perturbationgrowth ``` For example, lets plot the evolution of the perturbation growth using different colors for collisions with walls and disks in the Sinai billiard: ```@example lyaps using DynamicalBilliards, CairoMakie, LinearAlgebra bd = billiard_sinai() ts, Rs, is = perturbationgrowth(Particle(0.1, 0.1, 0.1), bd, 10.0) Δ = perturbationevolution(Rs) fig = Figure() ax = Axis(fig[1,1]; xlabel = L"t", ylabel = L"\log(||\Delta ||)") lines!(ts, log.(norm.(Δ))) scatter!(ts, log.(norm.(Δ)); color = [j == 1 ? :black : :red for j in is]) fig ```
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
274
```@docs MushroomTools ``` Notice that the name `MushroomTools` is exported by `DynamicalBilliards`. The functions within it are not though, so you have to access them like e.g. `MushroomTools.randomchaotic`. ```@autodocs Modules = [MushroomTools] Order = [:function] ```
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
3133
This page briefly discusses physical aspects of billiard systems. ## Pinned Particles In the case of propagation with magnetic field, a particle may be "pinned" (collision-less): There are no possible collisions that take place and the particle will revolve in circles forever. This can happen for specific initial conditions depending on your billiard table and the angular velocity ω. The function [`ispinned`](@ref) shows you whether a particle meets the conditions. ```@docs ispinned ``` In such event, the convention followed by `DynamicalBilliards` is the following: [`evolve!`](@ref) returns the expected output, however all returned vectors have only 2 entries. The collision times always have the entries `0.0, Inf`. All other returned vectors have the initial conditions, repeated once. [`evolve!`](@ref) can be given an additional `warning` keyword argument in the case of magnetic propagation, e.g. `warning = true` that throws a message whenever a pinned particle is evolved. ## Velocity measure Both `Particle` and `MagneticParticle` are assumed to **always** have a velocity vector of measure 1 during evolution. This simplifies the formulas used internally to a significant amount. However, during ray-splitting, the a `MagneticParticle` may be in areas with different angular velocities (result of the `ω_new` function). Physically, in such a situation, the velocity measure of the particle could also change. This change depends on the forces acting on the particle (e.g. magnetic field) as well as the relation of the momentum with the velocity (functional type of kinetic energy). In any case, such a change is not accounted for internally by `DynamicalBilliards`. However it is very easy to implement this by "re-normalizing" the angular velocities you use. Since the "code" velocity has measure one, the rotation radius is given by ```math r = \frac{1}{\omega_\text{code}} = \frac{v_\text{real}}{\omega_\text{real}} ``` then one simply has to adjust the values of `ω` given in the code with ```math \omega_\text{code} = \frac{\omega_\text{real}}{v_\text{real}} ``` After getting the timeseries: ```julia # These are the "code"-data. |v| = 1 always ct, poss, vels, omegas = evolve(p, bd, ttotal) xt, yt, vxt, vyt, t = timeseries(p, bd, ttotal) ``` you only need to make some final adjustment on the `vxt, vyt`. The position and time data are completely unaffected. ```julia omegas_code = omegas # real angular velocities: omegas_real = supplied_by_user # or with some user provided function: f = o -> (o == 0.5 ? 2o : o*√2) omegas_real = f.(omegas_code) # real velocity measure: vels_real = abs.(omegas_real ./ omegas_code) contt = cumsum(ct) omega_t = zeros(t) vxtreal = copy(vxt) vytreal = copy(vyt) j = 1 for i in eachindex(t) vxtreal[i] *= vels_real[j] vytreal[i] *= vels_real[j] omega_t[i] = omegas_real[j] if t[i] >= contt[j] j += 1 end end ``` Now you can be sure that the particle at time `t[i]` had real velocity `[vxtreal[i], vytreal[i]]` and was propagating with real angular velocity `omega_t[i]`.
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
10225
# Ray-Splitting Ray-splitting is a semi-classical approach to the billiard system, giving a wave attribute to the ray traced by the particle. Upon collision a particle may propagate through an obstacle (transmission & refraction) or be reflected. Following the mindset of this package, implementing a ray-splitting billiard requires only three simple steps. We will introduce them and demonstrate them using a simple example in this documentation page. ## 1. Ray-Splitting Obstacles The first step is that an [`Obstacle`](@ref) that supports ray-splitting is required to be present in your billiard table. The only new feature these obstacles have is an additional Boolean field called `pflag` (propagation flag). This field notes on which side of the obstacle the particle is currently propagating. The normal vector as well as the distance from boundary change sign depending on the value of `pflag`. The obstacles [`Antidot`](@ref), [`SplitterWall`](@ref) and [`FiniteSplitterWall`](@ref) are the equivalents of disk, wall and finite-wall for ray-splitting. Let's create a billiard with a bunch of ray-splitting obstacles! ```@example ray using DynamicalBilliards x, y = 2.0, 1.0 bdr = billiard_rectangle(x, y) sw = SplitterWall([x/2, 0.0], [x/2,y], [-1,0], true) a1 = Antidot([x/4, y/2], 0.25, "Left Antidot") a2 = Antidot([3x/4, y/2], 0.15, "Right Antidot") bd = Billiard(a1, a2, sw, bdr...) ``` ```@example ray using CairoMakie fig, ax = bdplot(bd) fig ``` (notice also that raysplitting obstacles are by default plotted with a different color and with dotted linestyle) ## 2. The `RaySplitter` structure In the second step, you have to define 2+1 functions: transmission probability, refraction angle and optionally new angular velocity after transmission. These functions, as well as which obstacles participate in ray-splitting, are bundled into a special structure: ```@docs RaySplitter ``` If you want different type of transmission/refraction functions for different obstacles, then you define multiple `RaySplitter`s. Continuing from the above billiard, let's also create some `RaySplitter` instances for it. First define a refraction function ```@example ray refraction(φ, pflag, ω) = pflag ? 0.5φ : 2.0φ ``` Then, a transmission probability function. In this example, we want to create a function that given some factor `p`, it returns a probability weighted with `p` in one direction of ray-splitting and `1-p` in another direction. ```@example ray transmission_p(p) = (φ, pflag, ω) -> begin if pflag p*exp(-(φ)^2/2(π/8)^2) else abs(φ) < π/4 ? (1-p)*exp(-(φ)^2/2(π/4)^2) : 0.0 end end ``` Notice also how we defined the function in such a way that critical refraction is respected, i.e. if `θ(φ) ≥ π/2` then `T(φ) = 0`. Although this is necessary from a physical perspective, the code does take care of it by clamping the refraction angle (see below). Lastly, for this example we will use magnetic propagation. We define functions such that the antidots also reverse the direction and magnitude of the magnetic field. ```@example ray newoantidot(x, bool) = bool ? -2.0x : -0.5x newowall(x, bool) = bool ? 0.5x : 2.0x ``` Now we create the [`RaySplitter`](@ref) instances we want ```@example ray raywall = RaySplitter([3], transmission_p(0.5), refraction, newowall) raya = RaySplitter([1, 2], transmission_p(0.8), refraction, newoantidot) ``` Because we want to use same functions for both antidots, we gave both indices in `raya`, `[1, 2]` (which are the indices of the antidots in the billiard `bd`). ## 3. Evolution with Ray-Splitting The third step is trivial. After you have created your `RaySplitter`(s), you simply pass them into `evolve` or `timeseries` as a fourth argument! If you have many instances of `RaySplitter` you pass a tuple of them. For example, ```@example ray using Random, CairoMakie timeseries = DynamicalBilliards.timeseries Random.seed!(42) p = randominside(bd, 1.0) raysplitters = (raywall, raya) xt, yt, vxt, vyt, tt = timeseries(p, bd, 100, raysplitters) fig, ax = bdplot(bd) lines!(ax, xt, yt) scatter!(ax, xt[[1, 100]], yt[[1, 100]]; color = "black") fig ``` You can see that at some points the particle crossed the boundaries of the red obstacles, which allow for ray splitting. !!! info "Resetting the billiard" Notice that evolving a particle inside a billiard always mutates the billiard if ray-splitting is used. This means that you should always set the fields `pflag` of some obstacles to the values you desire after *each* call to `evolve`. If you use the function [`randominside`](@ref) you must definitely do this! The function `reset_billiard!(bd)` turns all `pflag`s to `true`. !!! warning "Angle of refraction is clamped" Internally we clamp the output of the angle of refraction function. Let `c = DynamicalBilliards.CLAMPING_ANGLE` (currently `c = 0.1`). We clamp `θ` to `-π/2 + c ≤ θ ≤ π/2 - c`. This is so that the relocating algorithm does not fall into an infinite loop. You can change the value of `c` but very small values can lead to infinite loops in extreme cases. ## The Ray-Splitting Algorithm In this section we describe the algorithm we follow to implement the ray-splitting process. Let $T$ denote the transmission function, $\theta$ the refraction function and $\omega_{\text{new}}$ the new angular velocity function. The following describes the process after a particle has reached an obstacle that supports ray-splitting. 1. Find the angle of incidence $\phi' = \pi - \arccos(\vec{v} \cdot \vec{n}) = \arccos(\vec{v} \cdot (-\vec{n}))$ with $\vec{n}$ the normal vector at collision point. Notice that we use here $-\vec{n}$ because the velocity is opposing the normal vector before the collision happens. Using $-\vec{n}$ gives the angle between 0 and $\pi/2$ instead of $\pi/2$ to $\pi$. 2. Find the *correct* sign of the incidence angle, $\phi = \pm \phi'$. Specifically, use the cross product: if the third entry of $\vec{v} \times \vec{n}$ is negative, then have minus sign. The "correct" sign debates on whether the velocity vector is to the right or to the left of $(-\vec{n})$. This is important for finding the correct transmission angle and/or probability. 3. Check if $T(\phi, \verb|pflag|, \omega) > \text{random}()$. If not, do standard specular reflection. 4. If ray-splitting happens, then relocate the particle so that it is on the *other* side of the colliding obstacle. This contrasts the main evolution algorithm of this billiard package. 5. Re-compute the *correct* angle of incidence, as the position of the particle generally changes with relocating. 6. Find refraction angle $\theta(\phi, \verb|pflag|, \omega)$. Notice that this is a relative angle with respect to the normal vector. Also notice that $\theta$ may have opposite sign from $\phi$. It depends on the user if they want to add anomalous refraction. 7. Set `obstacle.pflag = !obstacle.pflag` for *all* obstacles affected by the current `RaySplitter`. This reverses $\vec{n}$ to $-\vec{n}$ as well! So from now on $\vec{n}$ is the opposite than what it was at the beginning of the algorithm! 8. Find the refraction angle in absolute space. First find $a = \text{atan}(n_y, n_x)$ and then set $\Theta = a + \theta$. 9. Perform refraction, i.e. set the particle velocity to the direction of $\Theta$. 10. Scale the magnetic field, i.e. set `p.omega` = $\omega_{\text{new}}(\omega, \verb|!pflag|)$. It is important to note that we use `!pflag` because we have already changed the `pflag` field. ## Physics of the Ray-Splitting Functions If `T` is the transmission probability function, then the condition for transmission is simply: `T(φ, pflag, ω) > rand()`. If it returns `true`, transmission (i.e. ray-splitting) will happen. The functions given to [`RaySplitter`](@ref) should have some properties in order to have physical meaning. In order to test if the `RaySplitter` you have defined has physical meaning, the function `isphysical` is provided ```@docs isphysical ``` ## Snell's Law In classical geometric optics, the refraction of a ray of light moving from one medium to another is described by Snell's law. For an angle of incidence of $\phi$, the refraction angle $\theta$ is determined by the equation ```math \frac{sin(\phi)}{\sin(\theta)} = \frac{n'}{n} ``` where $n$ and $n'$ are the respective refractive indices of the media. To easily simulate these relations in `DynamicalBilliards`, the function `law_of_refraction` can be used to set up ray-splitting according to this law. ```@docs law_of_refraction ``` ## Animation of Inverse Billiards Here we will show an application of *inverse* billiards, where particles go in and out of a billiard, while taking advantage of the existence of a strong magnetic field outside of the billiard to return. As always, we define the ray-splitting functions: ```@example ray using DynamicalBilliards trans(args...) = 1.0 # always perfect transmission refra(φ, pflag, ω) = pflag ? 0.8φ : 1.25φ # refraction angle neww(ω, pflag) = pflag ? 2.0 : 0.4 ``` Now, when we define the [`RaySplitter`](@ref) instance we will choose a different value for `affect`: ```@example ray ray = RaySplitter([1,2,3,4], trans, refra, neww, affect = (i) -> SVector(1,2,3,4)) ``` We initialize a simple rectangular billiard and a particle ```@example ray bd = billiard_rectangle(setting = "ray-splitting") p = MagneticParticle(0.4, 0.6, 0.0, 0.4) ``` [`bdplot_interactive`](@ref) does not accept ray-splitters yet (but it is easy if you want to do a PR). Nevertheless, doing an animation is still straightforward: ```@example ray using CairoMakie timeseries = DynamicalBilliards.timeseries fig, ax = bdplot(bd) xlims!(ax, (-1, 2)); ylims!(ax, (-1, 2)) # zoom out xt, yt = timeseries(p, bd, 10.0, (ray,)) D = 300 xta = Observable(xt[1:D]) yta = Observable(yt[1:D]) lines!(ax, xta, yta; color = :green) record(fig, "inverse_billiard.mp4", D+1:length(xt); framerate = 30) do i push!(xta[], xt[i]); popfirst!(xta[]) push!(yta[], yt[i]); popfirst!(yta[]) notify.((xta, yta)) end ``` ```@raw html <video width="auto" controls autoplay loop> <source src="../inverse_billiard.mp4" type="video/mp4"> </video> ```
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
9145
# High Level API `DynamicalBilliards` was created with ease-of-use as its main cornerstone. With 3 simple steps, the user can get the output of the propagation of a particle in a billiard. In general, the workflow of `DynamicalBilliards` follows these simple steps: 1. Create a billiard. 2. Create particles inside that billiard. 3. Get the output you want by using one of the high level functions. Adding more complexity in your billiard does not add complexity in your code. For example, to implement a ray-splitting billiard you only need to define one additional variable, a [`RaySplitter`](@ref) and pass it to the high level functions. After reading through this page, you will be able to use almost all aspects of `DynamicalBilliards` with minimal effort. !!! tip "Visualizations" Visualizing the billiards, particles, and their motion is one of the most important parts of the `DynamicalBilliards`. It is not discussed in this page however, but rather in the [Visualizing & Animating](@ref visualizations) page. ## Billiard A [`Billiard`](@ref) is simply a collection of [`Obstacle`](@ref) subtypes. Particles are propagating inside a `Billiard`, bouncing from obstacle to obstacle while having constant velocity in-between. There is a tutorial on how to create your own billiard. In addition, there are many pre-defined billiards that can be found in the [Standard Billiards Library](@ref) section. That is why knowing how to construct a [`Billiard`](@ref) is not important at this point. In this page we will be using the Bunimovich billiard as an example: ```@example 2 using DynamicalBilliards bd = billiard_bunimovich() ``` ## Particles A "particle" is that thingy that moves around in the billiard. It always moves with velocity of measure 1, by convention. Currently there are two types of particles: * [`Particle`](@ref), which propagates as a straight line. * [`MagneticParticle`](@ref), which propagates as a circle instead of a line (similar to electrons in a perpendicular magnetic field). To make a particle, provide the constructor with some initial conditions: ```@example 2 x0 = rand(); y0 = rand(); φ0 = 2π*rand() p = Particle(x0, y0, φ0) ``` To create a `MagneticParticle` simply provide the constructor with one more number, the angular velocity: ```@example 2 ω = 0.5 mp = MagneticParticle(x0, y0, φ0, ω) ``` When creating a billiard or a particle, the object is printed with `{Float64}` at the end. This shows what type of numbers are used for *all* numerical operations. If you are curious you can learn more about it in the [Numerical Precision](@ref). You can initialize several particles with the same direction but slightly different position is the following function: ```@docs particlebeam ``` !!! danger "Particles must be inside the Billiard!" Keep in mind that the particle must be initialized **inside a billiard** for any functionality to work properly and make sense. If you are not sure what we mean by that, then you should check out the [Internals](@ref) page. ## Random initial conditions If you have a `Billiard` which is not a rectangle, creating many random initial conditions inside it can be a pain. Fortunately, we have the following function: ```@docs randominside randominside_xyφ ``` For example: ```@example 2 p = randominside(bd) ``` and ```@example 2 mp = randominside(bd, ω) ``` `randominside` always creates particles with same number type as the billiard. ## `evolve` & `timeseries` Now that we have created a billiard and a particle inside, we want to evolve it! There is a simple function for that, called `evolve!` (or `evolve` if you don't want to mutate the particle), which returns the time, position and velocities at the collision points: ```@docs evolve! ``` Forget the ray-splitting part for now (see [Ray-Splitting](@ref)). Let's see an example: ```@example 2 ct, poss, vels = evolve(p, bd, 100) for i in 1:5 println(round(ct[i], digits=3), " ", poss[i], " ", vels[i]) end ``` Similarly, for magnetic propagation ```@example 2 ct, poss, vels, ω = evolve(mp, bd, 100) for i in 1:10 println(round(ct[i], digits=3), " ", poss[i], " ", vels[i]) end ``` The above return types are helpful in some applications. In other applications however one prefers to have the time series of the individual variables. For this, the `timeseries` function is used: ```@docs DynamicalBilliards.timeseries! ``` For example: ```@example 2 xt, yt, vxt, vyt, t = timeseries(p, bd, 100) # print as a matrix: hcat(xt, yt, vxt, vyt, t)[1:5, :] ``` Same story for magnetic particles: ```@example 2 # evolve the magnetic particle instead: xt, yt, vxt, vyt, t = timeseries(mp, bd, 100) # print as a matrix: hcat(xt, yt, vxt, vyt, t)[1:5, :] ``` Sometimes we may need information about which obstacles a particle visited, in which sequence, and when. For this we have the following function: ```@docs visited_obstacles! ``` !!! note "Type of `t`" Remember that the behavior of time evolution depends on the type of the `t` argument, which represents "total amount". If it is `AbstractFloat`, it represents total amount of time, but if it is `Int` it represents total number of collisions. ## Poincaré Sections ```@docs psos ``` For example, the surface of section in the periodic Sinai billiard with magnetic field reveals the mixed nature of the phase-space: ```@example psos using DynamicalBilliards, CairoMakie t = 100; r = 0.15 bd = billiard_sinai(r, setting = "periodic") # the direction of the normal vector is IMPORTANT!!! # (always keep in mind that ω > 0 means counter-clockwise rotation!) plane = InfiniteWall([0.5, 0.0], [0.5, 1.0], [-1.0, 0.0]) posvector, velvector = psos(bd, plane, t, 1000, 2.0) c(a) = length(a) == 1 ? "#6D44D0" : "#DA5210" fig = Figure(); ax = Axis(fig[1,1]; xlabel = L"y", ylabel=L"v_y") for i in 1:length(posvector) poss = posvector[i] # vector of positions vels = velvector[i] # vector of velocities at the section L = length(poss) if L > 0 #plot y vs vy y = [a[2] for a in poss] vy = [a[2] for a in vels] scatter!(y, vy; color = c(y), markersize = 2) end end fig ``` !!! note "`psos` operates on the unit cell" The `psos` function always calculates the crossings *within* the unit cell of a periodic billiard. This means that no information about the "actual" position of the particle is stored, everything is modulo the unit cell. This can be seen very well in the above example, where there aren't any entries in the region `0.5 - r ≤ y ≤ 0.5 + r`. Of course it is very easy to "re-normalize" the result such that it is coherent. The only change we have to do is simply replace the line `y = [a[2] for a in poss]` with ```julia y = [a[2] < 0.5 ? a[2] + 1 : a[2] for a in poss] ``` ## Escape Times It is very easy to create your own function that calculates an "escape time": the time until the particle leaves the billiard by meeting a specified condition. There is also a high-level function for this though: ```@docs escapetime ``` To create a "door" simply use [`FiniteWall`](@ref). For example, the default implementation of the mushroom billiard has a "door" at the bottom of the stem. Thus, ```@example 2 using Statistics bd = billiard_mushroom() et = zeros(100) for i ∈ 1:100 particle = randominside(bd) et[i] = escapetime(particle, bd, 10000) end println("Out of 100 particles, $(count(x-> x != Inf, et)) escaped") println("Mean escape time was $(mean(et[et .!= Inf]))") ``` Of course, `escapetime` works with `MagneticParticle` as well ```@example 2 escapetime(randominside(bd, 1.0), bd, 10000) ``` ## Mean Collision Times Because the computation of a mean collision time (average time between collisions in a billiard) is often a useful quantity, the following function computes it ```@docs meancollisiontime ``` For example, ```@example 2 bd = billiard_sinai() meancollisiontime(randominside(bd), bd, 10000.0) ``` ## Parallelization ```@docs parallelize ``` Here are some examples ```@example 2 bd = billiard_stadium() particles = [randominside(bd) for i in 1:1000] parallelize(meancollisiontime, bd, 1000, particles) ``` ```@example 2 parallelize(lyapunovspectrum, bd, 1000, particles) ``` ## It's all about bounce! The main propagation algorithm used by `DynamicalBilliards` is bundled in the following well-behaving function: ```@docs bounce! ``` `bounce!` is the function used internally by all high-level functions, like [`evolve!`](@ref), [`boundarymap`](@ref), [`escapetime`](@ref), etc. This is the function a user should use if they want to calculate other things besides what is already available in the high level API. ## Standard Billiards Library !!! tip "You can also use keywords!" All standard billiards have a function version that accepts keyword arguments instead of positional arguments, for ease of use. ```@docs billiard_rectangle billiard_sinai billiard_bunimovich billiard_mushroom billiard_polygon billiard_vertices billiard_iris billiard_hexagonal_sinai billiard_raysplitting_showcase billiard_logo ``` ## Particle types ```@docs Particle MagneticParticle ```
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
4813
# Internals This page is **not** part of the public API defined by `DynamicalBilliards`. Consider it something like a *developer's guide*. ## Implementation Before talking about the low level methods that enable everything to work nicely together, let's talk about how this package works. Firstly one defines a [`Billiard`](@ref) and optionally some [`RaySplitter`](@ref) instances. Then one creates a particle inside the defined billiard. The algorithm for the propagation of a particle is the following: 1. Calculate the [`collision`](@ref) of the particle with **all** obstacles in the billiard. 2. Find the collision that happens first (in time), and the obstacle corresponding to that. 3. [`DynamicalBilliards.relocate!`](@ref) the particle, and ensure that it is **inside** the billiard. This means that [`DynamicalBilliards.distance`](@ref) between particle and obstacle is either positive or close to machine precision. 4. (Optionally) check if there is transmission for ray-splitting: `T(φ) > rand()` * If yes, perform the ray-splitting algorithm (see the [Ray-Splitting](@ref) page). * If not, then [`DynamicalBilliards.resolvecollision!`](@ref) of the particle with the obstacle (specular or periodic conditions). 5. Continue this loop for a given amount of time. Notice that the [`DynamicalBilliards.relocate!`](@ref) step is *very* important because it takes care that all particles remain inside the billiard. The exposed [`bounce!`](@ref) function bundles steps 1-4 together. ### Where is "inside"? If for some reason (finite numeric precision) a particle goes outside a billiard, then it will escape to infinity. But what *is* inside? "Inside" is defined on obstacle level by the function `distance`: ```@docs DynamicalBilliards.distance ``` Notice that for very small negative values of distance, [`collision`](@ref) takes care of finite precision issues and does not return wrong collisions. ## Numerical Precision All core types of `DynamicalBilliards` are parametrically constructed, with parameter `T <: AbstractFloat`. This means that the fields of all particles and obstacles contain numbers strictly of type `T`. You will understand why this choice happened as you continue reading this paragraph. The main concerns during evolution in a billiard table are: 1. The particle must never leak out of the billiard table. This is simply translated to the `distance` function being positive after any collision _and_ that `collision` takes care of extreme cases with very small (but negative) distance. 2. The collision time is never infinite, besides the cases of [Pinned Particles](@ref) in a magnetic billiard. These are solved with two ways: 1. After the next collision is computed, `relocate!` brings the particle to that point and calculates the `distance` with the colliding obstacle. If it is negative, it translates the particle's position by this distance, _along the normal vector_. 2. `collision` takes care of cases where the distance between particle and obstacle is less than `accuracy(::T)`. (This is necessary only for magnetic propagation, as for straight propagation checking the velocity direction with respect to the normal is always enough). Adjusting the global precision of `DynamicalBilliards` is easy and can be done by choosing the floating precision you would like. This is done by initializing your billiard table with parametric type `T`, e.g. `bd = billiard_sinai(Float16(0.3))`. This choice will propagate to the entire `bd`, all particles resulting from [`randominside`](@ref), **as well as the entire evolution process**. !!! danger "BigFloats" Evolution with `BigFloat` in `DynamicalBilliards` is on average 3 to 4 orders of magnitude slower than with `Float64`. --- ## Collision Times ```@docs collision next_collision ``` ## Non-Exported Internals ### Obstacle related ```@docs DynamicalBilliards.normalvec DynamicalBilliards.cellsize ``` ### Propagation ```@docs DynamicalBilliards.propagate! DynamicalBilliards.resolvecollision! DynamicalBilliards.relocate! DynamicalBilliards.specular! DynamicalBilliards.periodicity! ``` ### Timeseries ```@docs DynamicalBilliards.extrapolate ``` --- !!! warning "Cyclotron center is a field of `MagneticParticle`" For almost all operations involving a `MagneticParticle`, the center of the cyclotron is required. In order to compute this center only when it physically changes, we have made it a field of the `struct`. This means that after changing the position or velocity of the particle, this center must be changed by doing `mp.center = DynamicalBilliards.find_cyclotron(mp)`. The [`bounce!`](@ref) function takes care of that in the most opportune moment, but if you want to write your own specific low level function, do not forget this point!
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
2942
# Phase Spaces ## Coordinate Systems Any billiard has two coordinate systems: 1. The "real" coordinates, i.e. the coordinates that specify the full, three-dimensional phase space: $x, y, \phi$. 2. The "boundary" coordinates, also known as Birkhoff coordinates, which instead reduce the continuous billiard into a map, by only considering the collision points. These coordinates are only two: $\xi, \sin(\phi_n)$, with $\xi$ being the parametrization of the arc length and $\phi_n$ being the angle as measured from the normal vector. With `DynamicalBilliards` it is very easy to switch between the two coordinate systems, using: ```@docs to_bcoords from_bcoords arcintervals ``` ## Boundary Maps Boundary maps can be obtained with the high level function ```@docs boundarymap ``` For example, take a look at boundary maps of the mushroom billiard, which is known to have a mixed phase space: ```@example coords using DynamicalBilliards, CairoMakie bd = billiard_mushroom() n = 100 # how many particles to create t = 200 # how long to evolve each one bmap, arcs = parallelize(boundarymap, bd, t, n) randomcolor(args...) = RGBAf(0.9 .* (rand(), rand(), rand())..., 0.75) colors = [randomcolor() for i in 1:n] # random colors fig, ax = bdplot_boundarymap(bmap, arcs; color = colors) fig ``` ## Phase Space Portions It is possible to compute the portion of phase space covered by a particle as it is evolved in time. We have two methods, one for the "boundary" coordinates (2D space) and one for the "real" coordinates (3D space): ```@docs boundarymap_portion phasespace_portion ``` For example, for mushroom billiards the ratio of the chaotic-to-total phase space is known **analytically** for both the full 3D [1] space as well as the boundary 2D [2] space: ```math \begin{aligned} g_\text{c, 3D} &= \frac{2 \, \pi r^{2} - 4 \, r^{2} \arccos\left(\frac{w}{2 \, r}\right) + 4 \, l w + \sqrt{4 \, r^{2} - w^{2}} w}{2 \, {\left(\pi r^{2} + 2 \, l w\right)}}\\ g_\text{c, 2D} &= \frac{\pi w + 2 \, w \arccos\left(\frac{w}{2 \, r}\right) + 4 \, l + 4 \, r - 2 \, \sqrt{4 \, r^{2} - w^{2}}}{2 \, {\left(\pi r + 2 \, l + 2 \, r\right)}} \end{aligned} ``` We can easily confirm those formulas: ```@example phasespace using DynamicalBilliards t = 1000000.0 l = 1.0; r = 1.0; w = 0.4 bd = billiard_mushroom(l, w, r) p = MushroomTools.randomchaotic(l, w, r) ratio, dic = boundarymap_portion(bd, t, p, 0.01) trueratio = MushroomTools.g_c_2D(l,w,r) println("2D numeric - theory: $(abs(ratio - trueratio))") ratio = phasespace_portion(bd, t, p, 0.01) trueratio = MushroomTools.g_c_3D(l,w,r) println("3D numeric - theory: $(abs(ratio - trueratio))") ``` Of course, increasing evolution time and decreasing boxsize will bring higher accuracy. ## References [1] : A. H. Barnett & T. Betcke, *Quantum mushroom billiards*, [Chaos, 17(4) (20017)](https://doi.org/10.1063/1.2816946) [2] : Lukas Hupe, B.Sc. Thesis (2018), *to be published*
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
5503
# Creating your own Billiard ## The `Billiard` type ```@docs Billiard ``` --- A `Billiard` is a wrapper of a `Tuple` of `Obstacle`s. The abstract Type `Obstacle{T}` is the supertype of all objects that a particle may collide with, with global billiard precision of type `T`. There are many premade functions that construct well-known billiards, like the periodic Sinai billiard. You can find all of them at the [Standard Billiards Library](@ref). To create a custom billiard from scratch, it is often convenient to start with an empty `Vector{Obstacle{T}}`: ```@example tut1 using DynamicalBilliards bd = Obstacle{Float64}[] # T<: AbstractFloat ``` and then you create your obstacles one by one and add them to it. All obstacles that are already defined in the package can be found at the [Obstacle Library](@ref) below. For the example of this page, we will create a hexagonal billiard with a disk in the middle step-by-step (the function [`billiard_polygon`](@ref) creates a polygonal billiard table already). The first step is to define the six walls of the billiard table. An [`InfiniteWall`](@ref) object needs to be supplemented with a start point, an end point, a normal vector and, optionally, a name. The vertex points of a regular hexagon of radius ``r`` are given by the formula: ```math (x,y) = \left( r\cos\left(\frac{2\pi i}{6}\right), r\cos\left(\frac{2\pi i}{6}\right) \right)\,, \quad \text{for i $\in$ \{1,...,6\}} ``` To create each wall object, we will implement the following loop: ```@example tut1 hexagon_vertex = (r) -> [ [r*cos(2π*i/6), r*sin(2π*i/6)] for i in 1:6] hexver = hexagon_vertex(2.0) for i in eachindex(hexver) starting = hexver[i] ending = hexver[mod1(i+1, length(hexver))] w = ending - starting normal = [-w[2], w[1]] wall = InfiniteWall(starting, ending, normal, "wall $i") push!(bd, wall) end summary(bd) ``` !!! note "Keep the size around 1." Because the precision in `DynamicalBilliards` is measured using `eps(T)` with `T` the number type, it is advised to keep the size of the billiard in the order of magnitude of 1. Having overly large billiards with sizes of 100 or more can lead to accuracy loss! The `normal` vector of a `Wall` obstacle is necessary to be supplemented by the user because it must point towards where the particle is expected to come from. If `w` is the vector (wall) pointing from start- to end-point then the vector `[-w[2], w[1]]` is pointing to the left of `w` and the vector `[w[2], -[w1]]` is pointing to the right. Both are normal to `w`, but you have to know which one to pick. In this case this is very easy, since the normal has to simply point towards the origin. !!! note "There is no glue." In `DynamicalBilliards` there is no "glue" that combines obstacles or "sticks" them together, ensuring that the billiard is closed. You only have to take care that their ends meet geometrically. Even obstacle overlapping is allowed, if you want to be on the safe side! We add a disk by specifying a center and radius (and optionally a name): ```@example tut1 d = Disk([0,0], 0.8) push!(bd, d) # Make the structure required: billiard = Billiard(bd) ``` The billiard table now works for straight or magnetic propagation. To expand this to ray-splitting you have to use ray-splitting `Obstacle`s (see the tutorial on Ray-Splitting). Additional information on how to define your own `Obstacle` sub-type is given in the tutorial on [Defining your own Obstacles](@ref). If you make *any* billiard system that you think is cool and missing from this package, you are more than welcome to submit a PR extending the Standard Billiards Library with your contribution! ## Obstacle order !!! info "Obstacle order." The order that the obstacles are given to the constructor is important for the function [`boundarymap`](@ref). For any other functionality it is irrelevant. ## Convex Billiards These 2 types of walls used by `DynamicalBilliards` that behave differently during evolution: 1. [`InfiniteWall`](@ref) : This wall is not actually infinite. It has a starting and ending position. However, when the collision time is calculated, this wall is assumed to be a line (i.e. *infinite*). This is absolutely fine, as long as the billiards used are [*convex* polygons](https://en.wikipedia.org/wiki/Convex_polygon). [`SplitterWall`](@ref), [`PeriodicWall`](@ref) and [`RandomWall`](@ref) behave like `InfiniteWall` during evolution. 2. `FiniteWall` : This wall is indeed finite in every sense of the word. This means that during collision time estimation, if the collision point that was calculated lies *outside* of the boundaries of the `FiniteWall`, then the returned collision time is `Inf` (no collision). `FiniteWall` is slower than `InfiniteWall` for that reason. [`FiniteSplitterWall`](@ref) behaves like a `FiniteWall` during evolution. If you wish to create a billiard table that you know will be convex, you should then use `InfiniteWall`s for faster evolution. Notice that using [`escapetime`](@ref) requires at least one `FiniteWall` with field `isdoor=true`. ## Obstacle Library This is the list of `Obstacle`s you can use when creating your own billiard. ```@docs Obstacle ``` ### Curved ```@docs Disk RandomDisk Antidot Semicircle Ellipse ``` ### Lines ```@docs Wall InfiniteWall RandomWall PeriodicWall SplitterWall FiniteWall FiniteSplitterWall ``` --- In addition, `translate` is a helpful function: ```@docs translate ```
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
10256
# Defining your own Obstacles In this tutorial we will go through the processes of creating a new obstacle type, a `Semicircle`. This type is already used in the [`billiard_bunimovich`](@ref) and [`billiard_mushroom`](@ref) functions. !!! info "Everything uses `SVector{2}`" Fields of `Particle`s and `Obstacle`s contain all their information in 2-dimensional static vectors from module `StaticArrays`. This is important to keep in mind when extending new methods. !!! info "Extends internal APIs" Notice that implementing your own obstacle requires you to extend methods that _do not_ belong to the public API. !!! note "See also the `Ellipse` PR" Pull Request [#159](https://github.com/JuliaDynamics/DynamicalBilliards.jl/pull/159) implements the [`Ellipse`](@ref) obstacle, step by step, by following the tutorial of this page. All commits are commented and it can be a second helpful guide on how to implement an obstacle. ## Type Definition The first thing you have to do is make your new type a sub-type of `Obstacle{T}` (or any other abstract sub-type of it). We will do: ```julia struct Semicircle{T<:AbstractFloat} <: Circular{T} # <: Obstacle{T} c::SVector{2,T} # this MUST be a static vector r::T facedir::SVector{2,T} # this MUST be a static vector name::String # this is an OPTIONAL field end ``` `c` is the center and `r` is the radius of the full circle. `facedir` is the direction which the semicircle is facing, which is also the direction of its "open" face. `name` is an optional field, that allows one to easily identify which obstacle is which. It is also used when printing a [`Billiard`](@ref). If not used, then `string(typeof(obstacle))` is used instead. Notice that the `struct` **must be** parameterized by `T<:AbstractFloat` (see the [Numerical Precision](@ref) page for more). For convenience, we will also define: ```julia function Semicircle( c::AbstractVector{T}, r::Real, facedir, name = "Semicircle") where {T<:Real} S = T <: Integer ? Float64 : T return Semicircle{S}(SVector{2,S}(c), convert(S, abs(r)), name) end ``` so that constructing a `Semicircle` is possible from arbitrary vectors. ## Necessary Methods The following functions must obtain methods for `Semicircle` (or any other custom `Obstacle`) in order for it to work with `DynamicalBilliards`: 1. [`DynamicalBilliards.normalvec`](@ref) 2. [`DynamicalBilliards.distance`](@ref) (with arguments `(position, obstacle)`) 3. [`DynamicalBilliards.collision`](@ref) with `Particle` Assuming that upon collision a specular reflection happens, then you don't need to define a method for [`DynamicalBilliards.specular!`](@ref). You can however define custom methods for [`DynamicalBilliards.specular!`](@ref), which is what we have done e.g. for [`RandomDisk`](@ref). The first method is very simple. *(Remember that in Julia to extend a function with a new method you must preface it with the parent module)* ```julia DynamicalBilliards.normalvec(d::Semicircle, pos) = normalize(d.c - pos) ``` Since the function is only used during `distance` and [`DynamicalBilliards.resolvecollision!`](@ref) and since we will be writing explicit methods for the first, we don't have to care about what happens when the particle is far away from the boundary. The `distance` method is a bit tricky. Since the type already subtypes `Circular`, the following definition from `DynamicalBilliards` applies: ```julia distance(pos::AbstractVector, d::Circular) = norm(pos - d.c) - d.r ``` However, the method must be expanded. That is because when the particle is on the "open" half of the disk, the distance is not correct. We write: ```julia SV = SVector{2} #convenience function DynamicalBilliards.distance(pos::AbstractVector{T}, s::Semicircle{T}) where {T} # Check on which half of circle is the particle v1 = pos .- s.c nn = dot(v1, s.facedir) if nn ≤ 0 # I am "inside semicircle" return s.r - norm(pos - s.c) else # I am on the "other side" end1 = SV(s.c[1] + s.r*s.facedir[2], s.c[2] - s.r*s.facedir[1]) end2 = SV(s.c[1] - s.r*s.facedir[2], s.c[2] + s.r*s.facedir[1]) return min(norm(pos - end1), norm(pos - end2)) end end ``` Notice that this definition always returns positive distance when the particle is on the "other side". Finally, the method for [`collision`](@ref) is by far the most *trickiest*. But, with pen, paper and a significant amount of patience, one can find a way: ```julia function DynamicalBilliards.collision(p::Particle{T}, d::Semicircle{T})::T where {T} dc = p.pos - d.c B = dot(p.vel, dc) #velocity towards circle center: B > 0 C = dot(dc, dc) - d.r*d.r #being outside of circle: C > 0 Δ = B^2 - C Δ ≤ 0 && return DynamicalBilliards.nocollision(T) sqrtD = sqrt(Δ) nn = dot(dc, d.facedir) if nn ≥ 0 # I am NOT inside semicircle # Return most positive time t = -B + sqrtD else # I am inside semicircle: t = -B - sqrtD # these lines make sure that the code works for ANY starting position: if t ≤ 0 || distance(p, d) ≤ accuracy(T) t = -B + sqrtD end end # This check is necessary to not collide with the non-existing side newpos = p.pos + p.vel * t if dot(newpos - d.c, d.facedir) ≥ 0 # collision point on BAD HALF; return DynamicalBilliards.nocollision(T) end # If collision time is negative, return Inf: t ≤ 0.0 ? DynamicalBilliards.nocollision(T) : (t, p.pos + t*p.vel) end ``` And that is all. The obstacle now works perfectly fine for straight propagation. !!! note "Ray-Splitting support" Supporting ray-splitting for your custom obstacle is very easy. The first step is to give it a field called `pflag`, which is a `Bool`. The second step is to ensure that `collisiontime` works properly for particles coming from both directions of the obstacle! Both inside or outside! This is implemented for `Ellipse` in Pull Request [#159](https://github.com/JuliaDynamics/DynamicalBilliards.jl/pull/159). ## Optional Methods 1. [`DynamicalBilliards.cellsize`](@ref) : Enables [`randominside`](@ref) with this obstacle. 1. [`collision`](@ref) with [`MagneticParticle`](@ref) : enables magnetic propagation 2. [`bdplot`](@ref) with `obstacle` : enables plotting and animating 3. [`DynamicalBilliards.specular!`](@ref) with `offset` : Allows [`lyapunovspectrum`](@ref) to be computed. 4. [`to_bcoords`](@ref) : Allows the [`boundarymap`](@ref) and [`boundarymap_portion`](@ref) to be computed. 5. [`from_bcoords`](@ref) : Allows [`phasespace_portion`](@ref) to be computed. The [`DynamicalBilliards.cellsize`](@ref) method is kinda trivial: ```julia function DynamicalBilliards.cellsize(a::Semicircle{T}) where {T} xmin, ymin = a.c - a.r xmax, ymax = a.c + a.r return xmin, ymin, xmax, ymax end ``` The [`collision`](@ref) method for [`MagneticParticle`](@ref) is also tricky, however it is almost identical with the method for the general `Circular` obstacle: ```julia function DynamicalBilliards.collision(p::MagneticParticle{T}, o::Semicircle{T})::T where {T} ω = p.omega pc, rc = cyclotron(p) p1 = o.c r1 = o.r d = norm(p1-pc) if (d >= rc + r1) || (d <= abs(rc-r1)) return nocollision(T) end # Solve quadratic: a = (rc^2 - r1^2 + d^2)/2d h = sqrt(rc^2 - a^2) # Collision points (always 2): I1 = SVector{2, T}( pc[1] + a*(p1[1] - pc[1])/d + h*(p1[2] - pc[2])/d, pc[2] + a*(p1[2] - pc[2])/d - h*(p1[1] - pc[1])/d ) I2 = SVector{2, T}( pc[1] + a*(p1[1] - pc[1])/d - h*(p1[2] - pc[2])/d, pc[2] + a*(p1[2] - pc[2])/d + h*(p1[1] - pc[1])/d ) # Only consider intersections on the "correct" side of Semicircle: cond1 = dot(I1-o.c, o.facedir) < 0 cond2 = dot(I2-o.c, o.facedir) < 0 # Collision time, equiv. to arc-length until collision point: θ, I = nocollision(T) if cond1 || cond2 for (Y, cond) in ((I1, cond1), (I2, cond2)) if cond φ = realangle(p, o, Y) φ < θ && (θ = φ; I = Y) end end end # Collision time = arc-length until collision point return θ*rc, I end ``` Then, we add swag by writing a method for [`bdplot`](@ref): ```julia using PyPlot # brings plot(::Obstacle; kwargs...) into scope function DynamicalBilliards.bdplot!(ax::Axis, d::Semicircle; kwargs...) theta1 = atan(d.facedir[2], d.facedir[1])*180/π + 90 # ... end ``` To enable computation of Lyapunov exponents in billiards with your obstacle, you have to write another method for `specular!` that also handles the evolution of perturbation vectors in tangent space. For this, the method has to accept an argument of type `Vector{SVector{4, T}}`, which contains the four perturbation vectors corresponding to the four Lyapunov exponents. Finding a formula for the evolution of the perturbations requires some tricky calculations. Fortunately for us, the results for general circular obstacles were already determined by Dellago, Posch and Hoover [1] – we just have to implement them. ```julia function DynamicalBilliards.specular!(p::Particle{T}, o::Circular{T}, offset::Vector{SVector{4, T}}) where {T<:AbstractFloat} n = normalvec(o, p.pos) ti = SV{T}(-p.vel[2],p.vel[1]) cosa = -dot(n, p.vel) p.vel = p.vel + 2*cosa*n tf = SV{T}(-p.vel[2], p.vel[1]) for k in 1:4 δqprev = offset[k][δqind] δpprev = offset[k][δpind] # Formulas from Dellago, Posch and Hoover, PRE 53, 2, 1996: 1485-1501 (eq. 27) # with norm(p) = 1 δq = δqprev - 2*dot(δqprev,n)*n δp = δpprev - 2*dot(δpprev,n)*n - curvature(o)*2/o.r*dot(δqprev,ti)/cosa*tf ### offset[k] = vcat(δq, δp) end end @inline curvature(::Semicircle) = -1 @inline curvature(::Disk) = +1 ``` Note that calculating Lyapunov exponents for magnetic particles requires a separate method, as the formulas are different for magnetic propagation. Finally, we also add a methods for [`to_bcoords`](@ref) and [`from_bcoords`](@ref). For them, see the relevant source file (use `@edit`). **References** [1]: Dellago et al., Phys. Rev. E 53, 1485 (1996).
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
4.1.0
c92c935dfcb4f5f048d169b390d9f63b59c3dda1
docs
7284
--- title: 'DynamicalBilliards.jl: An easy-to-use, modular and extendable Julia package for Dynamical Billiard systems in two dimensions.' tags: - billiards - physics - chaos - escape - obstacle authors: - name: George Datseris orcid: 0000-0002-6427-2385 affiliation: 1 affiliations: - name: Max Planck Institute for Dynamics and Self-Organization index: 1 date: 03 July 2018 bibliography: paper.bib --- # Summary [DynamicalBilliards.jl](http://orcid.org/0000-0002-6427-2385) is a package about two-dimensional (dynamical) billiard systems written in its entirety in Julia. It is easy to use, and easy to be extended. It is accompanied by a [detailed documentation archive](https://juliadynamics.github.io/DynamicalBilliards.jl/stable/) with a lot of tutorials, example code as well as information about the physical algorithms at play. The package is mainly used to simulate any kind of two-dimensional system where particle motion is interrupted by collisions, e.g., a gas infused with big molecules. # Features The features of the DynamicalBilliards.jl, as of version v2.0.0, are: * Modular creation of a billiard from well defined obstacles. Arbitrary billiard shapes can be made and no shape is "hard coded". * Full support for both *straight* and *magnetic* propagation of a particle in a billiard table. * During magnetic propagation the particle orbit is a circle instead of a line! * All features exist for both types of propagation! * Support for creating random initial conditions in an arbitrary billiard. * Ray-splitting implementation: a particle may propagate through an obstacle given arbitrary transmission and refraction laws. This is also known as a "semiclassical billiard". * Poincaré surfaces of section (intersections with arbitrary plane). * Boundary maps. * Escape times & mean collision times. * Lyapunov exponents. * Novel algorithms that compute the portion of either the 2D boundary space or the 3D real space that an orbit covers as a particle evolves. * Easy to use low-level interface. * Specialized tools for mushroom billiards. * Full support for visualizing and animating billiards and motion in billiards. * Brutal tests that confirm the package works and overcomes numerical precision issues. # Description Billiard systems have been used extensively in scientific research and played a crucial role in the development of Chaos theory. A famous example is the Sinai billiard (easily simulated with our package) which was one of the first low-dimensional systems proven to be ergodic [@Sinai1970]. Even though the study of billiard systems started decades ago, there are still new surprises and plenty of research to be done with them. Bunimovich and Vela-Arevalo (two pioneers in the field) summarized new insights in the field of dynamical billiards [@Bunimovich2015]. Our package has plenty of applications, due to the large amount of features. In [@Datseris] we have used it to approximate the movement of electrons in graphene, a two-dimensional semiconductor. Another application would be the motion of a particle in a gas composed of molecules much bigger than the particle, such that the collisions leave the molecules stationary. In addition, DynamicalBilliards.jl offers the first time possibility of implementing ray-splitting billiards, since, to the best of our knowledge, there is no other open sourced project that offers this. Ray-splitting is powerful as it allows one to simulate particles that tunnel through obstacles, much like a quantum particle. At the end of this paper we provide an example application in a periodic gas-like system. Finally, one more example application would be calculating the escape time of a particle in a maze of obstacles. The package is written in pure Julia [@Julia] a new programming language with many advantages. Because Julia is dynamic, it allows users to experiment with billiards flexibly and interactively and have access to a very easy-to-use high level interface. On the other hand, because Julia is as fast as C, there is no worry about the speed of the algorithms. Another advantage of using Julia is that the source code is clear, concise and very easy to understand even for beginners. This allows our package to be extendable in an almost trivial manner. In fact, in one of our [tutorial pages](https://juliadynamics.github.io/DynamicalBilliards.jl/latest/tutorials/own_obstacle/) we show users that all they need to do to define a completely new type of `Obstacle` (the things particles collide with) is only four functions, with an average of just 50 lines of code in total. Everything else is taken care of with the modular approach of our package and the power of abstraction that Julia provides. DynamicalBilliards.jl calculates exactly all collisions between particles and obstacles, by solving 1st and 2nd order polynomial equations, which results in accuracies of the order of `1e-14` (for 64-bit floating point numbers). For this to work, particles are considered point particles. This advantage of exact solutions however also comes with a drawback: our package currently does not support (a) interactions between particles and (b) external electrostatic potentials. We would like to bring into attention another new billiard package, called "Bill2D" [@Solanpaa2016], which is written in C instead, and supports interactions between particles. There is a some amount of overlap between DynamicalBilliards.jl and Bill2D, however both packages offer a lot of unique features not included in each other. # Example ![Periodic Billiard](periodic_billiard.png) In the figure we show an example application of our package. A tiny particle (blue color) is propagating in a gas of periodically located large molecules (green color). Because the mass and size of the molecules is much bigger than that of the particle, we can accept that the collisions leave the molecules unmoved. # Acknowledgements This package is mainly developed by George Datseris. However, this development would not have been possible without significant help from other people (updated 05/05/2018): 1. [Lukas Hupe](https://github.com/lhupe)(@lhupe) Contributed the Lyapunov spectrum calculation for magnetic propagation, implemented the boundary map function, the phase-space portion algorithm and did other contributions in bringing this package to version 2.0 (see [here](https://github.com/JuliaDynamics/DynamicalBilliards.jl/projects/1)). 1. [Diego Tapias](https://github.com/dapias) (@dapias) Contributed the Lyapunov spectrum calculation method for straight propagation, which was then re-written. 1. [David. P. Sanders](https://github.com/dpsanders) (`@dpsanders`) and [Ragnar Fleischmann](https://www.ds.mpg.de/person/20199/118124) contributed in fruitful discussions about the programming and physics of Billiard systems all-around. 2. [Christopher Rackauckas](https://github.com/ChrisRackauckas) (`@ChrisRackauckas`) helped set-up the continuous integration, testing, documentation publishing and all around package development-related concepts. 3. [Tony Kelman](https://github.com/tkelman) (`@tkelman`) helped significantly in the package publication process, especially in making it work correctly without destroying METADATA.jl. # References
DynamicalBilliards
https://github.com/JuliaDynamics/DynamicalBilliards.jl.git
[ "MIT" ]
1.4.3
3ba86f8b385508778d19f52031074ee4c48cedac
code
1562
module NonconvexCore const debugging = Ref(false) const show_residuals = Ref(false) export Model, DictModel, addvar!, getobjective, set_objective!, add_ineq_constraint!, add_eq_constraint!, add_sd_constraint!, decompress_symmetric, getmin, getmax, setmin!, setmax!, setinteger!, optimize, Workspace, KKTCriteria, IpoptCriteria, FunctionWrapper, Tolerance, GenericCriteria, KKTCriteria, ScaledKKTCriteria, IpoptCriteria using Parameters, Zygote, ChainRulesCore, ForwardDiff using SparseArrays, Reexport, Requires @reexport using LinearAlgebra, OrderedCollections using Reexport, Setfield import JuMP, MathOptInterface const MOI = MathOptInterface using SolverCore: log_header, log_row using JuMP: VariableRef, is_binary, is_integer, has_lower_bound, has_upper_bound, lower_bound, upper_bound, start_value, ConstraintRef, constraint_object, AffExpr, objective_function, objective_sense using DifferentiableFlatten: flatten, maybeflatten, Unflatten # General include("utilities/params.jl") include("functions/functions.jl") include("functions/value_jacobian.jl") include("functions/counting_function.jl") include("functions/sparse.jl") include("common.jl") include("utilities/callbacks.jl") include("utilities/convergence.jl") # Models include("models/model.jl") include("models/vec_model.jl") include("models/dict_model.jl") include("models/model_docs.jl") include("models/jump.jl") include("models/moi.jl") end
NonconvexCore
https://github.com/JuliaNonconvex/NonconvexCore.jl.git
[ "MIT" ]
1.4.3
3ba86f8b385508778d19f52031074ee4c48cedac
code
11236
###################################################### # Common objects and methods used for all algorithms ###################################################### abstract type AbstractOptimizer end """ Trace A struct that stores the history of solutions. """ struct Trace tr::Vector end """ Workspace Abstract Workspace, which is a struct that stores states and information needed for optimization process. Implementation depends on specific algorithm. """ abstract type Workspace end function reset!(w::Workspace, x0 = nothing) if x0 !== nothing w.x0 .= x0 end return w end """ ConvergenceState A struct that summarizes the convergence state of a solution. The fields in this struct are: - `Δx`: the infinity norm of the change in the solution `x`. - `Δf`: the change in the objective value `f`. - `relΔf`: the ratio of change in the objective value `f`. - `kkt_residual`: the Karush-Kuhn-Tucker (KKT) residual of the solution. If [`ScaledKKTCriteria`](@ref) is used instead of [`KKTCriteria`](@ref), the `kkt_residual` will be divided by a factor. - `ipopt_residual`: the modified KKT residual used in the IPOPT solver. - `infeas`: maximum infeasibility amount. This is 0 if the solution is feasible. - `x_converged`: true if `Δx` is less than the `x` tolerance in [`MMAOptions`](@ref). - `fabs_converged`: true if `Δf` is less than the `f` tolerance in [`MMAOptions`](@ref). - `frel_converged`: true if `relΔf` is less than the `f` tolerance in [`MMAOptions`](@ref). - `kkt_converged`: true if the `kkt_residual` is less than the KKT tolerance in [`MMAOptions`](@ref). - `ipopt_converged`: true if the `ipopt_residual` is less than the KKT tolerance in [`MMAOptions`](@ref). - `infeas_converged`: true if `infeas` is less than the infeasibility tolerance in [`MMAOptions`](@ref). - `f_increased`: true if the objective value of the current solution is higher than that of the previous solution. - `converged`: true if the solution satisfies the convergence criteria of choice. See [`ConvergenceCriteria`](@ref) for more on the different convergence criteria available. """ @with_kw mutable struct ConvergenceState{T} Δx::T = Inf Δf::T = Inf relΔf::T = Inf kkt_residual::T = Inf ipopt_residual::T = Inf infeas::T = Inf x_converged::Bool = false fabs_converged::Bool = false frel_converged::Bool = false kkt_converged::Bool = false ipopt_converged::Bool = false infeas_converged::Bool = false f_increased::Bool = true converged::Bool = false end ConvergenceState(::Type{T}) where {T} = ConvergenceState{T}() """ Tolerance A struct specifying the different tolerances used to assess the convergence of the algorithms. The following are the fields of `Tolerance`: - `x`: the tolerance for `Δx` in [`ConvergenceState`](@ref). `x_converged` will be true if `Δx` is less than the `x` tolerance in `Tolerance`. This is used to assess convergence when the [`GenericCriteria`](@ref) is used as the convergence criteria. - `fabs`: the tolerance for `Δf` in [`ConvergenceState`](@ref). `f_converged` will be true if `Δf` is less than the `fabs` tolerance in `Tolerance`. This is used to assess convergence when the [`GenericCriteria`](@ref) is used as the convergence criteria. - `frel`: the tolerance for `relΔf` in [`ConvergenceState`](@ref). `f_converged` will be true if `relΔf` is less than the `frel` tolerance in `Tolerance`. This is used to assess convergence when the [`GenericCriteria`](@ref) is used as the convergence criteria. - `kkt`: the KKT tolerance. `kkt_converged` in [`ConvergenceState`](@ref) will be true if the `kkt_residual` is less than the KKT tolerance. And `ipopt_converged` in [`ConvergenceState`](@ref) will be true if `ipopt_residual` is less than the KKT tolerance. This is used to assess convergence when the [`KKTCriteria`](@ref), the [`ScaledKKTCriteria`](@ref) or [`IpoptCriteria`](@ref) criteria is used as the convergence criteria. - `infeas`: the maximum infeasibility tolerance. `infeas_converged` in [`ConvergenceState`](@ref) will be true if the maximum infeasibility is less than the infeasibility tolerance. This is used to assess convergence regardless of the convergence criteria used. For more on convergence criteria, see [`GenericCriteria`](@ref), [`KKTCriteria`](@ref), [`ScaledKKTCriteria`](@ref) and [`IpoptCriteria`](@ref). """ struct Tolerance{Tx,Tf,Tkkt,Tinfeas} x::Tx fabs::Tf frel::Tf kkt::Tkkt infeas::Tinfeas end function Tolerance(; x = 0.0, f = 1e-5, fabs = f, frel = f, kkt = 1e-5, infeas = 1e-5) Tolerance(x, fabs, frel, kkt, infeas) end function (tol::Tolerance{<:Function,<:Function,<:Function})(i) return Tolerance(tol.x(i), tol.fabs(i), tol.frel(i), tol.kkt(i), tol.infeas) end function Base.:*(t::Tolerance, m::Real) return Tolerance(t.x * m, t.fabs * m, t.frel * m, t.kkt * m, t.infeas * m) end """ ConvergenceCriteria This an abstract type with 4 subtypes: 1. [`GenericCriteria`](@ref) 2. [`KKTCriteria`](@ref) 3. [`ScaledKKTCriteria`](@ref) 4. [`IpoptCriteria`](@ref) """ abstract type ConvergenceCriteria end """ GenericCriteria This is a generic convergence criteria that uses: 1. The maximum change in the solution, `Δx`, 2. The change in the objective value, `Δf`, and 3. The change percentage in the objective value, `Δf`, and 4. The maximum infeasibility `infeas`. to assess convergence. More details are given in [`assess_convergence!`](@ref). """ struct GenericCriteria <: ConvergenceCriteria end """ KKTCriteria This convergence criteria uses the Karush-Kuhn-Tucker residual and maximum infeasibility to assess convergence. More details are given in [`assess_convergence!`](@ref). """ struct KKTCriteria <: ConvergenceCriteria end """ IpoptCriteria This convergence criteria uses a scaled version of the Karush-Kuhn-Tucker (KKT) residual and maximum infeasibility to assess convergence. This scaled KKT residual is used in the IPOPT nonlinear programming solver as explained in [this paper](http://cepac.cheme.cmu.edu/pasilectures/biegler/ipopt.pdf). More details are given in [`assess_convergence!`](@ref). """ struct IpoptCriteria <: ConvergenceCriteria end """ ScaledKKTCriteria This convergence criteria uses another scaled version of the Karush-Kuhn-Tucker (KKT) residual and maximum infeasibility to assess convergence. In particular if the objective was scaled by a factor `m`, the KKT residual will be scaled down by a factor `max(m, 1/m)`. This scaling was found to make the convergence criteria less sensitive to scale compared to using the traditional KKT residual. More details are given in [`assess_convergence!`](@ref). """ struct ScaledKKTCriteria <: ConvergenceCriteria end """ Solution A struct that stores all the information about a solution. The following are the fields of `Solution`: - `x`: the current primal solution - `prevx`: the previous primal solution - `λ`: the current dual solution - `f`: the objective value of `x` - `prevf`: the obejctive value of `prevx` - `∇f`: the gradient of the objective at `x` - `g`: the constraint function value at `x` - `∇g`: the Jacobian of the constraint functions at `x` - `convstate`: the convergence state of the solution """ mutable struct Solution{X1,X2,L,P,F,D1,G,D2,C<:ConvergenceState} prevx::X1 x::X2 λ::L prevf::P f::F ∇f::D1 g::G ∇g::D2 convstate::C end """ AbstractResult An abstract type that stores optimization result. """ abstract type AbstractResult end """ GenericResult A summary result struct returned by [`optimize`](@ref), including following fields: - `optimizer`: the optimization algorithm used - `initial_x`: the initial primal solution - `minimizer`: the best solution found - `minimum`: the optimal value - `iter`: number of inner iterations run - `maxiter_reached`: true if the algorithm stopped due to reaching the maximum number of iterations - `tol`: an instance of [`Tolerance`](@ref) that specifies the convergence tolerances - `convstate`: an instance of [`ConvergenceCriteria`](@ref) that summarizes the convergence state of the best solution found - `fcalls`: the number of times the objective and constraint functions were called during the optimization """ mutable struct GenericResult{ O, I, M1, M2<:Real, T<:Tolerance, C<:Union{ConvergenceState,Nothing}, } <: AbstractResult optimizer::O initial_x::I minimizer::M1 minimum::M2 iter::Int maxiter_reached::Bool tol::T convstate::C fcalls::Int end abstract type AbstractModel end """ ``` optimize( model::AbstractModel, optimizer::AbstractOptimizer = MMA02(), x0::AbstractVector; options, convcriteria::ConvergenceCriteria = KKTCriteria(), plot_trace::Bool = false, callback::Function = plot_trace ? LazyPlottingCallback() : NoCallback(), kwargs..., ) ``` Optimizes `model` using the algorithm `optimizer`, e.g. an instance of [`MMA87`](@ref) or [`MMA02`](@ref). `x0` is the initial solution. The keyword arguments are: - `options`: used to set the optimization options. It is an instance of [`MMAOptions`](@ref) for [`MMA87`](@ref) and [`MMA02`](@ref). - `convcriteria`: an instance of [`ConvergenceCriteria`](@ref) that specifies the convergence criteria of the MMA algorithm. - `plot_trace`: a Boolean that if true specifies the callback to be an instance of [`PlottingCallback`](@ref) and plots a live trace of the last 50 solutions. - `callback`: a function that is called on `solution` in every iteration of the algorithm. This can be used to store information about the optimization process. The details of the MMA optimization algorithms can be found in the original [1987 MMA paper](https://onlinelibrary.wiley.com/doi/abs/10.1002/nme.1620240207) and the [2002 paper](https://epubs.siam.org/doi/abs/10.1137/S1052623499362822). """ function optimize( model::AbstractModel, optimizer::AbstractOptimizer, x0, args...; kwargs..., ) _optimize_precheck(model, optimizer, x0, args...; kwargs...) _model, _x0, unflatten = tovecmodel(model, x0) r = optimize(_model, optimizer, _x0, args...; kwargs...) return @set r.minimizer = unflatten(r.minimizer) end function _optimize_precheck( model::AbstractModel, optimizer::AbstractOptimizer, args...; kwargs..., ) if (length(model.sd_constraints.fs) != 0) @warn "The solver used does not support semidefinite constraints so they will be ignored." end end function optimize!(::Workspace) throw("Method not implemented for this type.") end """ optimize without x0 """ function optimize(model::AbstractModel, optimizer::AbstractOptimizer, args...; kwargs...) _optimize_precheck(model, optimizer, args...; kwargs...) _model, _, unflatten = tovecmodel(model) r = optimize(_model, optimizer, args...; kwargs...) return @set r.minimizer = unflatten(r.minimizer) end """ Clamp the box constraint and evaluate objective function at point x """ function clamp_and_evaluate!(model::AbstractModel, x::AbstractVector) @unpack box_min, box_max = model x .= clamp.(x, box_min, box_max) model.objective(x) end
NonconvexCore
https://github.com/JuliaNonconvex/NonconvexCore.jl.git
[ "MIT" ]
1.4.3
3ba86f8b385508778d19f52031074ee4c48cedac
code
310
struct CountingFunction{F} <: AbstractFunction counter::Base.RefValue{Int} f::F end getdim(f::CountingFunction) = getdim(f.f) CountingFunction(f::Function) = CountingFunction(Ref(0), f) function (f::CountingFunction)(x) f.counter[] += 1 return f.f(x) end getfunction(f::CountingFunction) = f.f
NonconvexCore
https://github.com/JuliaNonconvex/NonconvexCore.jl.git
[ "MIT" ]
1.4.3
3ba86f8b385508778d19f52031074ee4c48cedac
code
7783
""" abstract type AbstractFunction <: Function end An abstract function type. """ abstract type AbstractFunction <: Function end """ length(f::AbstractFunction) Returns the number of outputs of `f`. """ Base.length(f::AbstractFunction) = getdim(f) """ ``` struct FunctionWrapper <: AbstractFunction f::Function dim::Int end ``` A function wrapper type that wraps the function `f` where the function `f` is declared to return an output of dimension `dim`. """ struct FunctionWrapper{F} <: AbstractFunction f::F dim::Int end """ (f::FunctionWrapper)(args...; kwargs...) Calls the wrapped function in `f` with arguments `args` and keyword arguments `kwargs` and returns the output. """ function (f::FunctionWrapper)(args...; kwargs...) out = f.f(args...; kwargs...) @assert length(out) == getdim(f) return out end """ getdim(f::AbstractFunction) Returns the dimension of the function `f`, i.e. the number of outputs. """ getdim """ getfunction(f::AbstractFunction) Returns any wrapped function inside the function `f`. """ getfunction """ getfunction(f::FunctionWrapper) Returns the function wrapped in `f`. """ getfunction(f::FunctionWrapper) = f.f getdim(f::FunctionWrapper) = f.dim """ ``` struct VectorOfFunctions <: AbstractFunction fs end ``` A struct for a collection of instances of `AbstractFunction`. The dimension of this function is the sum of the dimensions of the individual functions and the outputs are concatenated in a vector. """ struct VectorOfFunctions{ F<:Union{AbstractVector{<:AbstractFunction},Tuple{Vararg{AbstractFunction}}}, } <: AbstractFunction fs::F end """ VectorOfFunctions(fs) Constructs an instance of `VectorOfFunctions` made of functions `fs`. `fs` can be a vector or tuple of instances of `AbstractFunction`. If a function in `fs` is a `VectorOfFunctions`, it will be unwrapped. """ function VectorOfFunctions( fs::Union{AbstractVector{>:VectorOfFunctions},Tuple{Vararg{>:VectorOfFunctions}}}, ) @assert length(fs) > 0 new_fs = mapreduce(vcat, fs) do f if f isa VectorOfFunctions f.fs else f end end return VectorOfFunctions(new_fs) end """ (f::VectorOfFunctions)(args...; kwargs...) Calls the wrapped functions in `f` with arguments `args` and keyword arguments `kwargs` and returns the concatenated output. """ function (f::VectorOfFunctions)(args...; kwargs...) length(f.fs) == 0 && return Union{}[] ys = map(f.fs) do f return f(args...; kwargs...) end return vcat(ys...) end function getdim(c::VectorOfFunctions) length(c.fs) == 0 && return 0 return sum(getdim, c.fs) end """ getfunction(f::VectorOfFunctions, i::Integer) Returns the `i`^th wrapped function in `f`. """ getfunction(f::VectorOfFunctions, i::Integer) = getfunctions(f)[i] """ getfunctions(f::VectorOfFunctions) Returns the vector or tuple of functions wrapped in `f`. """ getfunctions(f::VectorOfFunctions) = f.fs """ abstract type AbstractConstraint <: AbstractFunction end An abstract constraint type. """ abstract type AbstractConstraint <: AbstractFunction end """ ``` struct Objective <: AbstractFunction f multiple flags::Set{Symbol} end ``` The objective function to be optimized. The objective is always assumed to be of dimension 1. `multiple` is of type `Ref{<:Number}`. When an instance of `Objective` is called, its output will be scaled by a multiplier `multiple[]`. This is 1 by default. """ struct Objective{F,M<:Base.RefValue} <: AbstractFunction f::F multiple::M flags::Set{Symbol} end """ Objective(f, multiple::Number = 1.0) Constructs an instance of `Objective` wrapping `f`. When an instance of `Objective`, it calls `f` returning the output multiplied by `multiple`. `f` must return a number. """ function Objective(f, multiple::Number = 1.0; flags = Set{Symbol}()) return Objective(f, Ref(multiple), Set(flags)) end """ (obj::Objective)(args...; kwargs...) Calls the wrapped function in `obj` with arguments `args` and keyword arguments `kwargs` returning the output multiplied by `obj.multiple[]`. The output of the wrapped function must be a number. """ function (o::Objective)(args...; kwargs...) out = o.f(args...; kwargs...) * o.multiple[] @assert out isa Number return out end getdim(c::Objective) = 1 """ getfunction(obj::Objective) Returns the function wrapped in `obj`. """ getfunction(obj::Objective) = obj.f """ ``` struct IneqConstraint <: AbstractConstraint f::Function rhs dim::Int flags::Set{Symbol} end ``` A struct for an inequality constraint of the form `f(x) .- rhs .<= 0`. The dimension of the constraint is `dim`. Calling the struct will return `f(x) .- rhs`. """ struct IneqConstraint{F,R} <: AbstractConstraint f::F rhs::R dim::Int flags::Set{Symbol} end """ IneqConstraint(f, rhs) Constructs an instance of `IneqConstraint` with a left-hand-side function `f` and right-hand-side bound `rhs`. If `f` is an instance of `AbstractFunction`, the dimension of the constraint will be `getdim(f)`, otherwise it is assumed to be `length(rhs)` by default. """ function IneqConstraint(f, rhs; flags = Set{Symbol}()) return IneqConstraint(f, rhs, length(rhs), Set(flags)) end function IneqConstraint(f::AbstractFunction, rhs; flags = Set{Symbol}()) return IneqConstraint(f, rhs, getdim(f), Set(flags)) end """ (c::IneqConstraint)(args...; kwargs...) Calls the wrapped function in the constraint `c`, `c.f`, with arguments `args` and keyword arguments `kwargs` returning the constraint violation `c.f(args...; kwargs...) .- c.rhs`. """ function (c::IneqConstraint)(args...; kwargs...) out = c.f(args...; kwargs...) .- c.rhs @assert length(out) == getdim(c) return out end getdim(c::IneqConstraint) = c.dim """ getfunction(f::IneqConstraint) Returns the function wrapped in `f`. """ getfunction(f::IneqConstraint) = f.f """ ``` struct EqConstraint <: AbstractConstraint f::Function rhs dim::Int flags::Set{Symbol} end ``` A struct for an equality constraint of the form `f(x) .- rhs .== 0`. The dimension of the constraint is `dim`. Calling the struct will return `f(x) .- rhs`. """ struct EqConstraint{F,R} <: AbstractConstraint f::F rhs::R dim::Int flags::Set{Symbol} end """ EqConstraint(f, rhs) Constructs an instance of `EqConstraint` with a left-hand-side function `f` and right-hand-side bound `rhs`. If `f` is an instance of `AbstractFunction`, the dimension of the constraint will be `getdim(f)`, otherwise it is assumed to be `length(rhs)` by default. """ function EqConstraint(f, rhs; flags = Set{Symbol}()) return EqConstraint(f, rhs, length(rhs), Set(flags)) end function EqConstraint(f::AbstractFunction, rhs; flags = Set{Symbol}()) return EqConstraint(f, rhs, getdim(f), Set(flags)) end """ (c::EqConstraint)(args...; kwargs...) Calls the wrapped function in the constraint `c`, `c.f`, with arguments `args` and keyword arguments `kwargs` returning the constraint violation `c.f(args...; kwargs...) .- c.rhs`. """ function (c::EqConstraint)(args...; kwargs...) out = c.f(args...; kwargs...) .- c.rhs @assert length(out) == getdim(c) return out end getdim(c::EqConstraint) = c.dim """ getfunction(f::EqConstraint) Returns the function wrapped in `f`. """ getfunction(f::EqConstraint) = f.f """ Used in semidefinite programming """ struct SDConstraint{F} <: AbstractConstraint f::F dim::Int end function (c::SDConstraint)(args...; kwargs...) out = c.f(args...; kwargs...) @assert length(out) == getdim(c)^2 return out end getdim(c::SDConstraint) = c.dim getfunction(c::SDConstraint) = c.f
NonconvexCore
https://github.com/JuliaNonconvex/NonconvexCore.jl.git
[ "MIT" ]
1.4.3
3ba86f8b385508778d19f52031074ee4c48cedac
code
2296
# workaround Zygote.jacobian and ForwardDiff.jacobian not supporting sparse jacobians function sparse_gradient(f, x) _, pb = Zygote.pullback(f, x) return _sparsevec(pb(1.0)[1]) end function sparse_jacobian(f, x) val, pb = Zygote.pullback(f, x) M = length(val) vecs = [sparsevec([i], [true], M) for i = 1:M] Jt = reduce(hcat, first.(pb.(vecs))) return copy(Jt') end function sparse_fd_jacobian(f, x) pf = pushforward_function(f, x) M = length(x) vecs = [sparsevec([i], [true], M) for i = 1:M] # assumes there will be no structural non-zeros that have value 0 return reduce(hcat, sparse.(pf.(vecs))) end function pushforward_function(f, x) return v -> begin return ForwardDiff.derivative(h -> f(x + h * v), 0) end end function sparse_hessian(f, x) return sparse_fd_jacobian(x -> sparse_gradient(f, x), x) end _sparsevec(x::Real) = [x] _sparsevec(x::Vector) = copy(x) _sparsevec(x::Matrix) = copy(vec(x)) _sparsevec(x::SparseVector) = x function _sparsevec(x::Adjoint{<:Real,<:AbstractMatrix}) return _sparsevec(copy(x)) end function _sparsevec(x::SparseMatrixCSC) m, n = size(x) linear_inds = zeros(Int, length(x.nzval)) count = 1 for colind = 1:length(x.colptr)-1 for ind = x.colptr[colind]:x.colptr[colind+1]-1 rowind = x.rowval[ind] val = x.nzval[ind] linear_inds[count] = rowind + (colind - 1) * m count += 1 end end return sparsevec(linear_inds, copy(x.nzval), prod(size(x))) end _sparse_reshape(v::AbstractVector, _) = v _sparse_reshape(v::Vector, m, n) = reshape(v, m, n) function _sparse_reshape(v::SparseVector, m, n) if length(v.nzval) == 0 return sparse(Int[], Int[], v.nzval, m, n) end N = length(v.nzval) I = zeros(Int, N) J = zeros(Int, N) for (i, ind) in enumerate(v.nzind) _col, _row = divrem(ind, m) if _row == 0 col = _col row = m else col = _col + 1 row = _row end I[i] = row J[i] = col end return sparse(I, J, copy(v.nzval), m, n) end function ChainRulesCore.rrule(::typeof(_sparsevec), x) val = _sparsevec(x) val, Δ -> (NoTangent(), _sparse_reshape(Δ, size(x)...)) end
NonconvexCore
https://github.com/JuliaNonconvex/NonconvexCore.jl.git
[ "MIT" ]
1.4.3
3ba86f8b385508778d19f52031074ee4c48cedac
code
1939
# Simultaneous function and Jacobian evaluation """ value_jacobian(f::Function, x::AbstractVector) Returns the value and Jacobian of the function `f` at the point `x`. The automatic differentiation package, Zygote, is used by default. To define a custom adjoint rule for a function to be used in a constraint or objective, use [`ChainRulesCore.jl`](https://github.com/JuliaDiff/ChainRulesCore.jl). The Jacobian is returned as an instance of `Adjoint` for cache efficiency in the optimizer. """ function value_jacobian(f::Function, x::AbstractVector) out, pullback = Zygote.pullback(f, x) if out isa Number grad = pullback(1.0)[1] return out, grad' else dim = getdim(f) jact = mapreduce(hcat, 1:dim; init = zeros(length(x), 0)) do i pullback(I(dim)[:, i])[1] end return out, jact' end end function value_jacobian(c::VectorOfFunctions, x::AbstractVector) vals_jacs = map(c.fs) do f value_jacobian(f, x) end vals = mapreduce(vcat, vals_jacs; init = zeros(0)) do val_jac val_jac[1] end jact = mapreduce(hcat, vals_jacs; init = zeros(length(x), 0)) do val_jac val_jac[2]' end return vals, jact' end """ value_jacobian_transpose(f::Function, x::AbstractVector) Returns the value and transpose of the Jacobian of `f` at the point `x`. This calls [`value_jacobian`](@ref) and transposes the Jacobian. """ function value_jacobian_transpose(f::Function, x::AbstractVector) val, jac = value_jacobian(f, x) return val, jac' end """ value_gradient(f::Function, x::AbstractVector) Returns the value and gradient of the scalar-valued function `f` at the point `x`. This is a convenience function for scalar-valued functions that simply calls [`value_jacobian_transpose`](@ref) on `f` and `x`. """ function value_gradient(f::Function, x::AbstractVector) return value_jacobian_transpose(f, x) end
NonconvexCore
https://github.com/JuliaNonconvex/NonconvexCore.jl.git
[ "MIT" ]
1.4.3
3ba86f8b385508778d19f52031074ee4c48cedac
code
848
mutable struct DictModel <: AbstractModel objective::Union{Nothing,Objective} eq_constraints::VectorOfFunctions ineq_constraints::VectorOfFunctions sd_constraints::VectorOfFunctions box_min::OrderedDict box_max::OrderedDict init::OrderedDict integer::OrderedDict end function DictModel(f = nothing) return DictModel( Objective(f), VectorOfFunctions(EqConstraint[]), VectorOfFunctions(IneqConstraint[]), VectorOfFunctions(SDConstraint[]), OrderedDict(), OrderedDict(), OrderedDict(), OrderedDict(), ) end function addvar!( m::DictModel, k::Union{Symbol,String}, lb, ub; init = deepcopy(lb), integer = false, ) getmin(m)[k] = lb getmax(m)[k] = ub m.init[k] = init m.integer[k] = integer return m end
NonconvexCore
https://github.com/JuliaNonconvex/NonconvexCore.jl.git