text:
@everywhere include("self-phase.jl")
using YAML
using Iterators
#=
"""
To run, simply use:
```
julia multi-thread.jl <parameter file> <#saves>
```
e.g:
```
julia multi-thread.jl params.yaml 10
```
"""
"""
    unpack(p, numSaves)
given a dictionary of inital paremeters, and a number of times to save, performs
the entire simulation with those parameters.
"""
=#
@everywhere function unpack(p, numSaves)
    # Generate folder string
    fname = @sprintf("%.0fnm_%.0fμJ_%.2fbar_%.2fbar_%.0ffs_%.1fm_%.0ffs^2_%.0fμm",
                     p["λ"]*1E9, p["Energy"]*1E6, p["Pin"], p["Pout"], p["Tfwhm"]*1E15,
                     p["zmax"], p["Chirp"], p["fiberD"]*1E6)
    # Derive additional constants and spatial grids
    derive_constants(p)
    # Initialize electric field
    E, zinit = initialize(fname, p, "resume" in ARGS, "keep" in ARGS)
    # Save inital data
    saveData(fname, E, 0, zinit)
    # Simulate the whole thing
    simulate(E, p, zinit, fname, numSaves)
end

# Load paramters which are possible list
lists = YAML.load(open(ARGS[1]))
# Rename lambda to λ in dictionary.
if haskey(lists, "lambda")
    merge!(lists, Dict("λ" => pop!(lists, "lambda")))
end

# If paramter is a list of form [initial, final, stepsize] convert to list
# of all paramters in range. Otherwise keep it as a single value.
for key in keys(lists)
    if length(lists[key]) != 1
        lists[key] = collect(lists[key][1]:lists[key][3]:lists[key][2])
    else
        lists[key] = lists[key][1]
    end
end

# Generate all possible combinations of parameters.
param_tuples = collect(product(values(lists)...))

# Put all results into a single folder named data.
if "data" ∉ readdir()
    mkdir("data")
end
# Put all processes in same place.
@everywhere cd("data")

if length(ARGS) < 2
    println("No number of saves passed, assuming 2.")
    numSaves = 2
else
    numSaves = parse(Int, ARGS[2])
end

# Parallel map over all paramters to simulate!
pmap(jawn -> unpack(Dict{Any,Any}(zip(keys(lists), jawn)), numSaves), param_tuples)

max_stars_repo_name: ry-dgel/self-phase

max_issues_repo_name: ry-dgel/self-phase

max_forks_repo_name: ry-dgel/self-phase


text:
# This file was generated, do not modify it. # hide
describe(data)

# The describe() function shows that there are several features with missing values.

ext: jl


text:
struct NewPackage end
struct NewVersion end


text:
@testset "faithful opdiff" begin
    include("faithful_opdiff.jl")
end

@testset "stats diff" begin
    include("stats.jl")
end


text:
using WormlikeChain
using Test
using HypothesisTests
using Distributions
using Suppressor
using LinearAlgebra

"""
Roughly tests if the 1d array x is normally distributed iid.
    Not super rigorous, but hopefully catches some issues
"""
function testifnormal(x)
    sets= [x[:],
            x[1:2:end],
            x[2:2:end],
            √0.5(x[1:2:end] .+ x[2:2:end]),
            x[1:4:end],
            x[2:4:end],
            x[3:4:end],
            x[4:4:end],
            √0.25(x[1:4:end] .+ x[2:4:end] .+ x[3:4:end] .+ x[4:4:end]) ]
    for a in sets
        t= 0.0
        @suppress_err begin
            t=ApproximateOneSampleKSTest(a,Normal())
        end
        @test pvalue(t) > 0.005
    end
end

include("test_interface.jl")

include("test_cpukernels.jl")

@testset "bonded_forces_utils.jl" begin
    @test 1 == WormlikeChain.next_beadid(1,(1,2))
    @test 2 == WormlikeChain.next_beadid(1,(1,10))
    @test 4 == WormlikeChain.next_beadid(3,(1,10))
    @test 1 == WormlikeChain.next_beadid(9,(1,10))
    @test 1 == WormlikeChain.next_beadid(9,(1,10,15))
    @test 11 == WormlikeChain.next_beadid(10,(1,10,15))
    @test 10 == WormlikeChain.next_beadid(14,(1,10,15))

    @test 1 == WormlikeChain.prev_beadid(1,(1,2))
    @test 9 == WormlikeChain.prev_beadid(1,(1,10))
    @test 2 == WormlikeChain.prev_beadid(3,(1,10))
    @test 8 == WormlikeChain.prev_beadid(9,(1,10))
    @test 9 == WormlikeChain.prev_beadid(1,(1,10,15))
    @test 14 == WormlikeChain.prev_beadid(10,(1,10,15))
    @test 13 == WormlikeChain.prev_beadid(14,(1,10,15))

end

@testset "random_utils.jl" begin
    N= 1_000_000
    x= zeros(2*N)
    key= UInt64(123215)
    ctr1= UInt64(1)
    ctr2= UInt64(0)
    #generate a bunch of normal random numbers
    for i in 1:N
        x[2i], x[2i - 1] = WormlikeChain.randn_2x64(key, ctr1, ctr2+i)
    end
    testifnormal(x)
    for i in 1:N
        x[2i], x[2i - 1] = WormlikeChain.randn_2x64(key, ctr1+i, ctr2)
    end
    testifnormal(x)

    x= zeros(Float32,4*N)
    for i in 1:N
        x[4i-3:4i] .= WormlikeChain.randn_4x32(key, ctr1, ctr2+i)
    end
    testifnormal(x)
    for i in 1:N
        x[4i-3:4i] .= WormlikeChain.randn_4x32(key, ctr1+i, ctr2)
    end
    testifnormal(x)

    x= zeros(Float32,6*N)
    for i in 1:N
        #make sure to inc ctr2 by at least 2 because each 4 normal samples uses up 1 ctr2
        x[6i-5:6i] .= WormlikeChain.randn_32(key, ctr1, ctr2+i*2,Val(6))
    end
    testifnormal(x)
    for i in 1:N
        x[6i-5:6i] .= WormlikeChain.randn_32(key, ctr1+i, ctr2,Val(6))
    end
    testifnormal(x)

end


text:
const SXType = UInt8 # stores the type of SEXPREC

##############################################################################
##
## A table of R's SEXPREC tags from RInternals.h
##
##############################################################################

const NILSXP =      0x00 # nil = NULL
const SYMSXP =      0x01 # symbols
const LISTSXP =     0x02 # lists of dotted pairs
const CLOSXP =      0x03 # closures
const ENVSXP =      0x04 # environments
const PROMSXP =     0x05 # promises: [un]evaluated closure arguments
const LANGSXP =     0x06 # language constructs (special lists)
const SPECIALSXP =  0x07 # special forms
const BUILTINSXP =  0x08 # builtin non-special forms
const CHARSXP =     0x09 # "scalar" string type (internal only)
const LGLSXP =      0x0A # logical vectors
# 11 and 12 were factors and ordered factors in the 1990s
const INTSXP =      0x0D # integer vectors
const REALSXP =     0x0E # real variables
const CPLXSXP =     0x0F # complex variables
const STRSXP =      0x10 # string vectors
const DOTSXP =      0x11 # dot-dot-dot object
const ANYSXP =      0x12 # make "any" args work. Used in specifying types for symbol registration to mean anything is okay
const VECSXP =      0x13 # generic vectors
const EXPRSXP =     0x14 # expressions vectors
const BCODESXP =    0x15 # byte code
const EXTPTRSXP =   0x16 # external pointer
const WEAKREFSXP =  0x17 # weak reference
const RAWSXP =      0x18 # raw bytes
const S4SXP =       0x19 # S4, non-vector

# used for detecting PROTECT issues in memory.c
const NEWSXP =      0x1E # fresh node creaed in new page
const FREESXP =     0x1F # node released by GC

const FUNSXP =      0x63 # Closure or Builtin or Special

#=
 = Administrative SXP values (from serialize.c)
 =#
const REFSXP =            0xFF
const NILVALUE_SXP =      0xFE
const GLOBALENV_SXP =     0xFD
const UNBOUNDVALUE_SXP =  0xFC
const MISSINGARG_SXP =    0xFB
const BASENAMESPACE_SXP = 0xFA
const NAMESPACESXP =      0xF9
const PACKAGESXP =        0xF8
const PERSISTSXP =        0xF7
const CLASSREFSXP =       0xF6
const GENERICREFSXP =     0xF5
const BCREPDEF =          0xF4
const BCREPREF =          0xF3
const EMPTYENV_SXP =      0xF2
const BASEENV_SXP =       0xF1
const ATTRLANGSXP =       0xF0
const ATTRLISTSXP =       0xEF
const ALTREP_SXP =        0xEE

##############################################################################
##
## R objects in the file are preceded by a UInt32 giving the type and
## some flags.  These functions unpack bits in the flags.  The isobj
## bit might be useful for distinguishing an RInteger from a factor or
## an RList from a data.frame.
##
##############################################################################

const RDATag = UInt32

isobj(fl::RDATag) = (fl & 0x00000100) != 0
hasattr(fl::RDATag) = (fl & 0x00000200) != 0
hastag(fl::RDATag) = (fl & 0x00000400) != 0
sxtype(fl::RDATag) = fl % UInt8

##############################################################################
##
## Julia types encapsulating various types of R SEXPRECs
##
##############################################################################

"""
Base class for RData internal representation of all R types.
`SEXPREC` stands for S (R predecessor) expression record.
"""
abstract type RSEXPREC{S} end

sxtype(sxt::Type{T}) where T <: RSEXPREC{S} where S = S
sxtype(sxt::RSEXPREC) = sxtype(typeof(sxt))

"""
R symbol.
Not quite the same as a Julia symbol.
"""
struct RSymbol <: RSEXPREC{SYMSXP}
    displayname::RString
end

Base.string(symbol::RSymbol) = symbol.displayname

"""
Base class for all R types (objects) that can have attributes.
"""
abstract type ROBJ{S} <: RSEXPREC{S} end

"""
Base class for all R vector-like objects.
"""
abstract type RVEC{T, S} <: ROBJ{S} end

rvec_eltype(::Type{<:RVEC{T}}) where T = T
rvec_eltype(v::RVEC) = rvec_eltype(typeof(v))

"""
R vector object.
"""
struct RVector{T, S} <: RVEC{T, S}
    data::Vector{T}
    attr::Hash                   # collection of R object attributes

    RVector{T,S}(v::Vector{T}=T[], attr::Hash=Hash()) where {T,S} =
        new{T,S}(v, attr)
end

# add unique attribute storage to ROBJ if one doesn't have it
addattr(v::RVector{T, S}) where {T,S} =
    v.attr === emptyhash ? RVector{T, S}(v.data, Hash()) : v

const RLogicalVector = RVector{Int32, LGLSXP}
const RIntegerVector = RVector{Int32, INTSXP}
const RNumericVector = RVector{Float64, REALSXP}
const RComplexVector = RVector{ComplexF64, CPLXSXP}

"""
R vector object with explicit NA values.
"""
struct RNullableVector{T, S} <: RVEC{T, S}
    data::Vector{T}
    na::BitVector                # mask of NA elements
    attr::Hash                   # collection of R object attributes
end

const RStringVector = RNullableVector{RString,STRSXP}
const RList = RVector{RSEXPREC,VECSXP}  # "list" in R == Julia cell array

"""
Representation of R's paired list-like structures (`LISTSXP`, `LANGSXP`).
Unlike R which represents these as singly-linked list,
`RPairList` uses vector representation.
"""
struct RPairList <: ROBJ{LISTSXP}
    items::Vector{RSEXPREC}
    tags::Vector{RString}
    attr::Hash

    RPairList(attr::Hash = Hash()) = new(RSEXPREC[], RString[], attr)
end

Base.length(list::RPairList) = length(list.items)

function Base.push!(pl::RPairList, item::RSEXPREC, tag::RString)
    push!(pl.tags, tag)
    push!(pl.items, item)
end

mutable struct RClosure <: ROBJ{CLOSXP}
    formals
    body
    env
    attr::Hash

    RClosure(attr::Hash = Hash()) = new(nothing, nothing, nothing, attr)
end

struct RBuiltin <: RSEXPREC{BUILTINSXP}
    internal_function::RString
end

mutable struct RPromise <: ROBJ{PROMSXP}
    value
    expr
    env
    attr::Hash

    RPromise(attr::Hash = Hash()) = new(nothing, nothing, nothing, attr)
end

mutable struct REnvironment <: ROBJ{ENVSXP}
    enclosed
    frame
    hashtab
    attr::Hash

    REnvironment() = new(nothing, nothing, nothing, Hash())
end

struct RRaw <: ROBJ{RAWSXP}
    data::Vector{UInt8}
    attr::Hash
end

struct RS4Obj <: ROBJ{S4SXP}
    attr::Hash
end

mutable struct RExtPtr <: ROBJ{EXTPTRSXP}
    protected
    tag
    attr::Hash

    RExtPtr() = new(nothing, nothing, Hash())
end

mutable struct RBytecode <: ROBJ{BCODESXP}
    attr::Hash
    tag
    car
    cdr
    RBytecode(code = nothing, consts = nothing, attr::Hash = Hash()) =
        new(attr, nothing, code, consts)
end

struct RPackage <: RSEXPREC{PACKAGESXP}
    name::Vector{RString}
end

struct RNamespace <: RSEXPREC{NAMESPACESXP}
    name::Vector{RString}
end

struct RAltRep <: ROBJ{ALTREP_SXP}
    info
    state
    attr::Hash
end

# R objects without body (empty environments, missing args etc)
struct RDummy{S} <: RSEXPREC{S}
end

##############################################################################
##
## Utilities for working with basic properties of R objects:
##    attributes, class inheritance, etc
##
##############################################################################

const emptystrvec = RString[]

hasattr(ro::ROBJ, attrnm) = haskey(ro.attr, attrnm)
hasnames(ro::ROBJ) = hasattr(ro, "names")
hasdim(ro::ROBJ) = hasattr(ro, "dim")
hasdimnames(ro::ROBJ) = hasattr(ro, "dimnames")

getdata(ro::RSEXPREC) =
    throw(UnsupportedROBJ(sxtype(ro), "Don't know how to get data from $(typeof(ro))"))
getdata(ro::Union{RVector, RNullableVector, RRaw}) = ro.data

getattr(ro::ROBJ, attrnm) = getdata(getindex(ro.attr, attrnm))
getattr(ro::ROBJ, attrnm, default) = hasattr(ro, attrnm) ? getdata(getindex(ro.attr, attrnm)) : default

Base.names(ro::ROBJ) = getattr(ro, "names")

# class of an R object
class(x::RSEXPREC) = emptystrvec # not an object
class(ro::ROBJ) = getattr(ro, "class", emptystrvec)::Vector{RString}

# check if R object inherits from a given class
inherits(x::RSEXPREC, classname) = false
inherits(ro::ROBJ, classname::AbstractString) = any(isequal(classname), class(ro))
# check if R object inherits from all given classes
inherits(ro::ROBJ, classnames::AbstractVector{<:AbstractString}) =
    all(classname -> any(isequal(classname), class(ro)), classnames)

isdataframe(rl::RList) = inherits(rl, "data.frame")
isfactor(ri::RIntegerVector) = inherits(ri, "factor")

Base.length(rl::RVEC) = length(rl.data)
Base.size(rv::RVEC) = length(rv.data)
Base.size(rl::RList) = isdataframe(rl) ? (length(rl.data[1]), length(rl.data)) : length(rl.data)

row_names(ro::ROBJ) = getattr(ro, "row.names", emptystrvec)

altrep_typename(ar::RAltRep) =
    isa(ar.info, RPairList) && length(ar.info) >= 1 && isa(ar.info.items[1], RSymbol) ?
    string(ar.info.items[1]) : nothing

function unsupported_altrep_message(ar::RAltRep)
    artype = altrep_typename(ar)
    if artype !== nothing
        return "Unsupported AltRep SEXP variant ($artype)"
    else
        return "Unsupported AltRep SEXP variant (info type $(typeof(ar.info)))"
    end
end

function iswrapped(ar::RAltRep)
    artype = altrep_typename(ar)
    return artype !== nothing && startswith(artype, "wrap_")
end

function iscompactseq(ar::RAltRep)
    artype = altrep_typename(ar)
    return artype !== nothing && occursin(r"^compact_.+seq$", artype)
end

# unwrap data contained in RAltRep
function unwrap(ar::RAltRep)
    # the first element of the AltRep state should be the wrapped one
    if !isa(ar.state, RPairList) || length(ar.state) == 0
        error("Unexpected state of \"$(arinfo)\" AltRep SEXP")
    end

    data = ar.state.items[1] # the actual data
    # recover object attributes from the AltRep head
    for (attrname, attr) in ar.attr
        if !haskey(data.attr, attrname)
            if data.attr === emptyhash
                # make sure data has its own dedicated attribute storage
                data = addattr(data)
            end
            data.attr[attrname] = attr
        end
    end
    return data
end

# convert R compact sequence to Julia range
function jlrange(ar::RAltRep)
    artype = altrep_typename(ar)
    if string(artype) == "compact_intseq"
        T = Int
    elseif string(artype) == "compact_realseq"
        T = Float64
    else
        error("Unsupported AltRep SEXP variant ($artype)")
    end
    if !(ar.state isa RVEC && rvec_eltype(ar.state) <: Number && length(ar.state) == 3)
        error("$artype: expected 3-element number vector")
    end
    seqdef = getdata(ar.state)
    return range(T(seqdef[2]), length=Int(seqdef[1]), step=seqdef[3] != 1 ? T(seqdef[3]) : nothing)
end

# accessing AltRep data is special
function getdata(ar::RAltRep)
    if iswrapped(ar)
        return getdata(unwrap(ar))
    elseif iscompactseq(ar)
        return jlrange(ar)
    else
        @warn unsupported_altrep_message(ar)
        return nothing
    end
end


text:
using CausticsEngineering
using Test

@testset "CausticsEngineering.jl" begin
    # Write your tests here.
end

max_stars_repo_name: Mehul-Bagaria/causticsEngineering

max_issues_repo_name: Mehul-Bagaria/causticsEngineering

max_forks_repo_name: Mehul-Bagaria/causticsEngineering


text:
# This file was generated by the Julia Swagger Code Generator
# Do not modify this file directly. Modify the swagger specification instead.

mutable struct IoK8sApiNetworkingV1NetworkPolicyPeer <: SwaggerModel
    ipBlock::Any # spec type: Union{ Nothing, IoK8sApiNetworkingV1IPBlock } # spec name: ipBlock
    namespaceSelector::Any # spec type: Union{ Nothing, IoK8sApimachineryPkgApisMetaV1LabelSelector } # spec name: namespaceSelector
    podSelector::Any # spec type: Union{ Nothing, IoK8sApimachineryPkgApisMetaV1LabelSelector } # spec name: podSelector

    function IoK8sApiNetworkingV1NetworkPolicyPeer(;ipBlock=nothing, namespaceSelector=nothing, podSelector=nothing)
        o = new()
        validate_property(IoK8sApiNetworkingV1NetworkPolicyPeer, Symbol("ipBlock"), ipBlock)
        setfield!(o, Symbol("ipBlock"), ipBlock)
        validate_property(IoK8sApiNetworkingV1NetworkPolicyPeer, Symbol("namespaceSelector"), namespaceSelector)
        setfield!(o, Symbol("namespaceSelector"), namespaceSelector)
        validate_property(IoK8sApiNetworkingV1NetworkPolicyPeer, Symbol("podSelector"), podSelector)
        setfield!(o, Symbol("podSelector"), podSelector)
        o
    end
end # type IoK8sApiNetworkingV1NetworkPolicyPeer

const _property_map_IoK8sApiNetworkingV1NetworkPolicyPeer = Dict{Symbol,Symbol}(Symbol("ipBlock")=>Symbol("ipBlock"), Symbol("namespaceSelector")=>Symbol("namespaceSelector"), Symbol("podSelector")=>Symbol("podSelector"))
const _property_types_IoK8sApiNetworkingV1NetworkPolicyPeer = Dict{Symbol,String}(Symbol("ipBlock")=>"IoK8sApiNetworkingV1IPBlock", Symbol("namespaceSelector")=>"IoK8sApimachineryPkgApisMetaV1LabelSelector", Symbol("podSelector")=>"IoK8sApimachineryPkgApisMetaV1LabelSelector")
Base.propertynames(::Type{ IoK8sApiNetworkingV1NetworkPolicyPeer }) = collect(keys(_property_map_IoK8sApiNetworkingV1NetworkPolicyPeer))
Swagger.property_type(::Type{ IoK8sApiNetworkingV1NetworkPolicyPeer }, name::Symbol) = Union{Nothing,eval(Meta.parse(_property_types_IoK8sApiNetworkingV1NetworkPolicyPeer[name]))}
Swagger.field_name(::Type{ IoK8sApiNetworkingV1NetworkPolicyPeer }, property_name::Symbol) =  _property_map_IoK8sApiNetworkingV1NetworkPolicyPeer[property_name]

function check_required(o::IoK8sApiNetworkingV1NetworkPolicyPeer)
    true
end

function validate_property(::Type{ IoK8sApiNetworkingV1NetworkPolicyPeer }, name::Symbol, val)
end


text:
a = [1, 2, 3, 4, 1, 2, 3, 4]
@show unique(a) Set(a)

max_stars_repo_name: ethansaxenian/RosettaDecode

max_issues_repo_name: ethansaxenian/RosettaDecode

max_forks_repo_name: ethansaxenian/RosettaDecode


text:
################################################################################
#
#	ABSTRACT TYPE
#
#   BondHoppingHamiltonianDict <: AbstractBondHamiltonian{L,1}
#   --> L is the label type of bonds
#   --> N is the dimension the bond term matrix (NxN matrix)
#
#   FILE CONTAINS
#       - abstract type definition
#       - interface definition
#       - generator function
#
################################################################################

################################################################################
#
#   ABSTRACT TYPE DEFINITION
#
################################################################################
mutable struct BondHoppingHamiltonianDict{L} <: AbstractBondHamiltonian{L,1}

    # coupling
    couplings :: Dict{L,Float64}

end

# export the type
export BondHoppingHamiltonianDict

################################################################################
#
#	INTERFACING / ACCESSING BOND HAMILTONIANS
#	(functions have to be overwritten by concrete types)
#
################################################################################

# get bond term of Hamiltonian
function bondterm(
            h :: BondHoppingHamiltonianDict{L},
            b :: AbstractBond{L,NB}
        ) :: Float64 where {N,L,NB,NS}

    # return the matching coupling and 0.0 if not found
    return get(h.couplings, label(b), 0.0)
end

# export the function
export bondterm

# set a couplint within the dictonary of couplings and add it if not present yet
function setCoupling(
            h :: BondHoppingHamiltonianDict{L},
            coupling :: L,
            coupling_strength :: Real
        ) where {L}

    # add the coupling to the dictonary
    h.couplings[coupling] = coupling_strength
end
function setCoupling(
            h :: BondHoppingHamiltonianDict{L},
            bond :: B,
            coupling_strength :: Real
        ) where {L,NB,B<:AbstractBond{L,NB}}

    # add the coupling to the dictonary
    h.couplings[label(bond)] = coupling_strength
end

# export the function
export setCoupling

function getHoppingHamiltonianDict(
            unitcell :: U
        ) :: BondHoppingHamiltonianDict{L} where {L,NB,S,B<:AbstractBond{L,NB},U<:AbstractUnitcell{S,B}}

    # just create a new hamiltonian
    return BondHoppingHamiltonianDict{L}(Dict{L,Float64}())
end
function getHoppingHamiltonianDict(
            unitcell  :: U,
            couplings :: Dict{L,<:Real}
        ) :: BondHoppingHamiltonianDict{L} where {L,NB,S,B<:AbstractBond{L,NB},U<:AbstractUnitcell{S,B}}

    # just create a new hamiltonian
    hb = BondHoppingHamiltonianDict{L}(Dict{L,Float64}())
    # set all copulings
    for c in keys(couplings)
        setCoupling(hb, c, couplings[c])
    end
    # return the bond hamiltonian
    return hb
end

export getHoppingHamiltonianDict

function getBondHamiltonianType(
        ::Val{:BondHoppingHamiltonianDict}
    )

    # return the type
    return BondHoppingHamiltonianDict
end

function saveBondHamiltonian(
        hb :: HB,
        fn :: AbstractString,
        group :: AbstractString = "bond_hamiltonian"
        ;
        append :: Bool = false
    ) where {L,HB<:BondHoppingHamiltonianDict{L}}

    # determine the mode based on if one wants to append stuff
    if append
        mode = "r+"
    else
        mode = "w"
    end

    # open the file in mode
    h5open(fn, mode) do file
        # create the group in which the bonds are saved
        group_hb = g_create(file, group)
        # save the type identifier
        attrs(group_hb)["type"] = "BondHoppingHamiltonianDict"
        # save the parameters
        attrs(group_hb)["N"]    = 1
        attrs(group_hb)["L"]    = string(L)
        # save the labels
        if L <: Number
            group_hb["labels"]  = [p[1] for p in hb.couplings]
        else
            group_hb["labels"]  = [string(p[1]) for p in hb.couplings]
        end
        # save the Float64 couplings
        group_hb["couplings"]   = [p[2] for p in hb.couplings]
    end

    # return nothing
    return nothing
end

function loadBondHamiltonian(
        ::Type{HB},
        fn :: AbstractString,
        group :: AbstractString = "bond_hamiltonian"
    ) where {LI,HB<:Union{BondHoppingHamiltonianDict{LI},BondHoppingHamiltonianDict}}

    # read attribute data
    attr_data = h5readattr(fn, group)
    # determine D based on this
    L = Meta.eval(Meta.parse(attr_data["L"]))
    N = attr_data["N"]

    # load coupling
    couplings  = h5read(fn, group*"/couplings")

    # load label
    labels     = L.(h5read(fn, group*"/labels"))

    # return the new bond hamiltonian
    return BondHoppingHamiltonianDict{L}(Dict([(labels[i], couplings[i]) for i in 1:length(labels)]))
end


text:
# Tests the functions in random_walk.jl
# These functions implement two alternate techniques for computing robustness and degree evolvability.
# The default is to store results in a goal_pair_dict
# The alternative is to store results in a goal_edge_matrix
# The test is to make sure that these give the same results when the random number generated has the same seed.
# However, this technique won't work when pmap() is used.
# So to do the test, you must change pmap to map in two places in function run_random_walks_parallel()
# Assuming that this has been done:
include("../src/random_walk.jl")
using Random
p = Parameters(3,1,7,4)
ngoals = 1
g = randgoal( p.numinputs, p.numoutputs )
Random.seed!(1);
ddf=run_random_walks_parallel(4,100,g,p,1000,output_dict=true)
Random.seed!(1);
mdf=run_random_walks_parallel(4,100,g,p,1000,output_dict=false)
#@assert ddf==mdf

# Additional tests
nwalks = 10
steps = 1000
dd = run_random_walks( nwalks, p, steps; output_dict=true )
M = run_random_walks( nwalks, p, steps; output_dict=false )
ssize = 2^(2^p.numinputs)
@assert matrix_to_dict(dict_to_matrix(dd,p)) == dd
@assert dict_to_matrix(matrix_to_dict(M),p) == M


text:
# ---
# title: 915. Partition Array into Disjoint Intervals
# id: problem915
# author: Indigo
# date: 2021-07-12
# difficulty: Medium
# categories: Array
# link: <https://leetcode.com/problems/partition-array-into-disjoint-intervals/description/>
# hidden: true
# ---
#
# Given an array `A`, partition it into two (contiguous) subarrays `left` and
# `right` so that:
#
#   * Every element in `left` is less than or equal to every element in `right`.
#   * `left` and `right` are non-empty.
#   * `left` has the smallest possible size.
#
# Return the **length** of `left` after such a partitioning.  It is guaranteed
# that such a partitioning exists.
#
#
#
# **Example 1:**
#
#
#
#     Input: [5,0,3,8,6]
#     Output: 3
#     Explanation: left = [5,0,3], right = [8,6]
#
#
# **Example 2:**
#
#
#
#     Input: [1,1,1,0,6,12]
#     Output: 4
#     Explanation: left = [1,1,1,0], right = [6,12]
#
#
#
#
# **Note:**
#
#   1. `2 <= A.length <= 30000`
#   2. `0 <= A[i] <= 10^6`
#   3. It is guaranteed there is at least one way to partition `A` as described.
#
#
#
#
## @lc code=start
using LeetCode

function partition_disjoint(nums::Vector{Int})
    n, pos = length(nums), 0
    maxn = leftm = nums[1]
    for i in 2:n
        maxn = max(maxn, nums[i])
        if nums[i] < leftm
            leftm = maxn
            pos = i
        end
    end
    return pos
end
## @lc code=end


text:
#!/usr/bin/env julia --project=@.

using Pkg
Pkg.activate(".")
Pkg.build() # Pkg.build(; verbose = true) for Julia 1.1 and up
Pkg.test() # (coverage=true)


text:
#= credits to:
M. Tamas K. Paap [PhD] @tpap, for the idea of  randvector & randmatrix ( plus the tip of reading the docs)

References:
-Random Int(64):
https://stackoverflow.com/questions/24326876/generating-a-random-integer-in-range-in-julia

#(possible) bitwise operation
=#

export genericGenerator, randvalue, randMatrix, randVector, randvaluerandtemplate
module randomness

function shiftRight(startingHex = 0x2f, offset = 0x1f, h = [+, -])

    return (x >>> (startingHex + offset)) #| (x << (0x3f & k))
end
startingHex = 0x2f
offset = 0x1f
_op = [+, -]
#op
#:op
#eval()
function shiftRight(startingHex = 0x2f, offset = 0x1f, K = -k, op = [+, -])
    return (x >>> (startingHex + offset + 0x3f & K)) #| (x << (0x3f & k))
end

# @double1010x2 #for a common xorshift manupulator #removing the unrelated
@inline xorshift_rotl(x::UInt64, k::Int) = (x >>> (0x3f & -k)) | (x << (0x3f & k)) #a commons move for a permutation
@inline xorshift_rotl(x::UInt32, k::Int) = (x >>> (0x1f & -k)) | (x << (0x1f & k))

#----

# delegation of samplers

#=
    rand!(::AbstractRNG, ::Sampleable, ::AbstractArray)
Samples in-place from the sampler and stores the result in the provided array.
=#
#rand!(::AbstractRNG, ::Sampleable, ::AbstractArray)

#=
    rand(::AbstractRNG, ::Sampleable)
Samples from the sampler and returns the result.
=#
rand(T::Type{AbstractRNG}, S::Type{Sampleable}) #error invalid :: Syntax #works

struct Bar{T}
    (T::Type{Bar{S}})() where {S} = new{T.parameters[1]}()
end

Bar{T}() where {T}

#----

using Random, StableRNGs, Test
#LehmerRNG

"""

Construction: `StableRNG(seed::Integer)`.
Seeding: `Random.seed!(rng::StableRNG, seed::Integer)`.
"""
seed = 12346543975
"""
AbstractRNG not defined
"""
function sumArray(A, range = 1:12)
    return [sum(A .== i) for i = range]
end
global rng = StableRNG(seed)
A = randn(rng, 10, 10) # instead of randn(10, 10)
m = rand(rng, 1:12, 20)
@test inv(inv(A)) ≈ A

sum
_error = inv(inv(A)) - A

#TODO: 1 liner sum

# [sum()]

#---
#=
mutable struct LehmerRNG <: AbstractRNG
    state::UInt128

    LehmerRNG(seed::Integer) = seed!(new(), seed)

    function LehmerRNG(; state::UInt128)
        isodd(state) || throw(ArgumentError("state must be odd"))
        new(state)
    end
end
=#
using StableRNGs, Random, Test
#--- rng: declare
seed = 3257946
rng = StableRNG(seed)
A = rand(rng, 10, 10) # instead of randn(10, 10)
@test inv(inv(A)) ≈ A

#--- sampler

maxcount = 100
range = 1:20
sp = Random.Sampler(rng, range) # define a sampler or Random.Sampler(MersenneTwister, 1:20)
for x in enumerate(maxcount)
    n = rand(rng, sp) # similar to n = rand(rng, 1:20)
    # use n
end
sp

#--- Generate values from sampler

struct Die
    nsides::Int # number of sides
end

#=
struct Die
    #face
    number = 1:6
end

Random.rand(::Random.SamplerType{Die}, number, rng = StableRNG(seed)::StableRNG, range = min(Die.number):max(Die.number)) = Die(rand(StableRNG(seed), range))
end
=#
# out

rand(Die.number)
rand(rng, Die.number)
rand(MersenneTwister(0), Die) #potentially 2 different  rvs
Die(11)

rand(Die.number, 3)

a = Vector{Die}(undef, 3)
rand!(a)

#after rng  geneerator
#generic sampler
#= StableSampler
"Random.SamplerType" & "Random.SamplerTrivial" are Default Fallbacks for types and values, respectively.
Random.SamplerSimple can be used to store pre-computed values,
without defining extra types for only this purpose.
using Random, StableRNGs=#
stablerng = Random.rand( StableRNG(seed), d::Random.SamplerTrivial{Int}) = rand(rng, 1:d[].nsides) #tested #works #{Die} # used AbstractRNG (not StableRNG)

function StableSampler(rng = rng) end #create an empty sampler
#const StableRNG = LehmerRNG

#--- seed

function seed!( StableRNG(seed), seed::Integer)
    seed >= 0 || throw(ArgumentError("seed must be non-negative"))
    seed <= typemax(UInt64) ||
    # this constraint could be loosened a bit if requested
        throw(ArgumentError("seed must be <= $(typemax(UInt64))"))

    seed = ((seed % UInt128) << 1) | one(UInt128) # must be odd
    rng.state = seed
    rng
end

Base.show(io::IO, rng = StableRNG(seed)::StableRNG) =
    print(io, LehmerRNG, "(state=0x", string(rng.state, base = 16, pad = 32), ")")

function Base.copy!(dst = StableRNG(seed), src=S::StableRNG)
    dst.state = src.state
    dst
end

#---

#=
export genericGenerator, randMatrix, randVector, randvalue

using Random;
using StableRNGs;
# e1e8635157374d87126d9d13be15a2679bccb5f0
=#

global seed = 1234
global rng = StableRNG(seed) #defaults to LehmerRNG - StableRNG should be specified  # new- display error LehmerRNG not defined

#= module randomness =#
"""
TODO(1):change non-existing MersenneTwister to anything else...
TODO(3): If is persistent, do Not Reseed (dedault: otherwise reseed) #later #how to not reseed???
"""
function randtemplate(seed = 1234, ispersistent = yes)
    return rng(seed)
end

"""
Returns a single value

```Inputs:

    rng(seed) Random Number Generator
    _min:_max: range any

    Note: Max must be Bounded

        # 1, 10,  1234, MersenneTwister(seed),  []
    #TODO: fill an array
"""
function randvalue(rng = StableRNG(seed), m = 5, n = 5, s = rand(m, n), p = 0.4) #working

    return randsubseq(rng, s, p) #ok# change rng
    #return rand(min:max) # returns a single value x ∈ [min,max]

end

res = randvalue() #ERROR: Type Assert
"""
returns a single value
    returns a single Vector

```inputs:

_min: minimum   , integer , Int64
_max: maximum   , integer , Int64
n:    Number of samples Int64 integer

Note: both maximum & minimum are assumed to be Reachable

e.g.
1. (There are) no Discontinuities at both bounds , &
2. Anomalies' (_min's & _max's) value is Reachable

note: max must be Bounded
```Inputs:
min : minimum value  ::Int64
max:  maimum value  ::Int64

TODO(2): return a Float  between 2 Integers x ∈ [min,max]
"""
#=
function randvalue(rng = StableRNG(seed), _min = 1::int64, _max = 10::Int64)

    # rand(rng,_min,_max)
    A = rand(rng, _min, _max) #ERROR:sampler is not defimed

    return A # returns a single value  x ∈ [min,max]

end

r = randvalue(StableRNG, 1, 2) #test
=#

"""
   Returns a single Vector Uniformly

   Example: randVector(_1::Int64, _max = 10::Int64, n = 10::Int64

  #TODO: Test the output
"""
function randVector(rng = StableRNG, _min = 1, _max = 10, n = 10)

    return rand(rng, _min:_max) # 1D array - n-element Array{Int64,1}
end
randVector()

function randVector(_min = 1::Int64, _max = 10::Int64, n = 10::Int64)

    return rand(_min:_max, n) # 1D array - n-element Array{Int64,1}

end

"""
 Returns a single Vector with n
"""

function randVector(_min = 1::Int64, _max = 10::Int64, n = 10::Int64)

    return rand(_min:_max, n) # 1D array - n-element Array{Int64,1}

end

"""
 Returns a single Matrix (2D - Array)
"""
#=
function randMatrix(rng = StableRNG(seed), min = 1::Int64, max = 10::Int64, a = 10, b = 11)

    return #=rand(rng, min:max, a, b)=#
end
=#

rand(StableRNG(seed), min, max, 10, 10)

"""
Returns a single Matrix (2D - Array)

"""
function randMatrix(_min = 1::Int64, _max = 10::Int64)

    return rand(_min:_max, n)
end

"""
Returns a single Matrix (2D - Array)
range(start[, stop]; length, stop, step=1)
range(1, step=5, length=100)
range(1, step=5, length=100)
"""
function randMatrix(r = _min:_max::range(Int64, Int64)) #::range(Int64,Int64))
    r = _min:_max
    #do a computation
    return rand(r, 2)
end

#=
function randArray(r = _min:_max)

        r = _min:_max
    #do a computation
    return r
=#

#--- helper functions

function permutate(rng = StableRNG(seed), n = 10) #sanity-check #where's the input? (value,Vector,...)
    return randperm(rng(seed), n)
end

permutate(StableRNG)

#--- testing 4
#permutate(MersenneTwisters(1234,n)

#randvalue(min = 1, max = 10, rng = )#TODO: uncomment lated

#randvalue(1, 10,  1234, MersenneTwisters(1234),  []) #MersenneTwister has been removed in julia 1.7

#---

#=
    LehmerRNG
    StableRNG
Simple RNG with stable streams, usually suitable for testing.
Use only the alias `StableRNG`, as the name `LehmerRNG` is not
part of the API.
Construction: `StableRNG(seed::Integer)`.
Seeding: `Random.seed!(rng::StableRNG, seed::Integer)`.
=#
mutable struct randomRNG <: StableRNGs #  AbstractRNG
    state::UInt64

    randomRNG(seed::Integer) = seed!(new(), seed)

    #if redundant, please do Delete
    function StableRNG(; state::UInt128)
        isodd(state) || throw(ArgumentError("state must be odd"))
        new(state)
    end
end

state #2 cannot declare a constant, it has already a value
#const StableRNG = LehmerRNG #invalid redefinition

function seed!(seed::Integer,rng=StableRNG(seed) )
    seed >= 0 || throw(ArgumentError("seed must be non-negative"))
    seed <= typemax(UInt64) ||
    # this constraint could be loosened a bit if requested
        throw(ArgumentError("seed must be <= $(typemax(UInt64))"))

    seed = ((seed % UInt128) << 1) | one(UInt128) # must be odd
    rng.state = seed
    rng
end
using StableRNGs
print(seed!(StableRNG(seed), seed))# something seems off -

Base.show(io::IO, rng = StableRNG::stableRNG) =
    print(io, StableRNG, "(state=0x", string(rng.state, base = 16, pad = 32), ")") # how state can be relevant ( to my situation?)

function Base.copy!(dst = StableRNG::stableRNG, src = StableRNG::stableRNG)
    dst.state = src.state #copy state
    dst
end

Base.copy(src = StableRNG(seed)::stableRNG) = stableRNG(state = src.state)

Base.:(==)(x = StableRNG(seed)::stableRNG, y =

StableRNG(seed) = x.state == y.state #y.state is indifferent , honestly

hash = Base.hash( StableRNG(seed)::StableRNG, h::UInt) = hash(rng.state, 0x93f376feff2bc48e % UInt ⊻ h)

## Sampling

using StableRNGs
#=
rng = StableRNG(seed = 1234, state = randState()) # cyclic code detected: State not asssignment (state dependent method )# self-referencing detected: randState()requires StableRNG,with StableRNG requires RandomState !
=#

function randState(rng)#::SamplerType{UInt128})
    rng.state *= 0x45a31efc5a35d971261fd0407a968add
    return (rng.state >> 64) % UInt128 #waiting UInt128 ! (i cannot comfortably work with that - too much on the memory)
end

function isEqual(rng, ::SamplerType{T}) #ok #SamplerType #TODO: define

    for T = [Bool, Base.BitInteger64_types...]
        T === UInt128 && continue
        @eval rand(rng::stableRNG, ::SamplerType{$T}) = rand(rng, UInt128) % $T
    end

end
rand(rng::stableRNG, ::SamplerType{UInt64}) = #UInt128 is bit too large for my requirements
    rand(rng, UInt64) | ((rand(rng, UInt64) % UInt128) << 64)

rand(rng::stableRNG, ::SamplerType{UInt64}) = rand(rng, UInt128) #Int128

Random.rng_native_52(::stableRNG(seed)) = UInt64

#--- within a range

# adapted verion of Random.SamplerRangeFast for native 64 bits generation
# we don't use "near division-less algorithm", as it doesn't work for Int128,
# and we want to maintain as little code as possible here

using Base: BitUnsigned, BitInteger
using Random: LessThan, Masked, uniform

struct SamplerRangeFast{U<:BitUnsigned,T<:BitInteger} <: Sampler{T} # define  a sampler
    a::T      # first element of the range
    bw::UInt  # bit width
    m::U      # range length - 1
    mask::U   # mask generated values before threshold rejection
end

SamplerRangeFast(r::AbstractUnitRange{T}) where {T<:BitInteger} =
    SamplerRangeFast(r, T <: Base.BitInteger64 ? UInt64 : UInt128)

function SamplerRangeFast(r::AbstractUnitRange{T}, ::Type{U}) where {T,U}
    isempty(r) && throw(ArgumentError("range must be non-empty"))
    m = (last(r) - first(r)) % unsigned(T) % U
    #                        ^--- % unsigned(T) to not propagate sign bit
    bw = (sizeof(U) << 3 - leading_zeros(m)) % UInt # bit-width
    mask = ((1 % U) << bw) - (1 % U)
    SamplerRangeFast{U,T}(first(r), bw, m, mask)
end

function rand(rng=StableRNG:StableRNG, sp::SamplerRangeFast{UInt64,T}) where {T}
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
    x = rand(rng, LessThan(m, Masked(mask, uniform(UInt64))))
    (x + a % UInt64) % T
end

#---
function rand(rng=StableRNG()::StableRNG, sp::SamplerRangeFast{UInt128,T}) where {T}
    a, bw, m, mask = sp.a, sp.bw, sp.m, sp.mask
    x = bw <= 64 ?
        rand(rng,
        LessThan(m % UInt64,
            Masked(mask % UInt64, uniform(UInt64)))) % UInt128 :
        rand(rng, LessThan(m, Masked(mask, uniform(UInt128))))
    x % T + a
end

function unknownOne()
    for T in Base.BitInteger_types
        # eval because of ambiguities with `where T <: BitInteger`
        @eval Sampler(::Type{LehmerRNG}, r::AbstractUnitRange{$T}, ::Random.Repetition) =
            SamplerRangeFast(r)
    end

end
end

max_stars_repo_name: adamwillisMastery/DeepLearner

max_issues_repo_name: adamwillisMastery/DeepLearner

max_forks_repo_name: adamwillisXanax/DeepLearner


text:
using Timestamps
using Documenter

DocMeta.setdocmeta!(Timestamps, :DocTestSetup, :(using Timestamps); recursive=true)

makedocs(;
    modules=[Timestamps],
    authors="Andrey Oskin and contributors <https://github.com/JuliaQuant/Timestamps.jl/graphs/contributors>",
    repo="https://github.com/JuliaQuant/Timestamps.jl/blob/{commit}{path}#{line}",
    sitename="Timestamps.jl",
    format=Documenter.HTML(;
        prettyurls=get(ENV, "CI", "false") == "true",
        canonical="https://JuliaQuant.github.io/Timestamps.jl",
        siteurl="https://github.com/JuliaQuant/Timestamps.jl",
        assets=String[],
    ),
    pages=[
        "Home" => "index.md",
    ],
)

deploydocs(;
    repo="github.com/JuliaQuant/Timestamps.jl",
)


text:
p1 = random_micrm_params(2,2,0.5)

p2 = deepcopy(p1)
p2[:u] = rand(2,2)
p2[:R] = rand(2)

p_coal = coalesce_communities(p1,p2)

@testset "coalescence dictionary" begin
    @test p_coal[:N] == 4
    @test p_coal[:M] == 2
end


text:
using GR

# GR initialization
setwindow(1, 640, 1, 480)
setviewport(0, 1, 0, 1)
setfillintstyle(GR.INTSTYLE_SOLID)
setlinetype(GR.LINETYPE_SOLID)
setlinewidth(1)
GR.setmarkertype(GR.MARKERTYPE_DOT)
GR.setmarkersize(1)

# our approach for calculating ips
type Rps
  ts::Float64
  req::Int
end
_rps = Rps(0.0, 0)

# rect coordinates
x1 = 1.0
x2 = 640.0
y1 = 1.0
y2 = 480.0

setcolorrep(1, 1.0, 1.0, 1.0)
setcolorrep(2, 0.0, 0.0, 0.0)
# press ctrl-c to stop the demo
i = 0
while i < 500000 # ~5seconds
  i += 1
  # calculating ips (Iterations per second)
  if time() - _rps.ts > 1.0
  	_rps.ts = time()
  	print("rps: ", _rps.req)
  	_rps.req = 0
  end
  _rps.req += 1

  #clearws()
  # this code clears previous rect
  #setlinecolorind(2)
  #setfillcolorind(2)
  #fillrect(x1, x2, y1, y2)

  #setlinecolorind(1)
  #setfillcolorind(1)
  #x1 = Float64(rand(-2:2))
  #x2 = Float64(rand(-2:2))
  #y1 = Float64(rand(-2:2))
  #y2 = Float64(rand(-2:2))
  #fillrect(x1, x1 + 2, y2, y2 + 2)
  setmarkercolorind(1000)
  polymarker([x2], [y2 - y1 + 1])
  updatews()
end

max_stars_repo_name: tmptrash/jevo

max_issues_repo_name: tmptrash/jevo

max_forks_repo_name: tmptrash/jevo


text:
using LightGraphs

struct Diffusion
  graph::Graph
  reached::Set{Int64}
  intermediate_reached::Set{Int64}
  to_watch::Set{Int64}
  p::Float64
  normalize_p::Bool
end

"""

    diffusion_simulation(g, p, num_steps;
                         to_watch=Set(vertices(g))
                         initial_at_risk=Set(vertices(g)),
                         normalize_p=false
                         )

### Implementation Notes

Runs diffusion simulation on `g` for `num_steps` with spread
probabilities based on `p`.

Returns an Array with number of vertices reached at each step of
simulation.

While simulation is always run on full graph, specifying `to_watch`
allows for reporting of the number of vertices reached within
a subpopulation.

If `normalized_p` is `false`, the probability of spread from a vertex i to
each of the out_neighbors of `i` is `p`.

If `normalized_p` is `true`, the probability of spread from a vertex `i` to
each of the out_neighbors of `i` is `p / degree(g, i)`.

"""

function diffusion_simulation(g::Graph,
                              p::Float64,
                              num_steps::Int64;
                              to_watch::Set{Int64}=Set(vertices(g)),
                              initial_at_risk::Set{Int64}=Set(vertices(g)),
                              normalize_p::Bool=false)

  simulation = Diffusion(g,
                         Set{Int64}(),
                         Set{Int64}(),
                         to_watch,
                         p,
                         normalize_p)

  vertices_reached = zeros(Int64, num_steps)

  # Initiate
  initial_infection(simulation, initial_at_risk)

  # Run for num_steps
  for step in 1:num_steps
    for i in simulation.reached
      infect_neighbors(simulation, i)
    end

  # flip state vectors
  union!(simulation.reached, simulation.intermediate_reached)

  # Get infection rate
  vertices_reached[step] = length( intersect(simulation.reached, simulation.to_watch) )
  end

  return vertices_reached

end

function initial_infection(simulation::Diffusion, initial_at_risk)
  i = rand(initial_at_risk)
  push!(simulation.reached, i)
end

function infect_neighbors(simulation, i)

  if simulation.normalize_p
    p = simulation.p / degree(simulation.graph, i)
  else
    p= simulation.p
  end

  for n in out_neighbors(simulation.graph, i)
    if rand(Float16) < p
      push!(simulation.intermediate_reached, n)
    end
  end

end


text:
struct ModelSpec{M <: AbstractMLModel, D <: MLData, S <: LearningStrategy}
    model::M
    data::D
    strat::S
end

function Base.show(io::IO, o::ModelSpec)
    println(io, "ModelSpec:")
    println(io, "  > model: ", o.model)
    println(io, "  > data : ", o.data)
    print(  io, "  > strat: ", o.strat)
end

function learn!(o::ModelSpec, strats::LearningStrategy...)
    s = strategy(o.strat, strats...)
    learn!(o.model, s, Iterators.repeated(o.data))
end


text:
### A Pluto.jl notebook ###
# v0.12.21

using Markdown
using InteractiveUtils

# This Pluto notebook uses @bind for interactivity. When running this notebook outside of Pluto, the following 'mock version' of @bind gives bound variables a default value (instead of an error).
macro bind(def, element)
    quote
        local el = $(esc(element))
        global $(esc(def)) = Core.applicable(Base.get, el) ? Base.get(el) : missing
        el
    end
end

# ╔═╡ 3b2050da-52c1-11eb-3b89-1d5b6eb2cf40
using PlutoUI, Printf, Plots, StatsPlots;

# ╔═╡ 49f027da-5dce-11eb-3fff-0fd590112019
using DataFrames, Distributions, Random

# ╔═╡ 8ae7009a-73c4-11eb-0374-25c172bd827e
md"""
# Carbon Footprint
"""

# ╔═╡ ae828cb2-86a8-11eb-2862-6137ecb692a5
md"""By: Dileep Kishore, Srikiran Chandrasekaran """

# ╔═╡ 94e65102-73c4-11eb-3cb4-81736a39e596
md"""
>A carbon footprint is the total greenhouse gas (GHG) emissions caused by an individual, event, organization, service, or product, expressed as carbon dioxide equivalent.
>Source: Wikipedia.

From an individual perspective, GHG may be emitted from activities such as driving a car, consuming food or even just streaming content over the internet.

In this dashboard we limit the sources of GHG emissions to:
1. Electricity usage
2. Food consumption
3. Streaming over the internet
4. Purchase of manufactured goods
5. Transportation
"""

# ╔═╡ 054ae36c-52cb-11eb-25aa-31355bbed6de
md"""## Sources of GHG emissions

Most of the data presented here was obtained from [NMF-earth](https://github.com/NMF-earth/carbon-footprint). The direct sources of the data are listed along with the source descriptions below:
"""

# ╔═╡ b4a152f0-4d4f-11eb-106b-b58e9f1495a9
import JSON, HTTP

# ╔═╡ 69f1de08-7e7f-11eb-1df1-c792e5e3ec57
md"""
First we write a function `read_json` to read `JSON` data from our [GitHub repository](https://github.com/quantumbrake/ghg-dashboard/) into a `Dict`
"""

# ╔═╡ cedb71ac-52b9-11eb-19e7-9f433ffb4f14
function read_json(
	file::String;
	repo::String = "https://raw.githubusercontent.com/quantumbrake/ghg-dashboard/main/"
	)::Dict
	file_url = repo * file
	raw_string = String(HTTP.get(file_url).body)
	data = JSON.parse(raw_string)
	return data
end

# ╔═╡ b2b598f8-4d3f-11eb-310d-7740ecc9d222
md"""
### 1. Electricity usage

The emissions involved in generating 1 Joule of energy in various countries

Unit: $\frac{kgCO_2eq}{J}$

Unit of imported data: $\frac{kgCO_2eq}{kWh}$

Conversion factor (imported data -> data): $(\frac{x}{3.6}) * 10^{-6}$

**Sources**:
- https://github.com/carbonalyser/Carbonalyser
- https://www.electricitymap.org - 28th of April 2020
"""

# ╔═╡ 0fcd983e-52b7-11eb-2c1f-13d00c8b4c43
begin
	pw_to_pj(x::Float64)::Float64 = (x / 3.6) * (10 ^ (-6))
	electricity_data_pw = read_json("data/carbon_footprint/electricity.json")
	values_pj = map(x -> pw_to_pj(x), values(electricity_data_pw))
	electricity_data = Dict(zip(keys(electricity_data_pw), values_pj))
	DataFrame(electricity_data)
end

# ╔═╡ 1fc15990-4d41-11eb-0f5f-c309cf01fdfa
md"""
### 2. Food consumption

The emissions involved in producing 1 item of various foods

Unit: $\frac{kgCO_2eq}{\textrm{item}}$

**Sources**:
- http://www.greeneatz.com/foods-carbon-footprint.html
- https://www.bilans-ges.ademe.fr
"""

# ╔═╡ 329e738a-52ba-11eb-22dd-fbfe2de89bb1
begin
	food_data = read_json("data/carbon_footprint/food.json")
	DataFrame(food_data)
end

# ╔═╡ e8574808-4d49-11eb-3515-2d66aadee9f2
md"""
### 3. Streaming over the internet

The emissions involved in streaming various content

Unit: $\frac{kgCO_2eq}{minute}$

**Standards used to calculate data size of streaming content**:
- HD / 720p : 1.21 GB (~ 2.5 hours)
- Full HD / 1080p : 7.02 GB (~ 2.5 hours)
- Ultra HD / 2160p : 35.73 Gb (~ 2.5 hours)
- MP3 song at 192 kbps : 3.8 MB (~ 2.5 mins)
"""

# ╔═╡ 83af9228-6353-11eb-0e5b-4550ac55ca4f
streaming_data = Dict(["HDVideo" => "Video HD",
			"fullHDVideo" => "Video - FullHD/1080p",
			"ultraHDVideo" => "Video - UltraHD/4K",
			"audioMP3" => "Audio - MP3"]);

# ╔═╡ fb596dc6-4d41-11eb-1dbd-6707e4fa7778
md"""
Calculating the emissions involved in moving data between the device and datacenter through the network.

Unit: $kgCO_2eq$

**Sources**:
- https://theshiftproject.org/wp-content/uploads/2019/03/Lean-ICT-Report_The-Shift-Project_2019.pdf
- https://github.com/carbonalyser/
- https://www.carbonbrief.org/factcheck-what-is-the-carbon-footprint-of-streaming-video-on-netflix
"""

# ╔═╡ 227d45a0-4d45-11eb-0cca-af99bc390097
function kwatts_to_joules(x::Float64)::Float64
		x * 3.6 * (10 ^ 6);
end

# ╔═╡ d4764dc0-7e81-11eb-29da-adbfa04c613b
md"""
We create a function to calculate the GHG emissions involved in transmitting `dataweight` (in bits) amount of data for a `duration` (in seconds) in a country with emission intensity equal to `electricity_intensity` (in $kgCO_2eq.J^{-1}$). As suggested by the units of this quantity, emission intensity is simply the amount of $CO_2$ in kilograms per emitted per Joule of energy produced.
"""

# ╔═╡ cfd60bf8-4d43-11eb-00b7-bd162061b954
function internet_carbonimpact(
		duration::Float64,
		data_weight::Float64,
		electricity_intensity::Float64
	)::Float64
	factor = Dict(
		"datacenter" => kwatts_to_joules(0.007 * (10 ^ (-9))) / 8,
		"network" => kwatts_to_joules(0.058 * (10 ^ (-9))) / 8,
		"device" => kwatts_to_joules(0.055 / (60 * 60))
	)
	ghg_datacenter = data_weight * get(factor, "datacenter", 0.0) * electricity_data["world"]
	ghg_network = data_weight * get(factor, "network", 0.0) * electricity_data["world"]
	ghg_device = duration * get(factor, "device", 0.0) * electricity_intensity
	total = ghg_datacenter + ghg_network + ghg_device
	return total
end

# ╔═╡ c25bfd94-7f7e-11eb-32ff-6fb869cd3b43
md"""
Next, we create a function to calculate carbon emissions created while streaming a particular type of content (`stream_type`) for `duration` (in seconds) in a country with emission intensity equal to `electricity_intensity` (in $kgCO_2eq.J^{-1}$)
"""

# ╔═╡ 5e3ae372-4d4a-11eb-3e76-e7b1545f3759
function streaming_carbonimpact(
		stream_type::String,
		duration::Float64,
		electricity_intensity::Float64
	)::Float64
	# assuming movie duration = 2h 22m, and file size as given above.
	# factor is a dictionary mapping kind of data to bits/s.
	factor = Dict(
		"HDVideo" => (1.21 * (10 ^ 9) * 8) / ((2 * 60 + 22) * 60),
		"fullHDVideo" => (7.02* (10 ^ 9) * 8) / ((2 * 60 + 22) * 60),
		"ultraHDVideo" => (35.73 * (10 ^ 9) * 8) / ((2 * 60 + 22) * 60),
		"audioMP3" => (3.8 * (10 ^ 6) * 8) / 154
	)
	data_weight = get(factor, stream_type, 0.0)
	total_carbonimpact = internet_carbonimpact(
		duration,
		data_weight,
		electricity_intensity
	)
	return total_carbonimpact
end

# ╔═╡ cccb00f0-4d46-11eb-027b-ab6e07ce3ce5
md"""
### 4. Purchase of manufactured goods

The emissions involved in producing 1 item of various products

Unit: $\frac{kgCO_2eq}{item}$

**Sources Clothing**:
- https://www.ademe.fr/sites/default/files/assets/documents/poids_carbone-biens-equipement-201809-rapport.pdf

**Sources Tech**:
- https://www.apple.com/lae/environment/pdf/products/iphone/iPhone_11_Pro_PER_sept2019.pdf
- https://www.apple.com/lae/environment/pdf/products/ipad/iPad_PER_sept2019.pdf
- https://www.apple.com/lae/environment/pdf/products/desktops/21.5-inch_iMac_with_Retina4KDisplay_PER_Mar2019.pdf
- https://www.apple.com/lae/environment/pdf/products/notebooks/13-inch_MacBookPro_PER_June2019.pdf
- https://www.bilans-ges.ademe.fr/fr/basecarbone/donnees-consulter/liste-element?recherche=T%C3%A9l%C3%A9vision

**Sources Transport**:
-   https://www.lowcvp.org.uk/assets/workingdocuments/MC-P-11-15a%20Lifecycle%20emissions%20report.pdf
"""

# ╔═╡ 42eb4b3e-52ba-11eb-2178-11e1d2a887af
begin
	purchase_data = read_json("data/carbon_footprint/purchase.json")
	DataFrame(purchase_data)
end

# ╔═╡ cd98af32-4d4b-11eb-2ffb-edbe9a3c069b
md"""
### 5. Transportation

The emissions per meter travelled in various vehicles

Unit: $\frac{kgCO_2eq}{m}$

**Sources**:
- https://static.ducky.eco/calculator_documentation.pdf
"""

# ╔═╡ 04b51758-52b7-11eb-10f9-f5be66cf0dec
begin
	transport_data = read_json("data/carbon_footprint/transport.json")
	DataFrame(transport_data)
end

# ╔═╡ 66d55490-7f7c-11eb-2d2d-77f9b4f7b184
md"""---"""

# ╔═╡ 0442fbb8-52c0-11eb-06ea-01e68e330d5d
md"""
## Carbon footprint Dashboard
"""

# ╔═╡ 52ee864c-8445-11eb-15b0-47a0f97b6fec
plotly()

# ╔═╡ 5fbcb6e6-52ca-11eb-3e8c-1bb7495dc15d
md"""### Check your emissions here

You can use this section to compute the total emissions from various activities. Note that this is emissions from all these activities, and not normalized on a per day basis for instance."""

# ╔═╡ 1b612ec2-52c1-11eb-22aa-3b406bd64623
md"""
#### Electricity:

Electricty location
$(@bind electricity_select Select([k => k for (k, v) in electricity_data]))

Electricity amount (in kWh)
$(@bind electricity_amount Slider(1:1000, default=10, show_value=true))

#### Food:

Food type
$(@bind food_select Select([k => k for (k, v) in food_data]))

Food amount (in grams)
$(@bind food_amount Slider(5:500, default=10, show_value=true))

#### Streaming:

Streaming type
$(@bind streaming_select Select(["HDVideo" => "Video HD",
			"fullHDVideo" => "Video - FullHD/1080p",
			"ultraHDVideo" => "Video - UltraHD/4K",
			"audioMP3" => "Audio - MP3"]))

Duration (in minutes)
$(@bind streaming_amount Slider(10:600, default=60, show_value=true))

#### Purchases:

Recent purchases
$(@bind purchase_select MultiSelect([k => k for (k, v) in purchase_data]))

#### Transport:

Transport type
$(@bind transport_select Select([k => k for (k, v) in transport_data]))

Transport distance (in km)
$(@bind transport_distance Slider(1:1000, default=10, show_value=true))
"""

# ╔═╡ f5225d7a-5846-11eb-1497-c5d439899e6b
function emission_calculator(
		transport_select::String,
		transport_distance::Integer,
		food_select::String,
		food_amount::Integer,
		streaming_select::String,
		streaming_amount::Integer,
		electricity_select::String,
		electricity_amount::Integer,
		purchase_select::Array,
)::Dict
	transport_emissions = transport_data[transport_select] * transport_distance * 1000
	food_emissions = food_data[food_select] * food_amount / 1000
	streaming_emissions = streaming_carbonimpact(streaming_select,streaming_amount * 60.0,electricity_data["world"])
	electricity_emissions = electricity_data_pw[electricity_select] * electricity_amount
	if isempty(purchase_select)
		purchase_emissions = 0.0
	else
		purchase_emissions = sum([purchase_data[purchase] for purchase in purchase_select])
	end
	total_emissions = (transport_emissions + food_emissions + streaming_emissions + electricity_emissions + purchase_emissions)
	data = Dict(
		"transport" => transport_emissions,
		"food" => food_emissions,
		"streaming" => streaming_emissions,
		"electricity" => electricity_emissions,
		"purchase" => purchase_emissions,
		"total" => total_emissions,
		)
	return data
end

# ╔═╡ 8aa42c6e-6354-11eb-3c43-cb16327595c2
function emission_calculator(
		transport_select::Array{String,1},
		transport_distance::Array{Int64,1},
		food_select::Array{String,1},
		food_amount::Array{Int64,1},
		streaming_select::Array{String,1},
		streaming_amount::Array{Int64,1},
		electricity_select::String,
		electricity_amount::Int64,
		purchase_select::Array{String, 1},
		purchase_amount::Array{Int64, 1},
)::Dict
	transport_emissions = 0
	for (i, j) in zip(transport_select, transport_distance)
		transport_emissions += transport_data[i] * j * 1000
	end
	food_emissions = 0
	for (i, j) in zip(food_select, food_amount)
		food_emissions += food_data[i] * j / 1000
	end
	streaming_emissions = 0
	for (i, j) in zip(streaming_select, streaming_amount)
		streaming_emissions += streaming_carbonimpact(i, j * 60.0,electricity_data["world"])
	end
	electricity_emissions = electricity_data_pw[electricity_select] * electricity_amount
	purchase_emissions = 0.0
	for (i, j) in zip(purchase_select, purchase_amount)
		purchase_emissions += purchase_data[i] * j
	end
	total_emissions = (transport_emissions + food_emissions + streaming_emissions + electricity_emissions + purchase_emissions)
	data = Dict(
		"transport" => transport_emissions,
		"food" => food_emissions,
		"streaming" => streaming_emissions,
		"electricity" => electricity_emissions,
		"purchase" => purchase_emissions,
		"total" => total_emissions,
		)
	return data
end

# ╔═╡ 9388aa8a-52c9-11eb-0dd8-3184bcfb93b2
begin
	emissions_data = emission_calculator(
			transport_select,
			transport_distance,
			food_select,
			food_amount,
			streaming_select,
			streaming_amount,
			electricity_select,
			electricity_amount,
			purchase_select,
	)
	transport_emissions = emissions_data["transport"]
	food_emissions =  emissions_data["food"]
	streaming_emissions =  emissions_data["streaming"]
	electricity_emissions =  emissions_data["electricity"]
	purchase_emissions = emissions_data["purchase"]
	total_emissions = emissions_data["total"]
	"Emissions calculation code"
end

# ╔═╡ 2b0d264c-7f7f-11eb-2bf6-1119de8bbe96
begin
	x = ["Electricity", "Food", "Streaming", "Purchases", "Transport"]
	y = [electricity_emissions, food_emissions, streaming_emissions, purchase_emissions, transport_emissions]
	pie(x, y, title="Emissions breakdown (Total = $(@sprintf("%.2f", total_emissions)) kgCO2eq)", legend=:right)
end

# ╔═╡ 0a38c120-52c6-11eb-2ec5-e7780b3e11ec
md"""
### Your carbon footprint:

| Emission source | kgCO2eq |
| --- | --- |
| Electricity | $(@sprintf("%.3f", electricity_emissions)) |
| Food | $(@sprintf("%.3f", food_emissions)) |
| Streaming | $(@sprintf("%.3f", streaming_emissions)) |
| Purchase | $(@sprintf("%.3f", purchase_emissions)) |
| Transport | $(@sprintf("%.3f", transport_emissions))  |
| **Total emissions** | **$(@sprintf("%.3f", total_emissions))** |

"""

# ╔═╡ ec388b4a-52ca-11eb-097d-6760de18dd0e
md"""---"""

# ╔═╡ 34baf426-7f7f-11eb-0cf0-bb0d1a7c28fd
md"""
## Carbon footprint simulations for different lifestyles
"""

# ╔═╡ 672fef94-6351-11eb-0af1-652d5992e129
Random.seed!(1234);

# ╔═╡ 18787dee-8446-11eb-2b9d-9967d7fe6d5c
md"""
We create a "Person" `struct` that stores information about a lifestyle. This can be used to simulate the daily behavior of a person following this lifestyle and understand emissions due to:
1. Vehicles owned and their usage distribution
2. Food consumed and their amount
3. Content streamed and their amount
4. Country of residence
5. Commonly purchased products and their purchase rates

>NOTE:
>We assume that the distributions for each emission type are applicable to all objects or items of that type.
>Eg: If `foods` are "tofu" and "beans" and the provided `food_consumption` distribution is $\mathcal{N}(150, 50)$, we assume that each food item follows that distribution.
"""

# ╔═╡ 49571046-68c2-11eb-071e-2709f8e40e48
struct Person
	vehicles::Array{String,1}
	transport_distribution::ContinuousUnivariateDistribution
	foods::Array{String,1}
	food_consumption::ContinuousUnivariateDistribution
	streams::Array{String,1}
	streaming_distribution::ContinuousUnivariateDistribution
	country::String
	electricity_usage::ContinuousUnivariateDistribution
	purchases::Array{String,1}
	purchase_rate::DiscreteUnivariateDistribution
end

# ╔═╡ e0ad3a7e-8447-11eb-2df2-3d52fffaab6b
md"""
We create functions to calculate the daily and yearly emissions of a `Person`:
"""

# ╔═╡ 2c63765e-68c3-11eb-317c-d1603846ca9c
function daily_emissions(person::Person)::Dict
	transport_distances = floor.(
		Int,
		rand(
			person.transport_distribution,
			length(person.vehicles)
		)
	)
	food_amounts = floor.(
		Int,
		rand(
			person.food_consumption,
			length(person.foods)
		)
	)
	stream_amounts = floor.(
		Int,
		rand(
			person.streaming_distribution,
			length(person.streams)
		)
	)
	electricity_amounts = floor.(
		Int,
		rand(
			person.electricity_usage,
		)
	)
	purchase_amounts = floor.(
		Int,
		rand(
			person.purchase_rate,
			length(person.purchases)
		)
	)
	result = emission_calculator(
	person.vehicles,
	transport_distances,
	person.foods,
	food_amounts,
	person.streams,
	stream_amounts,
	person.country,
	electricity_amounts,
	person.purchases,
	purchase_amounts,
	)
	return result
end

# ╔═╡ 7bb8f0e4-8448-11eb-2bd5-e9f94078860e
function yearly_emissions(person::Person)::DataFrame
	df = DataFrame(daily_emissions(person))
	for i in range(2, stop=365)
		push!(df, daily_emissions(person))
	end
	return df
end

# ╔═╡ 04badb38-8448-11eb-2750-fde9b58547e4
md"""
### Case Study: Switching from a meat rich diet to a vegan diet

Let us consider the case where a person following a meat rich diet considers switching to a vegan diet and the impact it would have on their carbon footprint
"""

# ╔═╡ 5114761e-84d0-11eb-094e-fde0d465d19e
md"""
We create a `Person` who eats a diet rich in meat and animal derived products (`person_meat`) and a `Person` who follows a vegan diet (`person_vegan`). The only differences between these two is in the food items they eat (consumption quantities are the same).

Each `Person`:
1. Owns a car and drives on an average of 50 km per day
2. Watches ultraHDVideo for an average of 240 mins a day
3. Lives in the USA and uses an average of 30 kWh of electrcity per day
4. Buys jeans, shirts and shoes at the rate of 1 per 100 days

Additionally:
- The `person_meat` eats an average of 120g of pork, chicken, milk, eggs and rice everyday
- The `person_vegan` eats an average of 120g of fruit, tofu, beans, vegetables and rice everyday

>Note that it is possible to create more accurate and sophisticated distributions, but for the purposes of this case study we have decided to limit it to simple foods and distributions.
"""

# ╔═╡ f9d0182e-8450-11eb-3f42-3df1cf54cf96
person_meat = Person(
	["car"],
	truncated(Normal(50, 5), 0, 1000),
	["pork", "chicken", "milk", "eggs", "rice"],
	truncated(Normal(120, 20), 0, 500),
	["ultraHDVideo"],
	truncated(Normal(240, 50), 0, 600),  # 240 mins is US average
	"usa",
	truncated(Normal(30, 5), 0, 200),  # 30 kwh is US average
	["jeans", "shirt", "shoes"],
	Poisson(0.01)
)

# ╔═╡ 521ebdb6-68c5-11eb-3bb2-8926b33ec780
person_vegan = Person(
	["car"],
	truncated(Normal(50, 5), 0, 1000),
	["fruit", "tofu", "beans", "vegetables", "rice"],
	truncated(Normal(120, 20), 0, 500),
	["ultraHDVideo"],
	truncated(Normal(240, 50), 0, 600),  # 240 mins is US average
	"usa",
	truncated(Normal(30, 5), 0, 200),  # 30 kwh is US average
	["jeans", "shirt", "shoes"],
	Poisson(0.01)
)

# ╔═╡ 081ee4fc-84f4-11eb-3bad-a1e680d897b3
md"""
The daily emissions of `person_meat` for a year:
"""

# ╔═╡ 2af54294-8451-11eb-29b9-dd400f6ceb74
emissions_meat = yearly_emissions(person_meat)

# ╔═╡ f0ecfbb6-84f3-11eb-0b02-27ffea69c7ca
md"""
The daily emissions of `person_vegan` for a year:
"""

# ╔═╡ 751bb036-844e-11eb-035b-6d62fe25bfce
emissions_vegan = yearly_emissions(person_vegan)

# ╔═╡ b185179e-8451-11eb-1877-593c6b4be750
begin
	emissions_vegan_long = stack(emissions_vegan, [:electricity, :food, :purchase, :streaming, :transport]);
	emissions_meat_long = stack(emissions_meat, [:electricity, :food, :purchase, :streaming, :transport]);
end;

# ╔═╡ 4d7c796a-84f4-11eb-19cf-dfd729ac8b98
md"""
A plot of the distributions of daily emissions of each `Person` in each category is shown below. Only the distribution of emissions from food consumption are distinctly different (as per the design of the case study)
"""

# ╔═╡ 5b1d34d4-8451-11eb-15b5-1d45b1b3cb01
begin
	@df emissions_vegan_long violin(:variable, :value, side=:left, label="vegan diet", linewidth=0, title="Distribution of carbon emissions", ylabel="kgCO2eq")
	@df emissions_meat_long violin!(:variable, :value, side=:right, label="meat diet", linewidth=0)
end

# ╔═╡ 2245ae6e-84f5-11eb-0bc9-61f05b3d6935
md"""
We then plot only the distribution of daily emissions from food consumption of both `person_vegan` and `person_meat`.

The means are $\approx$ $(@sprintf("%.3f", mean(emissions_meat[!, :food]) - mean(emissions_vegan[!, :food]))) kgCO2eq apart (with the meat diet having higher emissions) and we observe that the choice of foods allowed for the meat diet in this case study offer for a wider range of emissions compared to the vegan diet.
"""

# ╔═╡ b7a631d2-8454-11eb-3ff7-5b02d14ce2b9
begin
	@df emissions_vegan density(:food, fill=(0, .5, :green), label="vegan diet (food)", xlabel="kgCO2eq", ylabel="Density", title="Density plot of daily emissions due to food", legend=:right)
	@df emissions_meat density!(:food, fill=(0, .5, :red), label="meat diet (food)")
end

# ╔═╡ e6423e30-84f6-11eb-0c07-cdae8e894eb0
md"""
Does this shift in the distribution of emissions due to food consumption affect the overall carbon emissions in any significant way?

To answer this question we plot the distribution of total emissions (shown below) and observe that there is indeed a shift in the daily total emission by $\approx$ $(@sprintf("%.3f", mean(emissions_meat[!, :total]) - mean(emissions_vegan[!, :total]))) kgCO2eq, which means that the vegan diet has reduced daily emissions by $(@sprintf("%.2f", (1 - (mean(emissions_vegan[!, :total]) / mean(emissions_meat[!, :total]))) * 100 ))%
"""

# ╔═╡ c760edd0-8452-11eb-318b-9de3fd9409ae
begin
	@df emissions_vegan density(:total, fill=(0, .5, :green), label="vegan diet (total)", xlabel="kgCO2eq", ylabel="Density", title="Density plot of the daily total emissions", legend=:right)
	@df emissions_meat density!(:total, fill=(0, .5, :red), label="meat diet (total)")
end

# ╔═╡ 3ce10e94-8455-11eb-0083-3dea8a3ebc13
md"""
Total **annual** difference in emissions would amount to $\approx$ $(@sprintf("%.2f", sum(emissions_meat[!, :total]) - sum(emissions_vegan[!, :total]))) kgCO2eq. Implying that the switching to a vegan diet would allow one to reduce their carbon footprint by a considerable amount.
"""

# ╔═╡ Cell order:
# ╟─8ae7009a-73c4-11eb-0374-25c172bd827e
# ╟─ae828cb2-86a8-11eb-2862-6137ecb692a5
# ╟─94e65102-73c4-11eb-3cb4-81736a39e596
# ╟─054ae36c-52cb-11eb-25aa-31355bbed6de
# ╠═b4a152f0-4d4f-11eb-106b-b58e9f1495a9
# ╟─69f1de08-7e7f-11eb-1df1-c792e5e3ec57
# ╠═cedb71ac-52b9-11eb-19e7-9f433ffb4f14
# ╟─b2b598f8-4d3f-11eb-310d-7740ecc9d222
# ╟─0fcd983e-52b7-11eb-2c1f-13d00c8b4c43
# ╟─1fc15990-4d41-11eb-0f5f-c309cf01fdfa
# ╟─329e738a-52ba-11eb-22dd-fbfe2de89bb1
# ╟─e8574808-4d49-11eb-3515-2d66aadee9f2
# ╟─83af9228-6353-11eb-0e5b-4550ac55ca4f
# ╟─fb596dc6-4d41-11eb-1dbd-6707e4fa7778
# ╠═227d45a0-4d45-11eb-0cca-af99bc390097
# ╟─d4764dc0-7e81-11eb-29da-adbfa04c613b
# ╠═cfd60bf8-4d43-11eb-00b7-bd162061b954
# ╟─c25bfd94-7f7e-11eb-32ff-6fb869cd3b43
# ╠═5e3ae372-4d4a-11eb-3e76-e7b1545f3759
# ╟─cccb00f0-4d46-11eb-027b-ab6e07ce3ce5
# ╟─42eb4b3e-52ba-11eb-2178-11e1d2a887af
# ╟─cd98af32-4d4b-11eb-2ffb-edbe9a3c069b
# ╟─04b51758-52b7-11eb-10f9-f5be66cf0dec
# ╟─66d55490-7f7c-11eb-2d2d-77f9b4f7b184
# ╟─0442fbb8-52c0-11eb-06ea-01e68e330d5d
# ╠═3b2050da-52c1-11eb-3b89-1d5b6eb2cf40
# ╟─52ee864c-8445-11eb-15b0-47a0f97b6fec
# ╟─5fbcb6e6-52ca-11eb-3e8c-1bb7495dc15d
# ╟─1b612ec2-52c1-11eb-22aa-3b406bd64623
# ╟─2b0d264c-7f7f-11eb-2bf6-1119de8bbe96
# ╟─0a38c120-52c6-11eb-2ec5-e7780b3e11ec
# ╟─f5225d7a-5846-11eb-1497-c5d439899e6b
# ╟─8aa42c6e-6354-11eb-3c43-cb16327595c2
# ╟─9388aa8a-52c9-11eb-0dd8-3184bcfb93b2
# ╟─ec388b4a-52ca-11eb-097d-6760de18dd0e
# ╟─34baf426-7f7f-11eb-0cf0-bb0d1a7c28fd
# ╠═49f027da-5dce-11eb-3fff-0fd590112019
# ╠═672fef94-6351-11eb-0af1-652d5992e129
# ╟─18787dee-8446-11eb-2b9d-9967d7fe6d5c
# ╠═49571046-68c2-11eb-071e-2709f8e40e48
# ╟─e0ad3a7e-8447-11eb-2df2-3d52fffaab6b
# ╟─2c63765e-68c3-11eb-317c-d1603846ca9c
# ╟─7bb8f0e4-8448-11eb-2bd5-e9f94078860e
# ╟─04badb38-8448-11eb-2750-fde9b58547e4
# ╟─5114761e-84d0-11eb-094e-fde0d465d19e
# ╠═f9d0182e-8450-11eb-3f42-3df1cf54cf96
# ╠═521ebdb6-68c5-11eb-3bb2-8926b33ec780
# ╟─081ee4fc-84f4-11eb-3bad-a1e680d897b3
# ╟─2af54294-8451-11eb-29b9-dd400f6ceb74
# ╟─f0ecfbb6-84f3-11eb-0b02-27ffea69c7ca
# ╟─751bb036-844e-11eb-035b-6d62fe25bfce
# ╟─b185179e-8451-11eb-1877-593c6b4be750
# ╟─4d7c796a-84f4-11eb-19cf-dfd729ac8b98
# ╟─5b1d34d4-8451-11eb-15b5-1d45b1b3cb01
# ╟─2245ae6e-84f5-11eb-0bc9-61f05b3d6935
# ╟─b7a631d2-8454-11eb-3ff7-5b02d14ce2b9
# ╟─e6423e30-84f6-11eb-0c07-cdae8e894eb0
# ╟─c760edd0-8452-11eb-318b-9de3fd9409ae
# ╟─3ce10e94-8455-11eb-0083-3dea8a3ebc13

max_stars_repo_name: quantumbrake/ghg-dashboard

max_issues_repo_name: quantumbrake/ghg-dashboard

max_forks_repo_name: quantumbrake/ghg-dashboard


text:
module grids

export Grid,createFVgrid, createAdvecDiffOperator

type Grid
   lft::Array{Float64,1}
   ctr::Array{Float64,1}
   rgt::Array{Float64,1}
   BC::Array{Int64,1}
end

function createDifferentiationMatrix(vgrid::Array{Float64,1})
   Nv = length(vgrid)
   for i in 1:Nv
     ddv[i,2:end-1] = 1.0/(vgrid[3:end]-vgrid[1:end-2])
     ddv[i,1] = 1.0/(vgrid[2]-vgrid[1])
     ddv[i,end] = 1.0/(vgrid[end]-vgrid[end-1])
   end
end

function createFVgrid(Nv::Int64,v0::Float64,vf::Float64,BCs::Array{Int64,1})
   leftFaces = Float64[]
   centerPts = Float64[]
   rightFaces = Float64[]
   dv = (vf-v0)/Nv
   for i in 1:Nv
      push!(leftFaces, (i-1)*dv)
   end
   rightFaces = leftFaces[2:end]
   push!(rightFaces,leftFaces[end] + (leftFaces[end]-leftFaces[end-1]))

   centerPts = 0.5*( leftFaces[1:end] + rightFaces[1:end] )

   return Grid(leftFaces,centerPts,rightFaces,BCs)
end

function createAdvecDiffOperator(grid::Grid,jacobian::Function,advection::Function,diffusion::Function,boundaryVals::Array{Float64,1},source::Array{Float64,1})

   N = length(grid.ctr)
   a = zeros(Float64,N)
   b = zeros(Float64,N)
   c = zeros(Float64,N)
   operator = spzeros(N,N)

   # See ../docs/operator.pdf for description of this
   # Interior points
   denom = jacobian(grid.ctr[2:end-1]).*(grid.rgt[2:end-1]-grid.lft[2:end-1])
   A_left = jacobian(grid.lft[2:end-1]).*advection(grid.lft[2:end-1])
   A_right = jacobian(grid.rgt[2:end-1]).*advection(grid.rgt[2:end-1])
   D_left = (jacobian(grid.lft[2:end-1]).*diffusion(grid.lft[2:end-1]))./(grid.ctr[2:end-1] - grid.ctr[1:end-2])
   D_right = (jacobian(grid.rgt[2:end-1]).*diffusion(grid.rgt[2:end-1]))./(grid.ctr[3:end] - grid.ctr[2:end-1])

   a[1:end-2] = (-0.5*A_left + D_left)./denom
   b[2:end-1] = (0.5*A_right - 0.5*A_left - D_right - D_left)./denom
   c[3:end] = (0.5*A_right + D_right)./denom

   # i=1 boundary condition
   if grid.BC[1] == 0
      # Dirichlet boundary conditions
      scaleFactor = b[2]
      b[1] = scaleFactor
      source[1] = boundaryVals[1]*scaleFactor
   elseif grid.BC[1] == 1
      # Flux-specified boundary
      denom = jacobian(grid.ctr[1])*(grid.rgt[1]-grid.lft[1])
      b[1] = (0.5*jacobian(grid.rgt[1]).*advection(grid.rgt[1]) - (jacobian(grid.rgt[1]).*diffusion(grid.rgt[1]))./(grid.ctr[2] - grid.ctr[1]) )/denom
      c[2] = (0.5*jacobian(grid.rgt[1]).*advection(grid.rgt[1]) + (jacobian(grid.rgt[1]).*diffusion(grid.rgt[1]))./(grid.ctr[2] - grid.ctr[1]) )/denom
      source[1] = source[1] + jacobian(grid.lft[1])*boundaryVals[1] / (jacobian(grid.ctr[1])*(grid.rgt[1]-grid.lft[1]))
   else
         error("Invalid boundary condition for i = 1")
   end

   # i=N boundary condition
   if grid.BC[2] == 0
      # Dirichlet boundary conditions
      scaleFactor = b[N-1]
      b[N] = scaleFactor
      source[N] = boundaryVals[2]*scaleFactor
   elseif grid.BC[2] == 1
      # Flux-specified boundary
      denom = jacobian(grid.ctr[N])*(grid.rgt[N]-grid.lft[N])
      a[N-1] = (-0.5*jacobian(grid.lft[N]).*advection(grid.lft[N]) + (jacobian(grid.lft[N]).*diffusion(grid.lft[N]))./(grid.ctr[N] - grid.ctr[N-1]) )/denom
      b[N] = (- 0.5*jacobian(grid.lft[N]).*advection(grid.lft[N]) - (jacobian(grid.lft[1]).*diffusion(grid.lft[1]))./(grid.ctr[N] - grid.ctr[N-1]) )/denom
      source[N] = source[N] - jacobian(grid.rgt[N])*boundaryVals[2] / (jacobian(grid.ctr[N])*(grid.rgt[N]-grid.lft[N]))
   else
         error("Invalid boundary condition for i = N")
   end

   for icol in 2:N-1
      operator[icol-1:icol+1,icol] = [a[icol],b[icol],c[icol]]
   end
   operator[1,1] = b[1]
   operator[1,2] = c[2]
   operator[N,N-1] = a[N-1]
   operator[N,N] = b[N]

   return operator

end

end

max_stars_repo_name: gjwilkie/PlasmaTools

max_issues_repo_name: gjwilkie/PlasmaTools

max_forks_repo_name: gjwilkie/PlasmaTools


text:
"A `HyperRectangle` is the cartesian product of intervals."
abstract type HyperRectangle{T} <: ProductDomain{T} end

convert(::Type{HyperRectangle}, d::ProductDomain) =
	ProductDomain(map(t->convert(AbstractInterval, t), components(d)))

boundingbox(d::HyperRectangle) = d

"Compute all corners of the hyperrectangle."
function corners(d::HyperRectangle)
	left = leftendpoint(d)
	right = rightendpoint(d)
    N = length(left)
    corners = [similar(point_in_domain(d)) for i in 1:2^N]
    # All possible permutations of the corners
    for i=1:2^length(left)
        for j=1:N
            corners[i][j] = ((i>>(j-1))%2==0) ? left[j] : right[j]
        end
    end
    [convert(eltype(d), p) for p in corners]
end

# map the interval [a,b] to a cube defined by c (bottom-left) and d (top-right)
cube_face_map(a::Number, b::Number, c::SVector{2}, d::SVector{2}) = AffineMap((d-c)/(b-a), c - (d-c)/(b-a)*a)
function cube_face_map(a::Number, b::Number, c::Vector, d::Vector)
	@assert length(c) == length(d) == 2
	AffineMap((d-c)/(b-a), c - (d-c)/(b-a)*a)
end

# map the cube defined by a and b, to the cube defined by c and d,
# where the dimension of c and d is one larger, and one of the coordinates (dim) is fixed to dimval.
function cube_face_map(a::SVector{M}, b::SVector{M}, c::SVector{N}, d::SVector{N}, dim, dimval) where {N,M}
	@assert N == M+1
	T = promote_type(eltype(a),eltype(c))
	A = MMatrix{N,M,T}(undef)
	B = MVector{N,T}(undef)
	fill!(A, 0)
	fill!(B, 0)
	B[dim] = dimval
	for m = 1:dim-1
		# scalar map along the dimension "m"
		mapdim = interval_map(a[m], b[m], c[m], d[m])
		A[m,m] = mapdim.A
		B[m] = mapdim.b
	end
	for m = dim+1:N
		mapdim = interval_map(a[m-1], b[m-1], c[m], d[m])
		A[m,m-1] = mapdim.A
		B[m] = mapdim.b
	end
	AffineMap(SMatrix{N,M}(A), SVector{N}(B))
end

function cube_face_map(a::Vector, b::Vector, c::Vector, d::Vector, dim, dimval)
	M = length(a)
	N = length(c)
	@assert length(a)==length(b)
	@assert length(c)==length(d)
	@assert N == M+1
	T = promote_type(eltype(a),eltype(c))
	A = Matrix{T}(undef, N, M)
	B = Vector{T}(undef, N)
	fill!(A, 0)
	fill!(B, 0)
	B[dim] = dimval
	for m = 1:dim-1
		# scalar map along the dimension "m"
		mapdim = interval_map(a[m], b[m], c[m], d[m])
		A[m,m] = mapdim.A
		B[m] = mapdim.b
	end
	for m = dim+1:N
		mapdim = interval_map(a[m-1], b[m-1], c[m], d[m])
		A[m,m-1] = mapdim.A
		B[m] = mapdim.b
	end
	AffineMap(A, B)
end

# The boundary of a rectangle is a collection of mapped lower-dimensional rectangles.
# Dimension 2 is a special case, because the lower dimension is 1 where we use
# scalars instead of vectors
function boundary(d::HyperRectangle{SVector{2,T}}) where {T}
	left = leftendpoint(d)
	right = rightendpoint(d)
	x1 = left[1]; y1 = left[2]; x2 = right[1]; y2 = right[2]
	d_unit = UnitInterval{T}()
	maps = [
		cube_face_map(zero(T), one(T), SVector(x1,y1), SVector(x2,y1)),
		cube_face_map(zero(T), one(T), SVector(x2,y1), SVector(x2,y2)),
		cube_face_map(zero(T), one(T), SVector(x2,y2), SVector(x1,y2)),
		cube_face_map(zero(T), one(T), SVector(x1,y2), SVector(x1,y1))
	]
	faces = map(m -> ParametricDomain(m, d_unit), maps)
	UnionDomain(faces)
end

function boundary(d::HyperRectangle{SVector{N,T}}) where {N,T}
	left2 = leftendpoint(d)
	right2 = rightendpoint(d)
	d_unit = UnitCube{SVector{N-1,T}}()
	left1 = leftendpoint(d_unit)
	right1 = rightendpoint(d_unit)

	map1 = cube_face_map(left1, right1, left2, right2, 1, left2[1])
	MAP = typeof(map1)
	maps = MAP[]
	for dim in 1:N
		push!(maps, cube_face_map(left1, right1, left2, right2, dim, left2[dim]))
		push!(maps, cube_face_map(left1, right1, left2, right2, dim, right2[dim]))
	end
	faces = map(m -> ParametricDomain(m, d_unit), maps)
	UnionDomain(faces)
end

function boundary(d::HyperRectangle{Vector{T}}) where {T}
	if dimension(d) == 2
		left = leftendpoint(d)
		right = rightendpoint(d)
		x1 = left[1]; y1 = left[2]; x2 = right[1]; y2 = right[2]
		d_unit = UnitInterval{T}()
		maps = [
			cube_face_map(zero(T), one(T), [x1,y1], [x2,y1]),
			cube_face_map(zero(T), one(T), [x2,y1], [x2,y2]),
			cube_face_map(zero(T), one(T), [x2,y2], [x1,y2]),
			cube_face_map(zero(T), one(T), [x1,y2], [x1,y1])
		]
	else
		left2 = leftendpoint(d)
		right2 = rightendpoint(d)
		d_unit = UnitCube(dimension(d)-1)
		left1 = leftendpoint(d_unit)
		right1 = rightendpoint(d_unit)

		map1 = cube_face_map(left1, right1, left2, right2, 1, left2[1])
		MAP = typeof(map1)
		maps = MAP[]
		for dim in 1:dimension(d)
			push!(maps, cube_face_map(left1, right1, left2, right2, dim, left2[dim]))
			push!(maps, cube_face_map(left1, right1, left2, right2, dim, right2[dim]))
		end
	end
	faces = map(m -> ParametricDomain(m, d_unit), maps)
	UnionDomain(faces)
end

"A `Cube` is a hyperrectangle with equal side lengths in each dimension."
abstract type Cube{T} <: HyperRectangle{T} end

"A cube in a fixed N-dimensional Euclidean space."
const EuclideanCube{N,T} = Cube{SVector{N,T}}

"A cube with vector elements of variable length."
const VectorCube{T} = Cube{Vector{T}}

# This will cause a warning if vectors of different length are used with cubes
iscompatiblepair(x::AbstractVector, d::VectorCube) = length(x) == dimension(d)

"The unit cube is the domain `[0,1]^d`."
abstract type UnitCube{T} <: Cube{T} end

component(d::UnitCube, i::Int) =
    (1 <= i <= dimension(d) || throw(BoundsError); UnitInterval{numtype(d)}())

volume(d::UnitCube) = 1

"A unit cube that is specified by the element type `T`."
struct StaticUnitCube{T} <: UnitCube{T}
end

StaticUnitCube() = StaticUnitCube{SVector{3,Float64}}()
StaticUnitCube(::Val{N}) where {N} = StaticUnitCube{SVector{N,Float64}}()

StaticUnitCube{T}(n::Int) where {T} =
    (@assert n == euclideandimension(T); StaticUnitCube{T}())
StaticUnitCube{T}(::Val{N}) where {N,T} =
    (@assert N == euclideandimension(T); StaticUnitCube{T}())

similardomain(d::StaticUnitCube, ::Type{T}) where {T<:StaticTypes} =
    StaticUnitCube{T}()
similardomain(d::StaticUnitCube, ::Type{T}) where {T} =
    DynamicUnitCube{T}(dimension(d))

components(d::StaticUnitCube{SVector{N,T}}) where {N,T} =
    ntuple(x->UnitInterval{T}(), Val(N))

"The unit cube in a fixed N-dimensional space."
const EuclideanUnitCube{N,T} = StaticUnitCube{SVector{N,T}}

EuclideanUnitCube{N}() where {N} = EuclideanUnitCube{N,Float64}()

const UnitSquare{T} = EuclideanUnitCube{2,T}

"A unit cube whose dimension is specified by a field."
struct DynamicUnitCube{T} <: UnitCube{T}
    dimension   ::  Int

    DynamicUnitCube{T}(n::Int) where {T} = new(n)
    DynamicUnitCube{T}(n::Int) where {T<:StaticTypes} =
        (@assert n == euclideandimension(T); new(n))
end

DynamicUnitCube(n::Int) = DynamicUnitCube{Vector{Float64}}(n)

dimension(d::DynamicUnitCube) = d.dimension

components(d::DynamicUnitCube) = map(x->UnitInterval{numtype(d)}(), 1:dimension(d))

similardomain(d::DynamicUnitCube, ::Type{T}) where {T} =
    DynamicUnitCube{T}(d.dimension)
similardomain(d::DynamicUnitCube, ::Type{T}) where {T <: StaticTypes} =
    StaticUnitCube{T}()

"The unit cube with vector elements of a given dimension."
const VectorUnitCube{T} = DynamicUnitCube{Vector{T}}

VectorUnitCube(n::Int = 3) = VectorUnitCube{Float64}(n)
VectorUnitSquare() = VectorUnitCube(2)

UnitCube(n::Int) = DynamicUnitCube(n)
UnitCube(::Val{N} = Val(3)) where {N} = EuclideanUnitCube{N}()

UnitCube{T}(n::Int) where {T <: StaticTypes} = StaticUnitCube{T}(n)
UnitCube{T}(::Val{N}) where {N,T} = StaticUnitCube{T}(Val(N))
UnitCube{T}() where {T <: StaticTypes} = StaticUnitCube{T}()
UnitCube{T}(n::Int) where {T} = DynamicUnitCube{T}(n)

UnitCube(domains::UnitInterval...) = UnitCube(domains)
UnitCube(domains::NTuple{N,UnitInterval{T}}) where {N,T} =
    UnitCube{SVector{N,T}}(domains)
UnitCube(domains::SVector{N,UnitInterval{T}}) where {N,T} =
    UnitCube{SVector{N,T}}(domains)

UnitCube{T}(domains::UnitInterval...) where {T} = UnitCube{T}(domains)
UnitCube{T}(domain::NTuple{N,<:UnitInterval}) where {N,T<:SVector{N}} =
    StaticUnitCube{T}()
UnitCube{T}(domain::SVector{N,<:UnitInterval}) where {N,T<:SVector{N}} =
    StaticUnitCube{T}()

# Constructor: careful about ambiguities with FixedInterval arguments below
ProductDomain(domains::UnitInterval...) = UnitCube(domains...)
ProductDomain(domains::NTuple{N,<:UnitInterval}) where {N} = UnitCube(domains)
ProductDomain(domains::SVector{N,<:UnitInterval}) where {N} = UnitCube(domains)
ProductDomain(domains::AbstractVector{<:UnitInterval{T}}) where {T} =
    VectorUnitCube{T}(length(domains))
ProductDomain{T}(domains::UnitInterval...) where {N,S,T<:SVector{N,S}} =
	UnitCube{T}(domains...)
ProductDomain{T}(domains::NTuple{N,<:UnitInterval}) where {N,S,T<:SVector{N,S}} =
	UnitCube{T}(domains)
ProductDomain{T}(domains::SVector{N,<:UnitInterval}) where {N,S,T<:SVector{N,S}} =
	UnitCube{T}(domains)
ProductDomain{T}(domains::AbstractVector{<:UnitInterval}) where {S,T<:Vector{S}} =
	VectorUnitCube{S}(length(domains))

## Display:
show(io::IO, d::EuclideanUnitCube{3,Float64}) = print(io, "UnitCube()")
show(io::IO, d::EuclideanUnitCube{N,Float64}) where {N} = print(io, "UnitCube(Val($(N)))")
show(io::IO, d::UnitSquare{Float64}) = print(io, "UnitSquare()")
show(io::IO, d::UnitSquare{T}) where {T} = print(io, "UnitSquare{$(T)}()")
show(io::IO, d::VectorUnitCube{Float64}) = print(io, "UnitCube($(dimension(d)))")

# set the display stencils to [] to opt-out of composite display for the types above
Display.displaystencil(d::EuclideanUnitCube{N,Float64}) where {N} = []
Display.displaystencil(d::UnitSquare) = []
Display.displaystencil(d::VectorUnitCube{Float64}) = []
Display.object_parentheses(d::EuclideanUnitCube{N,Float64}) where {N} = false
Display.object_parentheses(d::UnitSquare) = false
Display.object_parentheses(d::VectorUnitCube{Float64}) = false

"An N-dimensional rectangle is the cartesian product of closed intervals."
struct Rectangle{T} <: HyperRectangle{T}
    a   ::  T
    b   ::  T

    function Rectangle{T}(a::S,b::S) where {S,T}
        @assert length(a)==length(b)
        new(a,b)
    end
end

dimension(d::Rectangle) = length(d.a)
component(d::Rectangle, i::Int) = ClosedInterval(d.a[i],d.b[i])
components(d::Rectangle) = map(ClosedInterval, d.a, d.b)

Rectangle(a, b) = Rectangle(promote(a,b)...)
Rectangle(a::T, b::T) where {T} = Rectangle{T}(a, b)
Rectangle(a::NTuple{N,T}, b::NTuple{N,T}) where {N,T} =
    Rectangle(SVector{N,T}(a), SVector{N,T}(b))
Rectangle(a::T, b::T) where {T<:Number} =
	error("Rectangles have to be constructed from vectors or tuples, not numbers.")

Rectangle(domains::Tuple) = Rectangle(domains...)
Rectangle(domains::ClosedInterval...) = Rectangle(promote_domains(domains)...)
Rectangle(domains::ClosedInterval{T}...) where {T} =
    Rectangle(map(leftendpoint, domains), map(rightendpoint, domains))
Rectangle(domains::AbstractVector{<:ClosedInterval}) =
    Rectangle(map(leftendpoint, domains), map(rightendpoint, domains))
Rectangle(domains::Domain...) =
    error("The Rectangle constructor expects two points or a list of intervals (closed).")

Rectangle{T}(domains::Tuple) where {T} = Rectangle{T}(domains...)
Rectangle{T}(domains::ClosedInterval...) where {T} =
	Rectangle{T}(map(leftendpoint, domains), map(rightendpoint, domains))
Rectangle{T}(domains::AbstractVector{<:ClosedInterval}) where {T} =
    Rectangle{T}(map(leftendpoint, domains), map(rightendpoint, domains))
Rectangle{T}(domains::Domain...) where {T} =
    error("The Rectangle constructor expects two points or a list of intervals (closed).")

ProductDomain(domains::ClosedInterval...) = Rectangle(domains...)
ProductDomain(domains::AbstractVector{<:ClosedInterval}) =
    Rectangle(map(leftendpoint, domains), map(rightendpoint, domains))
ProductDomain{T}(domains::ClosedInterval...) where {T} = Rectangle{T}(domains...)
ProductDomain{T}(domains::AbstractVector{<:ClosedInterval}) where {T} =
    Rectangle{T}(map(leftendpoint, domains), map(rightendpoint, domains))

"The N-fold cartesian product of a fixed interval."
struct FixedIntervalProduct{N,T,D} <: Cube{SVector{N,T}}
end

component(d::FixedIntervalProduct{N,T,D}, i::Int) where {N,T,D} =
    (1 <= i <= dimension(d) || throw(BoundsError); D())
components(d::FixedIntervalProduct{N,T,D}) where {N,T,D} =
    ntuple(x->D(), Val(N))

volume(d::FixedIntervalProduct{N,T,D}) where {N,T,D} = volume(D())^N

FixedIntervalProduct(domains::NTuple{N,D}) where {N,D <: FixedInterval} =
	FixedIntervalProduct{N,eltype(D),D}()
FixedIntervalProduct(domains::SVector{N,D}) where {N,D <: FixedInterval} =
	FixedIntervalProduct{N,eltype(D),D}()

const ChebyshevProductDomain{N,T} = FixedIntervalProduct{N,T,ChebyshevInterval{T}}
ChebyshevProductDomain(::Val{N}) where {N} = ChebyshevProductDomain{N}()
ChebyshevProductDomain{N}() where {N} = ChebyshevProductDomain{N,Float64}()

ProductDomain(domains::D...) where {D <: FixedInterval} =
	FixedIntervalProduct(domains)
ProductDomain(domains::NTuple{N,D}) where {N,D <: FixedInterval} =
	FixedIntervalProduct(domains)
ProductDomain(domains::SVector{N,<:FixedInterval}) where {N} =
	FixedIntervalProduct(domains)
ProductDomain{T}(domains::D...) where {N,S,T<:SVector{N,S},D <: FixedInterval} =
	FixedIntervalProduct(convert.(Ref(Domain{S}), domains))
ProductDomain{T}(domains::NTuple{N,D}) where {N,S,T<:SVector{N,S},D <: FixedInterval} =
	FixedIntervalProduct(convert.(Ref(Domain{S}), domains))
ProductDomain{T}(domains::SVector{N,<:FixedInterval}) where {N,S,T<:SVector{N}} =
	FixedIntervalProduct(domains)


text:
export iauC2teqx
"""
**  Assemble the celestial to terrestrial matrix from equinox-based
**  components (the celestial-to-true matrix, the Greenwich Apparent
**  Sidereal Time and the polar motion matrix).
**
**  This function is part of the International Astronomical Union's
**  SOFA (Standards Of Fundamental Astronomy) software collection.
**
**  Status:  support function.
**
**  Given:
**     rbpn   double[3][3]  celestial-to-true matrix
**     gst    double        Greenwich (apparent) Sidereal Time (radians)
**     rpom   double[3][3]  polar-motion matrix
**
**  Returned:
**     rc2t   double[3][3]  celestial-to-terrestrial matrix (Note 2)
**
**  Notes:
**
**  1) This function constructs the rotation matrix that transforms
**     vectors in the celestial system into vectors in the terrestrial
**     system.  It does so starting from precomputed components, namely
**     the matrix which rotates from celestial coordinates to the
**     true equator and equinox of date, the Greenwich Apparent Sidereal
**     Time and the polar motion matrix.  One use of the present function
**     is when generating a series of celestial-to-terrestrial matrices
**     where only the Sidereal Time changes, avoiding the considerable
**     overhead of recomputing the precession-nutation more often than
**     necessary to achieve given accuracy objectives.
**
**  2) The relationship between the arguments is as follows:
**
**        [TRS] = rpom * R_3(gst) * rbpn * [CRS]
**
**              = rc2t * [CRS]
**
**     where [CRS] is a vector in the Geocentric Celestial Reference
**     System and [TRS] is a vector in the International Terrestrial
**     Reference System (see IERS Conventions 2003).
**
**  Called:
**     iauCr        copy r-matrix
**     iauRz        rotate around Z-axis
**     iauRxr       product of two r-matrices
**
**  Reference:
**
**     McCarthy, D. D., Petit, G. (eds.), IERS Conventions (2003),
**     IERS Technical Note No. 32, BKG (2004)
**
**  This revision:  2013 August 24
**
**  SOFA release 2018-01-30
**
**  Copyright (C) 2018 IAU SOFA Board.  See notes at end.
"""

# void iauC2teqx(double rbpn[3][3], double gst, double rpom[3][3],
#                double rc2t[3][3])

function iauC2teqx(rbpn::AbstractMatrix{<:Real}, gst::Real, rpom::AbstractMatrix{<:Real})

   # Allocate return value
   rc2t = zeros(Float64, 3, 3)

   ccall((:iauC2teqx, libsofa_c), Cvoid,
         (Ptr{Cdouble}, Cdouble, Ptr{Cdouble},
         Ptr{Cdouble}),
         convert(Array{Float64, 2}, rbpn'), convert(Float64, gst),
         convert(Array{Float64, 2}, rpom'),
         rc2t)

   return SMatrix{3,3}(rc2t')
end


text:
using Base.Test

@testset "scripts" begin

noisepath = joinpath(Pkg.dir(),"ReferenceMicrocalFiles/ljh/20150707_C_chan13.noi")
ljhpath = joinpath(Pkg.dir(),"ReferenceMicrocalFiles/ljh/20150707_D_chan13.ljh")
preknowledgepath = joinpath(@__DIR__,"artifacts","pk_1x32_3072samples.preknowledge")

@test nothing==run(`julia ../scripts/benchmark.jl --runtime_s=3`)
@test nothing==run(`julia ../scripts/mattersimulator.jl --timeout=0 $ljhpath`)

# make_preknowledge python and mass
# if the enviroment variable POPE_NOMASS exists
# we skip make_preknowledge and instead copy required files
# from ReferenceMicrocalFiles
if !haskey(ENV,"POPE_NOMASS")
    @test nothing==run(`python ../scripts/make_preknowledge.py $ljhpath $noisepath artifacts --apply_filters --noprompt --quality_report --dont_popeonceafter --temp_out_dir=artifacts`)
else
    srcdir = joinpath(Pkg.dir(),"ReferenceMicrocalFiles","artifacts")
    cp(joinpath(srcdir,last(splitdir(preknowledgepath))), preknowledgepath)
    cp(joinpath(srcdir,"make_preknowledge_temp.hdf5"), joinpath("artifacts","make_preknowledge_temp.hdf5"))
    touch("artifacts/nomass") # add marker to indicate tests were run with nomass
end
@test nothing==run(`julia ../scripts/popeonce.jl $ljhpath $preknowledgepath artifacts/output.h5`)

end #testset


text:
# Use baremodule to shave off a few KB from the serialized `.ji` file
baremodule blaspp_jll
using Base
using Base: UUID
import JLLWrappers

JLLWrappers.@generate_main_file_header("blaspp")
JLLWrappers.@generate_main_file("blaspp", UUID("ac2d9471-9114-5691-9e37-f48642a6f9ea"))
end  # module blaspp_jll