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
792c195909ca5dfff5685305b6fa0aa16c3d1041
docs
952
# Public Interface Documentation of `LongwaveModePropagator.jl`'s exported structs and functions. **Contents** - [Basic Functions](@ref) - [Mode Finder](@ref) - [EigenAngle](@ref) - [Geophysics](@ref) - [Samplers](@ref) - [Emitters](@ref) - [Waveguides](@ref) - [IO](@ref) ### Basic Functions ```@docs propagate LMPParams ``` ### Mode Finder ```@docs findmodes PhysicalModeEquation setea IntegrationParams ``` ### EigenAngle ```@docs EigenAngle attenuation phasevelocity referencetoground ``` ### Geophysics ```@docs BField Species Ground GROUND waitprofile electroncollisionfrequency ioncollisionfrequency ``` ### Samplers ```@docs Sampler GroundSampler Fields Receiver ``` ### Emitters ```@docs Frequency Transmitter Dipole VerticalDipole HorizontalDipole inclination azimuth ``` ### Waveguides ```@docs HomogeneousWaveguide SegmentedWaveguide ``` ### IO ```@docs ExponentialInput TableInput BatchInput BasicOutput BatchOutput ```
LongwaveModePropagator
https://github.com/fgasdia/LongwaveModePropagator.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
1134
using Documenter, RayTracer makedocs( modules = [RayTracer], doctest = true, sitename = "RayTracer", authors = "Avik Pal", format = Documenter.HTML( prettyurls = get(ENV, "CI", nothing) == "true", assets = ["assets/raytracer.css"], ), pages = [ "Home" => "index.md", "Getting Started" => [ "Introduction to Rendering" => "getting_started/teapot_rendering.md", "Inverse Lighting" => "getting_started/inverse_lighting.md", "Optimizing using Optim.jl" => "getting_started/optim_compatibility.md", ], "API Documentation" => [ "General Utilities" => "api/utilities.md", "Differentiation" => "api/differentiation.md", "Scene Configuration" => "api/scene.md", "Renderers" => "api/renderers.md", "Optimization" => "api/optimization.md", "Acceleration Structures" => "api/accelerators.md", ], ], ) deploydocs( repo = "github.com/avik-pal/RayTracer.jl.git" )
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
4601
# # Inverse Lighting Tutorial # # In this tutorial we shall explore the inverse lighting problem. # Here, we shall try to reconstruct a target image by optimizing # the parameters of the light source (using gradients). using RayTracer, Images, Zygote, Flux, Statistics # ## Configuring the Scene # # Reduce the screen_size if the optimization is taking a bit long screen_size = (w = 300, h = 300) # Now we shall load the scene using [`load_obj`](@ref) function. For # this we need the [`obj`](https://en.wikipedia.org/wiki/Wavefront_.obj_file) # and [`mtl`](https://en.wikipedia.org/wiki/Wavefront_.obj_file#Material_template_library) # files. They can be downloaded using the following commands: # # ``` # wget https://raw.githubusercontent.com/tejank10/Duckietown.jl/master/src/meshes/tree.obj # wget https://raw.githubusercontent.com/tejank10/Duckietown.jl/master/src/meshes/tree.mtl # ``` scene = load_obj("./tree.obj") # Let us set up the [`Camera`](@ref). For a more detailed understanding of # the rendering process look into [Introduction to rendering using RayTracer.jl](@ref). cam = Camera( lookfrom = Vec3(0.0f0, 6.0f0, -10.0f0), lookat = Vec3(0.0f0, 2.0f0, 0.0f0), vup = Vec3(0.0f0, 1.0f0, 0.0f0), vfov = 45.0f0, focus = 0.5f0, width = screen_size.w, height = screen_size.h ) origin, direction = get_primary_rays(cam) # We should define a few convenience functions. Since we are going to calculate # the gradients only wrt to `light` we have it as an argument to the function. Having # `scene` as an additional parameters simply allows us to test our method for other # meshes without having to run `Zygote.refresh()` repeatedly. function render(light, scene) packed_image = raytrace(origin, direction, scene, light, origin, 2) array_image = reshape(hcat(packed_image.x, packed_image.y, packed_image.z), (screen_size.w, screen_size.h, 3, 1)) return array_image end showimg(img) = colorview(RGB, permutedims(img[:,:,:,1], (3,2,1))) # ## [Ground Truth Image](@id inv_light) # # For this tutorial we shall use the [`PointLight`](@ref) source. # We define the ground truth lighting source and the rendered image. We # will later assume that we have no information about this lighting # condition and try to reconstruct the image. light_gt = PointLight( color = Vec3(1.0f0, 1.0f0, 1.0f0), intensity = 20000.0f0, position = Vec3(1.0f0, 10.0f0, -50.0f0) ) target_img = render(light_gt, scene) # The presence of [`zeroonenorm`](@ref) is very important here. It rescales the # values in the image to 0 to 1. If we don't perform this step `Images` will # clamp the values while generating the image in RGB format. showimg(zeroonenorm(target_img)) # ```@raw html # <p align="center"> # <img width=300 height=300 src="../../assets/inv_light_original.png"> # </p> # ``` # ## Initial Guess of Lighting Parameters # # We shall make some arbitrary guess of the lighting parameters (intensity and # position) and try to get back the image in [Ground Truth Image](@ref inv_light) light_guess = PointLight( color = Vec3(1.0f0, 1.0f0, 1.0f0), intensity = 1.0f0, position = Vec3(-1.0f0, -10.0f0, -50.0f0) ) showimg(zeroonenorm(render(light_guess, scene))) # ```@raw html # <p align="center"> # <img width=300 height=300 src="../../assets/inv_light_initial.png"> # </p> # ``` # We shall store the images in `results_inv_lighting` directory mkpath("results_inv_lighting") save("./results_inv_lighting/inv_light_original.png", showimg(zeroonenorm(render(light_gt, scene)))) save("./results_inv_lighting/inv_light_initial.png", showimg(zeroonenorm(render(light_guess, scene)))) # ## Optimization Loop # # We will use the ADAM optimizer from Flux. (Try experimenting with other # optimizers as well). We can also use frameworks like Optim.jl for optimization. # We will show how to do it in a future tutorial opt = ADAM(1.0) for i in 1:401 loss, back_fn = Zygote._pullback(light_guess) do L sum((render(L, scene) .- target_img) .^ 2) end @show loss gs = back_fn(1.0f0) update!(opt, light_guess.intensity, gs[2].intensity) update!(opt, light_guess.position, gs[2].position) if i % 5 == 1 save("./results_inv_lighting/iteration_$i.png", showimg(zeroonenorm(render(light_guess, scene)))) end end # If we generate a `gif` for the optimization process it will look similar to this # ```@raw html # <p align="center"> # <img width=300 height=300 src="../../assets/inv_lighting.gif"> # </p> # ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
3932
# # Optimizing Scene Parameters using Optim.jl # # In this tutorial we will explore the exact same problem as demonstrated # in [Inverse Lighting Tutorial](@ref) but this time we will use the # Optimization Package [Optim.jl](https://julianlsolvers.github.io/Optim.jl/stable/). # I would recommend going through a few of the # [tutorials on Optim](https://julianlsolvers.github.io/Optim.jl/stable/#user/minimization/#_top) # before starting this one. # # If you have already read the previous tutorial, you can safely skip to # [Writing the Optimization Loop using Optim](@ref). The part previous to this # is same as the previous tutorial. using RayTracer, Images, Zygote, Flux, Statistics, Optim # ## Script for setting up the Scene screen_size = (w = 64, h = 64) scene = load_obj("./tree.obj") cam = Camera( Vec3(0.0f0, 6.0f0, -10.0f0), Vec3(0.0f0, 2.0f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 0.5f0, screen_size... ) origin, direction = get_primary_rays(cam) function render(light, scene) packed_image = raytrace(origin, direction, scene, light, origin, 2) array_image = reshape(hcat(packed_image.x, packed_image.y, packed_image.z), (screen_size.w, screen_size.h, 3, 1)) return array_image end showimg(img) = colorview(RGB, permutedims(img[:,:,:,1], (3,2,1))) light_gt = PointLight( Vec3(1.0f0, 1.0f0, 1.0f0), 20000.0f0, Vec3(1.0f0, 10.0f0, -50.0f0) ) target_img = render(light_gt, scene) showimg(zeroonenorm(render(light_gt, scene))) light_guess = PointLight( Vec3(1.0f0, 1.0f0, 1.0f0), 1.0f0, Vec3(-1.0f0, -10.0f0, -50.0f0) ) showimg(zeroonenorm(render(light_guess, scene))) # ## Writing the Optimization Loop using Optim # # Since, there is no direct support of Optim (unlike for Flux) in RayTracer # the interface might seem a bit ugly. This is mainly due to the way the # two optimization packages work. Flux allows inplace operation and ideally # even RayTracer prefers that. But Optim requires us to give the parameters # as an `AbstractArray`. # # Firstly, we shall extract the parameters, using the [`RayTracer.get_params`](@ref) # function, we want to optimize. initial_parameters = RayTracer.get_params(light_guess)[end-3:end] # Since the input to the `loss_function` is an abstract array we need to # convert it into a form that the RayTracer understands. For this we # shall use the [`RayTracer.set_params!`](@ref) function which will modify the # parameters inplace. # # In this function we simply compute the loss values and print it for our # reference function loss_function(θ::AbstractArray) light_optim = deepcopy(light_guess) RayTracer.set_params!(light_optim.intensity, θ[1:1]) RayTracer.set_params!(light_optim.position, θ[2:end]) loss = sum((render(light_optim, scene) .- target_img) .^ 2) @show loss return loss end # RayTracer uses Zygote's Reverse Mode AD for computing the derivatives. # However, the default in Optim is ForwardDiff. Hence, we need to override # that by giving our own gradient function. function ∇loss_function!(G, θ::AbstractArray) light_optim = deepcopy(light_guess) RayTracer.set_params!(light_optim.intensity, θ[1:1]) RayTracer.set_params!(light_optim.position, θ[2:end]) gs = gradient(light_optim) do L sum((render(L, scene) .- target_img) .^ 2) end G .= RayTracer.get_params(gs[1])[end-3:end] end # Now we simply call the `optimize` function with `LBFGS` optimizer. res = optimize(loss_function, ∇loss_function!, initial_parameters, LBFGS()) @show res.minimizer # It might be interesting to note that convergence using LBFGS was much faster (only # 252 iterations) compared to ADAM (401 iterations). # If we generate a `gif` for the optimization process it will look similar to this # ```@raw html # <p align="center"> # <img width=300 height=300 src="../../assets/inv_lighting_optim.gif"> # </p> # ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
2086
using RayTracer, Images, BenchmarkTools, ArgParse function render(scene, screen_size, gillum) cam = Camera( Vec3(0.5f0, 0.2f0, -0.5f0), Vec3(0.0f0, 0.1f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 1.0f0, screen_size... ) origin, direction = get_primary_rays(cam) light = PointLight( Vec3(1.0f0, 1.0f0, 1.0f0), 2.0f8, Vec3(10.0f0, 10.0f0, 5.0f0) ) image_packed = raytrace( origin, direction, scene, light, origin, gillum ) return zeroonenorm( reshape(hcat(image_packed.x, image_packed.y, image_packed.z), (3, screen_size...))) end function parse_commandline() s = ArgParseSettings() @add_arg_table s begin "--mesh_path", "-m" help = "path to the mesh being rendered" arg_type = String required = true "--global_illumination", "-g" help = "Activate global illumination (>= 2 for no)" arg_type = Int default = 2 end return parse_args(s) end function main() parsed_args = parse_commandline() println("Running Benchmarks for Mesh:\n 1. Path to the Mesh - $(parsed_args["mesh_path"])\n 2. Global Illumination - $(parsed_args["global_illumination"])") println("The benchmarking time involves the following:\n 1. Instantiating the Camera\n 2. Rendering\n 3. Reshaping and Normalizing the Image") for screen_size in [(32, 32), (64, 64), (128, 128), (512, 512), (1024, 1024)] @info "Screen Size --> $screen_size" scene = load_obj(parsed_args["mesh_path"]) print("Time without BVH --> ") @btime render($scene, $screen_size, $(parsed_args["global_illumination"])) bvh = BoundingVolumeHierarchy(scene) print("Time with BVH --> ") @btime render($bvh, $screen_size, $(parsed_args["global_illumination"])) end println("Benchmarking Completed") end main()
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
4392
# # Introduction to rendering using RayTracer.jl # # In this example we will render the famous UTAH Teapot model. # We will go through the entire rendering API. We will load # an obj file for the scene. This needs to be downloaded manually. # # Run this code in your terminal to get the file: # `wget https://raw.githubusercontent.com/McNopper/OpenGL/master/Binaries/teapot.obj` # If you are using REPL mode you need the `ImageView.jl` package using RayTracer, Images #, ImageView # ## General Attributes of the Scene # # Specify the dimensions of the image we want to generate. # `screen_size` is never passed into the RayTracer directly so it # need not be a named tuple. screen_size = (w = 256, h = 256) # Load the teapot object from an `obj` file. We can also specify # the scene using primitive objects directly but that becomes a # bit involved when there are complicated objects in the scene. scene = load_obj("teapot.obj") # We shall define a convenience function for rendering and saving # the images. # For understanding the parameters passed to the individual functions # look into the documentations of [`get_primary_rays`](@ref), [`raytrace`](@ref) # and [`get_image`](@ref) function generate_render_and_save(cam, light, filename) #src # Get the primary rays for the camera origin, direction = get_primary_rays(cam) #src # Render the scene color = raytrace(origin, direction, scene, light, origin, 2) #src # This will reshape `color` into the proper dimensions and return #src # an RGB image img = get_image(color, screen_size...) #src # Display the image #src # For REPL mode change this to `imshow(img)` display(img) #src # Save the generated image save(filename, img) end # ## Understanding the Light and Camera API # # ### DistantLight # # In this example we will be using the [`DistantLight`](@ref). This king of lighting # is useful when we want to render a scene in which all parts of the scene # receive the same intensity of light. # # For the DistantLight we need to provide three attributes: # * Color - Color of the Light Rays. Must be a Vec3 Object # * Intensity - Intensity of the Light # * Direction - The direction of light rays. Again this needs to be a Vec3 Object # # ### Camera # # We use a perspective view [`Camera`](@ref) Model in RayTracer. Let us look into the # arguments we need to pass into the Camera constructor. # # * LookFrom - The position of the Camera # * LookAt - The point in 3D space where the Camera is pointing # * vup - The UP vector of the world (typically Vec3(0.0, 1.0, 0.0), i.e. the y-axis) # * vfov - Field of View of the Camera # * Focus - The focal length of the Camera # * Width - Width of the output image # * Height - Height of the output image # ## Rendering Different Views of the Teapot # # Now that we know what each argument means let us render the teapot # # ### TOP VIEW Render light = DistantLight( Vec3(1.0f0), 100.0f0, Vec3(0.0f0, 1.0f0, 0.0f0) ) cam = Camera( Vec3(1.0f0, 10.0f0, -1.0f0), Vec3(0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 1.0f0, screen_size... ) generate_render_and_save(cam, light, "teapot_top.jpg") # ```@raw html # <p align="center"> # <img width=256 height=256 src="../../assets/teapot_top.jpg"> # </p> # ``` # ### SIDE VIEW Render light = DistantLight( Vec3(1.0f0), 100.0f0, Vec3(1.0f0, 1.0f0, -1.0f0) ) cam = Camera( Vec3(1.0f0, 2.0f0, -10.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 1.0f0, screen_size... ) generate_render_and_save(cam, light, "teapot_side.jpg") # ```@raw html # <p align="center"> # <img width=256 height=256 src="../../assets/teapot_side.jpg"> # </p> # ``` # ### FRONT VIEW Render light = DistantLight( Vec3(1.0f0), 100.0f0, Vec3(1.0f0, 1.0f0, 0.0f0) ) cam = Camera( Vec3(10.0f0, 2.0f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 1.0f0, screen_size... ) generate_render_and_save(cam, light, "teapot_front.jpg") # ```@raw html # <p align="center"> # <img width=256 height=256 src="../../assets/teapot_front.jpg"> # </p> # ``` # ## Next Steps # # * Try Rendering complex environments with RayTracer # * Look into the other examples in `examples/` # * Read about inverse rendering and see the examples on that
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
591
module RayTracer using Zygote, Flux, Images, Distributed, Statistics import Base.show using Compat import Compat.isnothing # Rendering Utilities include("utils.jl") include("light.jl") include("materials.jl") include("objects.jl") include("camera.jl") include("optimize.jl") # Acceleration Structures include("bvh.jl") # Renderers include("renderers/blinnphong.jl") include("renderers/rasterizer.jl") include("renderers/accelerated_raytracer.jl") # Image Utilities include("imutils.jl") # Differentiable Rendering include("gradients/zygote.jl") include("gradients/numerical.jl") end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
7469
export BoundingVolumeHierarchy """ AccelerationStructure Base Type for all Acceleration Structures. These can be used to speed up rendering by a significant amount. The main design behind an acceleration structure should be such that it can be used as a simple replacement for a vector of [`Object`](@ref)s. """ abstract type AccelerationStructure end """ BVHNode A node in the graph created from the scene list using [`BoundingVolumeHierarchy`](@ref). ### Fields: * `x_min` - Minimum x-value for the bounding box * `x_max` - Maximum x-value for the bounding box * `y_min` - Minimum y-value for the bounding box * `y_max` - Maximum y-value for the bounding box * `z_min` - Minimum z-value for the bounding box * `z_max` - Maximum z-value for the bounding box * `index_start` - Starting triangle in the scene list * `index_end` - Last triangle in the scene list * `left_child` - Can be `nothing` or another [`BVHNode`](@ref) * `right_child` - Can be `nothing` or another [`BVHNode`](@ref) """ struct BVHNode{T} x_min::T x_max::T y_min::T y_max::T z_min::T z_max::T index_start::Int index_end::Int left_child::Union{Nothing, BVHNode} right_child::Union{Nothing, BVHNode} end """ BoundingVolumeHierarchy An [`AccelerationStructure`](@ref) which constructs bounding boxes around groups of triangles to speed up intersection checking. A detailed description of ths technique is present [here](https://www.scratchapixel.com/lessons/advanced-rendering/introduction-acceleration-structure/bounding-volume-hierarchy-BVH-part1). ### Fields: * `scene_list` - The scene list passed into the BVH constructor but in sorted order * `root_node` - Root [`BVHNode`](@ref) ### Constructors: * `BoundingVolumeHierarchy(scene::Vector)` """ struct BoundingVolumeHierarchy{T, S} <: AccelerationStructure scene_list::Vector{T} root_node::BVHNode{S} end const BVH = BoundingVolumeHierarchy function BoundingVolumeHierarchy(scene::Vector) x_min, x_max = extrema(hcat([[s.v1.x[], s.v2.x[], s.v3.x[]] for s in scene]...)) y_min, y_max = extrema(hcat([[s.v1.y[], s.v2.y[], s.v3.y[]] for s in scene]...)) z_min, z_max = extrema(hcat([[s.v1.z[], s.v2.z[], s.v3.z[]] for s in scene]...)) longest_direction = getindex([:x, :y, :z], argmax([x_max - x_min, y_max - y_min, z_max - z_min])) centroids = map(t -> (t.v1 + t.v2 + t.v3) / 3, scene) centroid_dict = IdDict{eltype(scene), Vec3}() for (s, c) in zip(scene, centroids) centroid_dict[s] = c end scene = sort(scene, by = x -> getproperty(centroid_dict[x], longest_direction)[]) search_space = map(x -> getproperty(x, longest_direction)[], centroids) split_value = median(search_space) split_index = searchsortedfirst(search_space, split_value) if split_index - 1 == length(scene) || split_index == 1 bvhnode = BVHNode(x_min, x_max, y_min, y_max, z_min, z_max, 1, length(scene), nothing, nothing) else left_child, sc = BVHNode(scene[1:split_index - 1], 1, centroid_dict) scene[1:split_index - 1] .= sc right_child, sc = BVHNode(scene[split_index:end], split_index, centroid_dict) scene[split_index:end] .= sc bvhnode = BVHNode(x_min, x_max, y_min, y_max, z_min, z_max, 1, length(scene), left_child, right_child) end return BoundingVolumeHierarchy(scene, bvhnode) end function BVHNode(scene, index, centroid_dict) length(scene) == 0 && return (nothing, scene) x_min, x_max = extrema(hcat([[s.v1.x[], s.v2.x[], s.v3.x[]] for s in scene]...)) y_min, y_max = extrema(hcat([[s.v1.y[], s.v2.y[], s.v3.y[]] for s in scene]...)) z_min, z_max = extrema(hcat([[s.v1.z[], s.v2.z[], s.v3.z[]] for s in scene]...)) if length(scene) <= 100 return BVHNode(x_min, x_max, y_min, y_max, z_min, z_max, index, index + length(scene) -1, nothing, nothing), scene end longest_direction = getindex([:x, :y, :z], argmax([x_max - x_min, y_max - y_min, z_max - z_min])) scene = sort(scene, by = x -> getproperty(centroid_dict[x], longest_direction)[]) centroids = [centroid_dict[s] for s in scene] search_space = map(x -> getproperty(x, longest_direction)[], centroids) split_value = median(search_space) split_index = searchsortedfirst(search_space, split_value) if split_index - 1 == length(scene) || split_index == 1 return BVHNode(x_min, x_max, y_min, y_max, z_min, z_max, index, index + length(scene) - 1, nothing, nothing), scene end left_child, sc = BVHNode(scene[1:split_index - 1], index, centroid_dict) scene[1:split_index - 1] .= sc right_child, sc = BVHNode(scene[split_index:end], index + split_index - 1, centroid_dict) scene[split_index:end] .= sc bvhnode = BVHNode(x_min, x_max, y_min, y_max, z_min, z_max, index, index + length(scene) - 1, left_child, right_child) return bvhnode, scene end bvh_depth(bvh::BoundingVolumeHierarchy) = bvh_depth(bvh.root_node) bvh_depth(bvh::BVHNode) = 1 + max(bvh_depth(bvh.left_child), bvh_depth(bvh.right_child)) bvh_depth(::Nothing) = 0 isleafnode(bvh::BVHNode) = isnothing(bvh.left_child) && isnothing(bvh.right_child) function intersection_check(bvh::BVHNode, origin, direction) function check_intersection_ray(dir_x, dir_y, dir_z, ori_x, ori_y, ori_z) a, b = dir_x < 0 ? (bvh.x_max, bvh.x_min) : (bvh.x_min, bvh.x_max) tmin = (a - ori_x) / dir_x tmax = (b - ori_x) / dir_x a, b = dir_y < 0 ? (bvh.y_max, bvh.y_min) : (bvh.y_min, bvh.y_max) tymin = (a - ori_y) / dir_y tymax = (b - ori_y) / dir_y (tmin > tymax || tymin > tmax) && return false tmin = max(tmin, tymin) tmax = min(tmax, tymax) a, b = dir_z < 0 ? (bvh.z_max, bvh.z_min) : (bvh.z_min, bvh.z_max) tzmin = (a - ori_z) / dir_z tzmax = (b - ori_z) / dir_z (tmin > tzmax || tzmin > tmax) && return false return true end return broadcast(check_intersection_ray, direction.x, direction.y, direction.z, origin.x, origin.y, origin.z) end intersect(bvh::BoundingVolumeHierarchy, origin, direction) = intersect(bvh.root_node, bvh, origin, direction) function intersect(bvh::BVHNode, bvh_structure::BoundingVolumeHierarchy, origin, direction) hit = intersection_check(bvh, origin, direction) dir_rays = extract(hit, direction) ori_rays = extract(hit, origin) if isleafnode(bvh) t_values = IdDict{Triangle, Vector}( map(x -> (x, intersect(x, ori_rays, dir_rays)), bvh_structure.scene_list[bvh.index_start:bvh.index_end])) else t_values = intersect(bvh.left_child, bvh_structure, ori_rays, dir_rays) # We do not need to check the ones which have already intersected but let's # keep the code simple for now # if !isnothing(bvh.right_child) merge!(t_values, intersect(bvh.right_child, bvh_structure, ori_rays, dir_rays)) # end end for k in keys(t_values) t_values[k] = place(t_values[k], hit, Inf) end return t_values end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
5304
export Camera, get_primary_rays # ------ # # Camera # # ------ # """ FixedCameraParams The Parameters of the [`Camera`](@ref) which should not be updated in inverse rendering are wrapped into this object. ### Fields: * `vup` - Stores the World UP Vector (In most cases this is the Y-Axis Vec3(0.0, 1.0, 0.0)) * `width` - Width of the image to be rendered * `height` - Height of the image to be rendered """ struct FixedCameraParams{T} <: FixedParams vup::Vec3{T} width::Int height::Int end Base.show(io::IO, fcp::FixedCameraParams) = print(io, " Fixed Parameters:\n World UP - ", fcp.vup, "\n Screen Dimensions - ", fcp.height, " × ", fcp.width) Base.zero(fcp::FixedCameraParams) = FixedCameraParams(zero(fcp.vup), zero(fcp.width), zero(fcp.height)) """ Camera The Perspective View Camera Model ### Fields: * `lookfrom` - Position of the Camera in 3D World Space * `lookat` - Point in the 3D World Space where the Camera is Pointing * `vfov` - Field of View of the Camera * `focus` - The focal length of the Camera * `fixedparams` - An instance of [`FixedCameraParams`](@ref) ### Available Constructors: * `Camera(;lookfrom = Vec3(0.0f0), lookat = Vec3(0.0f0), vup = Vec3(0.0f0, 1.0f0, 0.0f0), vfov = 90.0f0, focus = 1.0f0, width = 128, height = 128)` * `Camera(lookfrom::Vec3{T}, lookat::Vec3{T}, vup::Vec3{T}, vfov::R, focus::R, width::Int, height::Int) where {T<:AbstractArray, R<:Real}` """ struct Camera{T} lookfrom::Vec3{T} lookat::Vec3{T} vfov::T focus::T fixedparams::FixedCameraParams{T} end Base.show(io::IO, cam::Camera) = print(io, "CAMERA Configuration:\n Lookfrom - ", cam.lookfrom, "\n Lookat - ", cam.lookat, "\n Field of View - ", cam.vfov[], "\n Focus - ", cam.focus[], "\n", cam.fixedparams) @diffops Camera Camera(;lookfrom = Vec3(0.0f0), lookat = Vec3(0.0f0), vup = Vec3(0.0f0, 1.0f0, 0.0f0), vfov = 90.0f0, focus = 1.0f0, width = 128, height = 128) = Camera(lookfrom, lookat, vup, vfov, focus, width, height) function Camera(lookfrom::Vec3{T}, lookat::Vec3{T}, vup::Vec3{T}, vfov::R, focus::R, width::Int, height::Int) where {T<:AbstractArray, R<:Real} fixedparams = FixedCameraParams(vup, width, height) return Camera(lookfrom, lookat, [vfov], [focus], fixedparams) end """ get_primary_rays(c::Camera) Takes the configuration of the camera and returns the origin and the direction of the primary rays. """ function get_primary_rays(c::Camera) width = c.fixedparams.width height = c.fixedparams.height vup = c.fixedparams.vup vfov = c.vfov[] focus = c.focus[] aspect_ratio = width / height half_height = tan(deg2rad(vfov / 2)) half_width = typeof(half_height)(aspect_ratio * half_height) origin = c.lookfrom w = normalize(c.lookfrom - c.lookat) u = normalize(cross(vup, w)) v = normalize(cross(w, u)) # Lower Left Corner llc = origin - half_width * focus * u - half_height * focus * v - w hori = 2 * half_width * focus * u vert = 2 * half_height * focus * v s = repeat((collect(0:(width - 1)) .+ 0.5f0) ./ width, outer = height) t = repeat((collect((height - 1):-1:0) .+ 0.5f0) ./ height, inner = width) direction = normalize(llc + s * hori + t * vert - origin) return (origin, direction) end """ get_transformation_matrix(c::Camera) Returns the `camera_to_world` transformation matrix. This is used for transforming the coordinates of a Point in 3D Camera Space to 3D World Space using the [`camera2world`](@ref) function. """ function get_transformation_matrix(c::Camera{T}) where {T} forward = normalize(c.lookfrom - c.lookat) right = normalize(cross(c.fixedparams.vup, forward)) up = normalize(cross(forward, right)) return [ right.x[] right.y[] right.z[] zero(eltype(T)); up.x[] up.y[] up.z[] zero(eltype(T)); forward.x[] forward.y[] forward.z[] zero(eltype(T)); c.lookfrom.x[] c.lookfrom.y[] c.lookfrom.z[] one(eltype(T))] end """ compute_screen_coordinates(c::Camera, film_aperture::Tuple, inch_to_mm::Real = 25.4) Computes the coordinates of the 4 corners of the screen and returns `top`, `right`, `bottom`, and `left`. """ function compute_screen_coordinates(c::Camera, film_aperture::Tuple, inch_to_mm::Real = 25.4) width = c.fixedparams.width height = c.fixedparams.height vfov = c.vfov[] focus = c.focus[] film_aspect_ratio = film_aperture[1] / film_aperture[2] device_aspect_ratio = width / height top = ((film_aperture[2] * inch_to_mm / 2) / focus) right = ((film_aperture[1] * inch_to_mm / 2) / focus) xscale = 1 yscale = 1 if film_aspect_ratio > device_aspect_ratio xscale = device_aspect_ratio / film_aspect_ratio else yscale = film_aspect_ratio / device_aspect_ratio end right *= xscale top *= yscale bottom = -top left = -right return top, right, bottom, left end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
1227
export get_image, zeroonenorm using Zygote: @adjoint # ---------- # # Processing # # ---------- # """ get_image(image, width, height) Reshapes and normalizes a Vec3 color format to the RGB format of Images for easy loading, saving and visualization. ### Arguments: * `image` - The rendered image in flattened Vec3 format (i.e., the output of the raytrace, rasterize, etc.) * `width` - Width of the output image * `height` - Height of the output image """ function get_image(im::Vec3{T}, width, height) where {T} low = eltype(T)(0) high = eltype(T)(1) color_r = reshape(im.x, width, height) color_g = reshape(im.y, width, height) color_b = reshape(im.z, width, height) im_arr = zeroonenorm(permutedims(reshape(hcat(color_r, color_g, color_b), (width, height, 3)), (3, 2, 1))) return colorview(RGB, im_arr) end """ zeroonenorm(x::AbstractArray) Normalizes the elements of the array to values between `0` and `1`. !!! note This function exists because the version of Zygote we use returns incorrect gradient for `1/maximum(x)` function. This has been fixed on the latest release of Zygote. """ zeroonenorm(x) = (x .- minimum(x)) ./ (maximum(x) - minimum(x))
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
4638
export PointLight, DistantLight # ----- # # Light # # ----- # """ Light All objects emitting light should be a subtype of this. To add a custom light source, two only two functions need to be defined. * `get_direction(l::MyCustomLightSource, pt::Vec3)` - `pt` is the point receiving the light from this source * `get_intensity(l::MyCustomLightSource, pt::Vec3, dist::Array)` - `dist` is the array representing the distance of the point from the light source """ abstract type Light end """ get_shading_info(l::Light, pt::Vec3) Returns the `direction` of light incident from the light source onto that Point and the intensity of that light ray. It computes these by internally calling the `get_direction` and `get_intensity` functions and hence this function never has to be modified for any `Light` subtype. ### Arguments: * `l` - The Object of the [`Light`](@ref) subtype * `pt` - The Point in 3D Space for which the shading information is queried """ function get_shading_info(l::Light, pt::Vec3) dir = get_direction(l, pt) dist = sqrt.(l2norm(dir)) intensity = get_intensity(l, pt, dist) return normalize(dir), intensity end """ get_direction(l::Light, pt::Vec3) Returns the direction of light incident from the light source to `pt`. """ function get_direction(l::Light, pt::Vec3) end """ get_intensity(l::Light, pt::Vec3, dist::Array) Computed the intensity of the light ray incident at `pt`. """ function get_intensity(l::Light, pt::Vec3, dist::AbstractArray) end # --------------- # # - Point Light - # # --------------- # """ PointLight A source of light which emits light rays from a point in 3D space. The intensity for this light source diminishes as inverse square of the distance from the point. ### Fields: * `color` - Color of the Light Rays emitted from the source. * `intensity` - Intensity of the Light Source. This decreases as ``\\frac{1}{r^2}`` where ``r`` is the distance of the point from the light source. * `position` - Location of the light source in 3D world space. ### Available Constructors: * `PointLight(;color = Vec3(1.0f0), intensity::Real = 100.0f0, position = Vec3(0.0f0))` * `PointLight(color, intensity::Real, position)` """ struct PointLight{T<:AbstractArray} <: Light color::Vec3{T} intensity::T position::Vec3{T} end PointLight(;color = Vec3(1.0f0), intensity::Real = 100.0f0, position = Vec3(0.0f0)) = PointLight(color, intensity, position) PointLight(c, i::Real, p) = PointLight(clamp(c, 0.0f0, 1.0f0), [i], p) show(io::IO, pl::PointLight) = print(io, "Point Light\n Color - ", pl.color, "\n Intensity - ", pl.intensity[], "\n Position - ", pl.position) @diffops PointLight get_direction(p::PointLight, pt::Vec3) = p.position - pt get_intensity(p::PointLight, pt::Vec3, dist::AbstractArray) = p.intensity[] * p.color / (4 .* (eltype(p.color.x))(π) .* (dist .^ 2)) # ----------------- # # - Distant Light - # # ----------------- # """ DistantLight A source of light that is present at infinity as such the rays from it are in a constant direction. The intensity for this light source always remains constant. This is extremely useful when we are trying to render a large scene like a city. ### Fields: * `color` - Color of the Light Rays emitted from the Source. * `intensity` - Intensity of the Light Source. * `direction` - Direction of the Light Rays emitted by the Source. ### Available Constructors: * `DistantLight(;color = Vec3(1.0f0), intensity::Real = 1.0f0, direction = Vec3(0.0f0, 1.0f0, 0.0f0))` * `DistantLight(color, intensity::Real, direction)` """ struct DistantLight{T<:AbstractArray} <: Light color::Vec3{T} intensity::T direction::Vec3{T} # Must be normalized end DistantLight(;color = Vec3(1.0f0), intensity::Real = 1.0f0, direction = Vec3(0.0f0, 1.0f0, 0.0f0)) = DistantLight(color, intensity, direction) DistantLight(c, i::Real, d) = DistantLight(clamp(c, 0.0f0, 1.0f0), [i], normalize(d)) show(io::IO, dl::DistantLight) = print(io, "Distant Light\n Color - ", dl.color, "\n Intensity - ", dl.intensity[], "\n Direction - ", dl.direction) @diffops DistantLight get_direction(d::DistantLight, pt::Vec3) = d.direction get_intensity(d::DistantLight, pt::Vec3, dist::AbstractArray) = d.intensity[]
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
8486
export Material # --------- # # Materials # # --------- # """ Material This Type stores information about the material of an [`Object`](@ref). We compute the color of a point by dispatching on the type of the material. That is why we store `nothing` when a particular field is absent. !!! note `texture_*` and `uv_coordinates` fields are applicable only if the object used is a [`Triangle`](@ref). If any of the texture fields are present, `uv_coordinates` must be present. ### Fields: * `color_ambient` - The Ambient Color of the Material. * `color_diffuse` - The Diffuse Color of the Material. * `color_specular` - The Specular Color of the Material. * `specular_exponent` - Specular Exponent of the Material. * `reflection` - The reflection coefficient of the material. * `texture_ambient` - Stores the ambient texture image (if present) in Vec3 format. * `texture_diffuse` - Stores the diffuse texture image (if present) in Vec3 format. * `texture_specular` - Stores the specular texture image (if present) in VEc3 format. * `uv_coordinates` - The uv coordinates are stored as a vector (of length 3) of tuples. ### Available Constructors ``` Material(;color_ambient = Vec3(1.0f0), color_diffuse = Vec3(1.0f0), color_specular = Vec3(1.0f0), specular_exponent::Real = 50.0f0, reflection::Real = 0.5f0, texture_ambient = nothing, texture_diffuse = nothing, texture_specular = nothing, uv_coordinates = nothing) ``` """ struct Material{T<:AbstractArray, R<:AbstractVector, U<:Union{Vec3, Nothing}, V<:Union{Vec3, Nothing}, W<:Union{Vec3, Nothing}, S<:Union{Vector, Nothing}} # Color Information color_ambient::Vec3{T} color_diffuse::Vec3{T} color_specular::Vec3{T} # Surface Properties specular_exponent::R reflection::R # Texture Information texture_ambient::U texture_diffuse::V texture_specular::W # UV coordinates (relevant only for triangles) uv_coordinates::S end Material(;color_ambient = Vec3(1.0f0), color_diffuse = Vec3(1.0f0), color_specular = Vec3(1.0f0), specular_exponent::Real = 50.0f0, reflection::Real = 0.5f0, texture_ambient = nothing, texture_diffuse = nothing, texture_specular = nothing, uv_coordinates = nothing) = Material(color_ambient, color_diffuse, color_specular, [specular_exponent], [reflection], texture_ambient, texture_diffuse, texture_specular, uv_coordinates) @diffops Material function Base.zero(m::Material) texture_ambient = isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient) texture_diffuse = isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse) texture_specular = isnothing(m.texture_specular) ? nothing : zero(m.texture_specular) uv_coordinates = isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates) return Material(zero(m.color_ambient), zero(m.color_diffuse), zero(m.color_specular), zero(m.specular_exponent), zero(m.reflection), texture_ambient, texture_diffuse, texture_specular, uv_coordinates) end """ get_color(m::Material, pt::Vec3, ::Val{T}, obj::Object) Returns the color at the point `pt`. We use `T` and the type of the Material `m` for efficiently dispatching to the right function. The right function is determined by the presence/absence of the texture field. The possible values of `T` are `:ambient`, `:diffuse`, and `:specular`. """ get_color(m::Material{T, R, Nothing, V, W, S}, pt::Vec3, ::Val{:ambient}, obj) where {T<:AbstractArray, R<:AbstractVector, V<:Union{Vec3, Nothing}, W<:Union{Vec3, Nothing}, S<:Union{Vector, Nothing}} = m.color_ambient get_color(m::Material{T, R, U, Nothing, W, S}, pt::Vec3, ::Val{:diffuse}, obj) where {T<:AbstractArray, R<:AbstractVector, U<:Union{Vec3, Nothing}, W<:Union{Vec3, Nothing}, S<:Union{Vector, Nothing}} = m.color_diffuse get_color(m::Material{T, R, U, V, Nothing, S}, pt::Vec3, ::Val{:specular}, obj) where {T<:AbstractArray, R<:AbstractVector, U<:Union{Vec3, Nothing}, V<:Union{Vec3, Nothing}, S<:Union{Vector, Nothing}} = m.color_specular # This function is only available for triangles. Maybe I should put a # type constraint # The three functions are present only for type inference. Ideally Julia # should figure it out not sure why it is not the case. function get_color(m::Material, pt::Vec3, ::Val{:ambient}, obj) v1v2 = obj.v2 - obj.v1 v1v3 = obj.v3 - obj.v1 normal = cross(v1v2, v1v3) denom = l2norm(normal) edge2 = obj.v3 - obj.v2 vp2 = pt - obj.v2 u_bary = dot(normal, cross(edge2, vp2)) ./ denom edge3 = obj.v1 - obj.v3 vp3 = pt - obj.v3 v_bary = dot(normal, cross(edge3, vp3)) ./ denom w_bary = 1 .- u_bary .- v_bary u = u_bary .* m.uv_coordinates[1][1] .+ v_bary .* m.uv_coordinates[2][1] .+ w_bary .* m.uv_coordinates[3][1] v = u_bary .* m.uv_coordinates[1][2] .+ v_bary .* m.uv_coordinates[2][2] .+ w_bary .* m.uv_coordinates[3][2] # which_texture, which_color = infer_index(f) image = Zygote.literal_getproperty(m, Val(:texture_ambient)) width, height = size(image) x_val = mod1.((Int.(ceil.(u .* width)) .- 1), width) y_val = mod1.((Int.(ceil.(v .* height)) .- 1), height) # Zygote doesn't like me using a splat operation here :'( img = image[x_val .+ (y_val .- 1) .* stride(image.x, 2)] return Zygote.literal_getproperty(m, Val(:color_ambient)) * Vec3(img.x, img.y, img.z) end function get_color(m::Material, pt::Vec3, ::Val{:diffuse}, obj) v1v2 = obj.v2 - obj.v1 v1v3 = obj.v3 - obj.v1 normal = cross(v1v2, v1v3) denom = l2norm(normal) edge2 = obj.v3 - obj.v2 vp2 = pt - obj.v2 u_bary = dot(normal, cross(edge2, vp2)) ./ denom edge3 = obj.v1 - obj.v3 vp3 = pt - obj.v3 v_bary = dot(normal, cross(edge3, vp3)) ./ denom w_bary = 1 .- u_bary .- v_bary u = u_bary .* m.uv_coordinates[1][1] .+ v_bary .* m.uv_coordinates[2][1] .+ w_bary .* m.uv_coordinates[3][1] v = u_bary .* m.uv_coordinates[1][2] .+ v_bary .* m.uv_coordinates[2][2] .+ w_bary .* m.uv_coordinates[3][2] # which_texture, which_color = infer_index(f) image = Zygote.literal_getproperty(m, Val(:texture_diffuse)) width, height = size(image) x_val = mod1.((Int.(ceil.(u .* width)) .- 1), width) y_val = mod1.((Int.(ceil.(v .* height)) .- 1), height) # Zygote doesn't like me using a splat operation here :'( img = image[x_val .+ (y_val .- 1) .* stride(image.x, 2)] return Zygote.literal_getproperty(m, Val(:color_diffuse)) * Vec3(img.x, img.y, img.z) end function get_color(m::Material, pt::Vec3, ::Val{:specular}, obj) v1v2 = obj.v2 - obj.v1 v1v3 = obj.v3 - obj.v1 normal = cross(v1v2, v1v3) denom = l2norm(normal) edge2 = obj.v3 - obj.v2 vp2 = pt - obj.v2 u_bary = dot(normal, cross(edge2, vp2)) ./ denom edge3 = obj.v1 - obj.v3 vp3 = pt - obj.v3 v_bary = dot(normal, cross(edge3, vp3)) ./ denom w_bary = 1 .- u_bary .- v_bary u = u_bary .* m.uv_coordinates[1][1] .+ v_bary .* m.uv_coordinates[2][1] .+ w_bary .* m.uv_coordinates[3][1] v = u_bary .* m.uv_coordinates[1][2] .+ v_bary .* m.uv_coordinates[2][2] .+ w_bary .* m.uv_coordinates[3][2] # which_texture, which_color = infer_index(f) image = Zygote.literal_getproperty(m, Val(:texture_specular)) width, height = size(image) x_val = mod1.((Int.(ceil.(u .* width)) .- 1), width) y_val = mod1.((Int.(ceil.(v .* height)) .- 1), height) # Zygote doesn't like me using a splat operation here :'( img = image[x_val .+ (y_val .- 1) .* stride(image.x, 2)] return Zygote.literal_getproperty(m, Val(:color_specular)) * Vec3(img.x, img.y, img.z) end """ specular_exponent(m::Material) Returns the `specular_exponent` of the Material `m`. """ specular_exponent(m::Material) = m.specular_exponent[] """ reflection(m::Material) Returns the `reflection coefficient` of the Material `m`. """ reflection(m::Material) = m.reflection[]
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
1639
# ------- # # Objects # # ------- # """ Object All primitive objects must be a subtype of this. Currently there are two primitive objects present, [`Triangle`](@ref) and [`Sphere`](@ref). To add support for custom primitive type, two functions need to be defined - [`intersect`](@ref) and [`get_normal`](@ref). """ abstract type Object end """ get_color(obj::Object, pt::Vec3, sym::Val) Computes the color at the point `pt` of the Object `obj` by dispatching to the correct `get_color(obj.material, pt, sym, obj)` method. """ get_color(obj::Object, pt::Vec3, sym::Val) = get_color(obj.material, pt, sym, obj) """ specular_exponent(obj::Object) Returns the `specular_exponent` of the material of the Object. """ specular_exponent(obj::Object) = specular_exponent(obj.material) """ reflection(obj::Object) Returns the `reflection coefficient` of the material of the Object. """ reflection(obj::Object) = reflection(obj.material) """ intersect(obj::Object, origin, direction) Computes the intersection of the light ray with the object. This function returns the ``t`` value where ``intersection\\_point = origin + t \\times direction``. In case the ray does not intersect with the object `Inf` is returned. """ function intersect(obj::Object, origin, direction) end """ get_normal(obj::Object, pt, direction) Returns the normal at the Point `pt` of the Object `obj`. """ function get_normal(obj::Object, pt, direction) end # ----------- # # - Imports - # # ----------- # include("objects/sphere.jl") include("objects/triangle.jl") include("objects/polygon_mesh.jl") include("objects/obj_parser.jl")
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
1026
import Flux.Optimise.apply! export update! # ---------- # # Optimisers # # ---------- # """ update!(opt, x, Δ) Provides an interface to use all of the Optimizers provided by Flux. The type of `x` can be anything as long as the operations defined by `@diffops` are available for it. By default all the differentiable types inside the Package can be used with it. The type of `Δ` must be same as that of `x`. This prevent silent type conversion of `x` which can significantly slow doen the raytracer. ### Example: ```julia julia> opt = ADAM() julia> gs = gradient(loss_function, θ) julia> update!(opt, θ, gs[1]) ``` """ function update!(opt, x::AbstractArray, Δ::AbstractArray) x .-= apply!(opt, x, Δ) return x end update!(opt, x::T, Δ::T) where {T<:Real} = (update!(opt, [x], [Δ]))[] update!(opt, x::FixedParams, Δ::FixedParams) = x update!(opt, x, Δ::Nothing) = x function update!(opt, x::T, Δ::T) where {T} map(i -> update!(opt, getfield(x, i), getfield(Δ, i)), fieldnames(T)) return x end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
10798
import Base: +, *, -, /, %, intersect, minimum, maximum, size, getindex export Vec3, rgb, clip01 # -------- # # Vector 3 # # -------- # """ Vec3 This is the central type for RayTracer. All of the other types are defined building upon this. All the fields of the Vec3 instance contains `Array`s. This ensures that we can collect the gradients w.r.t the fields using the `Params` API of Zygote. ### Fields: * `x` * `y` * `z` The types of `x`, `y`, and `z` must match. Also, if scalar input is given to the constructor it will be cnverted into a 1-element Vector. ### Defined Operations for Vec3: * `+`, `-`, `*` -- These operations will be broadcasted even though there is no explicit mention of broadcasting. * `dot` * `l2norm` * `cross` * `clamp` * `zero` * `similar` * `one` * `maximum` * `minimum` * `normalize` * `size` * `getindex` -- This returns a named tuple """ struct Vec3{T<:AbstractArray} x::T y::T z::T function Vec3(x::T, y::T, z::T) where {T<:AbstractArray} @assert size(x) == size(y) == size(z) new{T}(x, y, z) end function Vec3(x::T1, y::T2, z::T3) where {T1<:AbstractArray, T2<:AbstractArray, T3<:AbstractArray} # Yes, I know it is a terrible hack but Zygote.FillArray was pissing me off. T = eltype(x) <: Real ? eltype(x) : eltype(y) <: Real ? eltype(y) : eltype(z) @warn "Converting the type to $(T) by default" maxlog=1 @assert size(x) == size(y) == size(z) new{AbstractArray{T, ndims(x)}}(T.(x), T.(y), T.(z)) end end Vec3(a::T) where {T<:Real} = Vec3([a], [a], [a]) Vec3(a::T) where {T<:AbstractArray} = Vec3(copy(a), copy(a), copy(a)) Vec3(a::T, b::T, c::T) where {T<:Real} = Vec3([a], [b], [c]) function show(io::IO, v::Vec3) l = prod(size(v)) if l == 1 print(io, "x = ", v.x[], ", y = ", v.y[], ", z = ", v.z[]) elseif l <= 5 print(io, "Vec3 Object\n Length = ", l, "\n x = ", v.x, "\n y = ", v.y, "\n z = ", v.z) else print(io, "Vec3 Object\n Length = ", l, "\n x = ", v.x[1:5], "...\n y = ", v.y[1:5], "...\n z = ", v.z[1:5], "...") end end for op in (:+, :*, :-) @eval begin @inline function $(op)(a::Vec3, b::Vec3) return Vec3(broadcast($(op), a.x, b.x), broadcast($(op), a.y, b.y), broadcast($(op), a.z, b.z)) end end end for op in (:+, :*, :-, :/, :%) @eval begin @inline function $(op)(a::Vec3, b) return Vec3(broadcast($(op), a.x, b), broadcast($(op), a.y, b), broadcast($(op), a.z, b)) end @inline function $(op)(b, a::Vec3) return Vec3(broadcast($(op), a.x, b), broadcast($(op), a.y, b), broadcast($(op), a.z, b)) end end end @inline -(a::Vec3) = Vec3(-a.x, -a.y, -a.z) @inline dot(a::Vec3, b::Vec3) = a.x .* b.x .+ a.y .* b.y .+ a.z .* b.z @inline l2norm(a::Vec3) = dot(a, a) @inline function normalize(a::Vec3) l2 = l2norm(a) l2 = map(x -> x == 0 ? typeof(x)(1) : x, l2) return (a / sqrt.(l2)) end @inline cross(a::Vec3{T}, b::Vec3{T}) where {T} = Vec3(a.y .* b.z .- a.z .* b.y, a.z .* b.x .- a.x .* b.z, a.x .* b.y .- a.y .* b.x) @inline maximum(v::Vec3) = max(maximum(v.x), maximum(v.y), maximum(v.z)) @inline minimum(v::Vec3) = min(minimum(v.x), minimum(v.y), minimum(v.z)) @inline size(v::Vec3) = size(v.x) @inline getindex(v::Vec3, idx...) = (x = v.x[idx...], y = v.y[idx...], z = v.z[idx...]) """ place(a::Vec3, cond) place(a::Array, cond, val = 0) Constructs a new `Vec3` or `Array` depending on the type of `a` with array length equal to that of `cond` filled with zeros (or val). Then it fills the positions corresponding to the `true` values of `cond` with the values in `a`. The length of each array in `a` must be equal to the number of `true` values in the `cond` array. ### Example: ```jldoctest utils julia> using RayTracer; julia> a = Vec3(1, 2, 3) x = 1, y = 2, z = 3 julia> cond = [1, 2, 3] .> 2 3-element BitArray{1}: 0 0 1 julia> RayTracer.place(a, cond) Vec3 Object Length = 3 x = [0, 0, 1] y = [0, 0, 2] z = [0, 0, 3] ``` """ function place(a::Vec3, cond) r = Vec3(zeros(eltype(a.x), size(cond)...), zeros(eltype(a.y), size(cond)...), zeros(eltype(a.z), size(cond)...)) r.x[cond] .= a.x r.y[cond] .= a.y r.z[cond] .= a.z return r end function place(a::Array, cond, val = 0) r = fill(eltype(a)(val), size(cond)...) r[cond] .= a return r end """ place_idx!(a::Vec3, b::Vec3, idx) Number of `true`s in `idx` must be equal to the number of elements in `b`. This function involves mutation of arrays. Since the version of Zygote we use does not support mutation we specify a custom adjoint for this function. ### Arguments: * `a` - The contents of this `Vec3` will be updated * `b` - The contents of `b` are copied into `a` * `idx` - The indices of `a` which are updated. This is a BitArray with length of `idx` being equal to `a.x` """ function place_idx!(a::Vec3, b::Vec3, idx) a.x[idx] .= b.x a.y[idx] .= b.y a.z[idx] .= b.z return a end Base.clamp(v::Vec3, lo, hi) = Vec3(clamp.(v.x, lo, hi), clamp.(v.y, lo, hi), clamp.(v.z, lo, hi)) for f in (:zero, :similar, :one) @eval begin Base.$(f)(v::Vec3) = Vec3($(f)(v.x), $(f)(v.y), $(f)(v.z)) end end # ----- # # Color # # ----- # """ `rgb` is an alias for `Vec3`. It makes more sense to use this while defining colors. """ rgb = Vec3 # ----- # # Utils # # ----- # """ extract(cond, x<:Number) extract(cond, x<:AbstractArray) extract(cond, x::Vec3) Extracts the elements of `x` (in case it is an array) for which the indices corresponding to the `cond` are `true`. !!! note `extract` has a performance penalty when used on GPUs. ### Example: ```jldoctest utils julia> using RayTracer; julia> a = [1.0, 2.0, 3.0, 4.0] 4-element Array{Float64,1}: 1.0 2.0 3.0 4.0 julia> cond = a .< 2.5 4-element BitArray{1}: 1 1 0 0 julia> RayTracer.extract(cond, a) 2-element Array{Float64,1}: 1.0 2.0 ``` """ @inline extract(cond, x::T) where {T<:Number} = x @inline extract(cond, x::T) where {T<:AbstractArray} = x[cond] extract(cond, a::Vec3) = length(a.x) == 1 ? Vec3(a.x, a.y, a.z) : Vec3(extract(cond, a.x), extract(cond, a.y), extract(cond, a.z)) """ bigmul(x) Returns the output same as `typemax`. However, in case gradients are computed, it will return the gradient to be `0` instead of `nothing` as in case of typemax. """ @inline bigmul(x) = typemax(x) """ camera2world(point::Vec3, camera_to_world::Matrix) Converts a `point` in 3D Camera Space to the 3D World Space. To obtain the `camera_to_world` matrix use the [`get_transformation_matrix`](@ref) function. """ function camera2world(point::Vec3, camera_to_world) result = camera2world([point.x point.y point.z], camera_to_world) return Vec3(result[:, 1], result[:, 2], result[:, 3]) end camera2world(point::Array, camera_to_world) = point * camera_to_world[1:3, 1:3] .+ camera_to_world[4, 1:3]' """ world2camera(point::Vec3, world_to_camera::Matrix) Converts a `point` in 3D World Space to the 3D Camera Space. To obtain the `world_to_camera` matrix take the `inv` of the output from the [`get_transformation_matrix`](@ref) function. """ function world2camera(point::Vec3, world_to_camera) result = world2camera([point.x point.y point.z], world_to_camera) return Vec3(result[:, 1], result[:, 2], result[:, 3]) end world2camera(point::Array, world_to_camera) = point * world_to_camera[1:3, 1:3] .+ world_to_camera[4, 1:3]' # ----------------- # # - Helper Macros - # # ----------------- # """ @diffops MyType::DataType Generates functions for performing gradient based optimizations on this custom type. 5 functions are generated. 1. `x::MyType + y::MyType` -- For Gradient Accumulation 2. `x::MyType - y::MyType` -- For Gradient Based Updates 3. `x::MyType * η<:Real` -- For Multiplication of the Learning Rate with Gradient 4. `η<:Real * x::MyType` -- For Multiplication of the Learning Rate with Gradient 5. `x::MyType * y::MyType` -- Just for the sake of completeness. Most of these functions do not make semantic sense. For example, adding 2 `PointLight` instances do not make sense but in case both of them are gradients, it makes perfect sense to accumulate them in a third `PointLight` instance. """ macro diffops(a) quote # Addition for gradient accumulation function $(esc(:+))(x::$(esc(a)), y::$(esc(a))) return $(esc(a))([(isnothing(getfield(x, i)) || isnothing(getfield(y, i))) ? nothing : getfield(x, i) + getfield(y, i) for i in fieldnames($(esc(a)))]...) end # Subtraction for gradient updates function $(esc(:-))(x::$(esc(a)), y::$(esc(a))) return $(esc(a))([(isnothing(getfield(x, i)) || isnothing(getfield(y, i))) ? nothing : getfield(x, i) - getfield(y, i) for i in fieldnames($(esc(a)))]...) end # Multiply for learning rate and misc ops function $(esc(:*))(x::T, y::$(esc(a))) where {T<:Real} return $(esc(a))([isnothing(getfield(y, i)) ? nothing : x * getfield(y, i) for i in fieldnames($(esc(a)))]...) end function $(esc(:*))(x::$(esc(a)), y::T) where {T<:Real} return $(esc(a))([isnothing(getfield(x, i)) ? nothing : getfield(x, i) * y for i in fieldnames($(esc(a)))]...) end function $(esc(:*))(x::$(esc(a)), y::$(esc(a))) return $(esc(a))([(isnothing(getfield(x, i)) || isnothing(getfield(y, i))) ? nothing : getfield(x, i) * getfield(y, i) for i in fieldnames($(esc(a)))]...) end end end # ---------------- # # Fixed Parameters # # ---------------- # """ FixedParams Any subtype of FixedParams is not optimized using the `update!` API. For example, we don't want the screen size to be altered while inverse rendering, this is ensured by wrapping those parameters in a subtype of FixedParams. """ abstract type FixedParams; end for op in (:+, :*, :-, :/, :%) @eval begin @inline $(op)(a::FixedParams, b::FixedParams) = a @inline $(op)(a::FixedParams, b) = a @inline $(op)(a, b::FixedParams) = b end end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
5228
export numderiv # --------------------- # # Numerical Derivatives # # --------------------- # """ ngradient(f, xs::AbstractArray...) Computes the numerical gradients of `f` w.r.t `xs`. The function `f` must return a scalar value for this to work. This function is not meant for general usage as the value of the parameter `δ` has been tuned for this package specifically. Also, it should be noted that these gradients are highly unstable and should be used only for confirming the values obtained through other methods. For meaningful results be sure to use `Float64` as `Float32` is too numerically unstable. """ function ngradient(f, xs::AbstractArray...) grads = zero.(xs) for (x, Δ) in zip(xs, grads), i in 1:length(x) δ = 1.0e-11 tmp = x[i] x[i] = tmp - δ/2 y1 = f(xs...) x[i] = tmp + δ/2 y2 = f(xs...) x[i] = tmp Δ[i] = (y2 - y1)/δ end return grads end # ---------- # # Parameters # # ---------- # """ get_params(x) Get the parameters from a struct that can be tuned. The output is in the form of an array. ### Example: ```jldoctest julia> using RayTracer; julia> scene = Triangle(Vec3(-1.9f0, 1.6f0, 1.0f0), Vec3(1.0f0, 1.0f0, 0.0f0), Vec3(-0.5f0, -1.0f0, 0.0f0), Material()) Triangle Object: Vertex 1 - x = -1.9, y = 1.6, z = 1.0 Vertex 2 - x = 1.0, y = 1.0, z = 0.0 Vertex 3 - x = -0.5, y = -1.0, z = 0.0 Material{Array{Float32,1},Array{Float32,1},Nothing,Nothing,Nothing,Nothing}(x = 1.0, y = 1.0, z = 1.0, x = 1.0, y = 1.0, z = 1.0, x = 1.0, y = 1.0, z = 1.0, Float32[50.0], Float32[0.5], nothing, nothing, nothing, nothing) julia> RayTracer.get_params(scene) 20-element Array{Float32,1}: -1.9 1.6 1.0 1.0 1.0 0.0 -0.5 -1.0 0.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 1.0 50.0 0.5 ``` """ get_params(x::T, typehelp = Float32) where {T<:AbstractArray} = x get_params(x::T, typehelp = Float32) where {T<:Real} = [x] get_params(::Nothing, typehelp = Float32) = typehelp[] get_params(x::T, typehelp = Float32) where {T} = foldl((a, b) -> [a; b], [map(i -> get_params(getfield(x, i), typehelp), fieldnames(T))...]) """ set_params!(x, y::AbstractArray) Sets the tunable parameters of the struct `x`. The index of the last element set into the struct is returned as output. This may be used to confirm that the size of the input array was as expected. ### Example: ```jldoctest julia> using RayTracer; julia> scene = Triangle(Vec3(-1.9f0, 1.6f0, 1.0f0), Vec3(1.0f0, 1.0f0, 0.0f0), Vec3(-0.5f0, -1.0f0, 0.0f0), Material()) Triangle Object: Vertex 1 - x = -1.9, y = 1.6, z = 1.0 Vertex 2 - x = 1.0, y = 1.0, z = 0.0 Vertex 3 - x = -0.5, y = -1.0, z = 0.0 Material{Array{Float32,1},Array{Float32,1},Nothing,Nothing,Nothing,Nothing}(x = 1.0, y = 1.0, z = 1.0, x = 1.0, y = 1.0, z = 1.0, x = 1.0, y = 1.0, z = 1.0, Float32[50.0], Float32[0.5], nothing, nothing, nothing, nothing) julia> new_params = collect(1.0f0:20.0f0) 20-element Array{Float32,1}: 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0 11.0 12.0 13.0 14.0 15.0 16.0 17.0 18.0 19.0 20.0 julia> RayTracer.set_params!(scene, new_params); julia> scene Triangle Object: Vertex 1 - x = 1.0, y = 2.0, z = 3.0 Vertex 2 - x = 4.0, y = 5.0, z = 6.0 Vertex 3 - x = 7.0, y = 8.0, z = 9.0 Material{Array{Float32,1},Array{Float32,1},Nothing,Nothing,Nothing,Nothing}(x = 10.0, y = 11.0, z = 12.0, x = 13.0, y = 14.0, z = 15.0, x = 16.0, y = 17.0, z = 18.0, Float32[19.0], Float32[20.0], nothing, nothing, nothing, nothing) ``` """ function set_params!(x::AbstractArray, y::AbstractArray) l = length(x) x .= y[1:l] return l end # FIXME: This update strategy fails for real parameters. Will need to deal with # this later. But currently I am not much concered about these parameters. set_params!(x::T, y::AbstractArray) where {T<:Real} = set_params!([x], y) function set_params!(x, y::AbstractArray) start = 1 for i in 1:nfields(x) isnothing(getfield(x, i)) && continue start += set_params!(getfield(x, i), y[start:end]) end return start - 1 end # ------------------------- # # Numerical Differentiation # # ------------------------- # """ numderiv(f, θ) numderiv(f, θ::AbstractArray) numderiv(f, θ::Real) Compute the numerical derivates wrt one of the scene parameters. The parameter passed cannot be enclosed in an Array, thus making this not a general method for differentiation. !!! note This is not a generalized method for getting the gradients. For that please use Zygote. However, this can be used to debug you model, incase you feel the gradients obtained by other methods is sketchy. """ function numderiv(f, θ) arr = get_params(θ) function modified_f(x::AbstractArray) θ₂ = deepcopy(θ) set_params!(θ₂, x) return f(θ₂) end grads = ngradient(modified_f, arr)[1] grad_θ = deepcopy(θ) set_params!(grad_θ, grads) return grad_θ end numderiv(f, θ::AbstractArray) = ngradient(f, θ) numderiv(f, θ::Real) = ngradient(f, [θ])
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
17204
import Base.getproperty import Base.findmin import Base.findmax import Base.push! using Zygote: @adjoint, @nograd import Zygote.literal_getproperty # ---- # # Vec3 # # ---- # # Hack to avoid nothing in the gradient due to typemax @adjoint bigmul(x::T) where {T} = bigmul(x), Δ -> (zero(T),) @adjoint Vec3(a, b, c) = Vec3(a, b, c), Δ -> (Δ.x, Δ.y, Δ.z) @adjoint literal_getproperty(v::Vec3, ::Val{:x}) = getproperty(v, :x), Δ -> (Vec3(Δ, zero(v.y), zero(v.z)), nothing) @adjoint literal_getproperty(v::Vec3, ::Val{:y}) = getproperty(v, :y), Δ -> (Vec3(zero(v.x), Δ, zero(v.z)), nothing) @adjoint literal_getproperty(v::Vec3, ::Val{:z}) = getproperty(v, :z), Δ -> (Vec3(zero(v.x), zero(v.y), Δ), nothing) @adjoint function dot(a::Vec3, b::Vec3) dot(a, b), Δ -> begin Δ = map(x -> isnothing(x) ? zero(eltype(a.x)) : x, Δ) t1 = Δ * b t2 = Δ * a if length(a.x) != length(t1.x) t1 = Vec3(sum(t1.x), sum(t1.y), sum(t1.z)) end if length(b.x) != length(t2.x) t2 = Vec3(sum(t2.x), sum(t2.y), sum(t2.z)) end return (t1, t2) end end # The purpose of this adjoint is to ensure type inference works # in the backward pass @adjoint function cross(a::Vec3{T}, b::Vec3{T}) where {T} cross(a, b), Δ -> begin ∇a = zero(a) ∇b = zero(b) x = (Δ.z .* b.y) .- (Δ.y .* b.z) y = (Δ.x .* b.z) .- (Δ.z .* b.x) z = (Δ.y .* b.x) .- (Δ.x .* b.y) if length(a.x) == 1 ∇a.x .= sum(x) ∇a.y .= sum(y) ∇a.z .= sum(z) else ∇a.x .= x ∇a.y .= y ∇a.z .= z end x = (Δ.y .* a.z) .- (Δ.z .* a.y) y = (Δ.z .* a.x) .- (Δ.x .* a.z) z = (Δ.x .* a.y) .- (Δ.y .* a.x) if length(b.x) == 1 ∇b.x .= sum(x) ∇b.y .= sum(y) ∇b.z .= sum(z) else ∇b.x .= x ∇b.y .= y ∇b.z .= z end return (∇a, ∇b) end end @adjoint place(a::Vec3, cond) = place(a, cond), Δ -> (Vec3(Δ.x[cond], Δ.y[cond], Δ.z[cond]), nothing) @adjoint place(a::Array, cond) = place(a, cond), Δ -> (Δ[cond], nothing) @adjoint place_idx!(a::Vec3, b::Vec3, idx) = place_idx!(a, b, idx), Δ -> (zero(Δ), Vec3(Δ[idx]...), nothing) # ----- # # Light # # ----- # # -------------- # # - PointLight - # # -------------- # @adjoint PointLight(color::Vec3, intensity, pos::Vec3) = PointLight(color, intensity, pos), Δ -> (Δ.color, Δ.intensity, Δ.position) @adjoint literal_getproperty(p::PointLight, ::Val{:color}) = getproperty(p, :color), Δ -> (PointLight(Δ, zero(p.intensity), zero(p.position)), nothing) @adjoint literal_getproperty(p::PointLight, ::Val{:intensity}) = getproperty(p, :intensity), Δ -> (PointLight(zero(p.color), Δ, zero(p.position)), nothing) @adjoint literal_getproperty(p::PointLight, ::Val{:position}) = getproperty(p, :position), Δ -> (PointLight(zero(p.color), zero(p.intensity), Δ), nothing) # ---------------- # # - DistantLight - # # ---------------- # @adjoint DistantLight(color::Vec3, intensity, direction::Vec3) = DistantLight(color, intensity, direction), Δ -> (Δ.color, Δ.intensity, Δ.direction) @adjoint literal_getproperty(d::DistantLight, ::Val{:color}) = getproperty(d, :color), Δ -> (DistantLight(Δ, zero(d.intensity), zero(d.direction)), nothing) @adjoint literal_getproperty(d::DistantLight, ::Val{:intensity}) = getproperty(d, :intensity), Δ -> (DistantLight(zero(d.color), Δ, zero(d.direction)), nothing) @adjoint literal_getproperty(d::DistantLight, ::Val{:direction}) = getproperty(d, :direction), Δ -> (DistantLight(zero(d.color), zero(d.intensity), Δ), nothing) # -------- # # Material # # -------- # @adjoint Material(color_ambient, color_diffuse, color_specular, specular_exponent, reflection, texture_ambient, texture_diffuse, texture_specular, uv_coordinates) = Material(color_ambient, color_diffuse, color_specular, specular_exponent, reflection, texture_ambient, texture_diffuse, texture_specular, uv_coordinates), Δ -> (Δ.color_ambient, Δ.color_diffuse, Δ.color_specular, Δ.specular_exponent, Δ.reflection, Δ.texture_ambient, Δ.texture_diffuse, Δ.texture_specular, Δ.uv_coordinates) @adjoint literal_getproperty(m::Material, ::Val{:color_ambient}) = getproperty(m, :color_ambient), Δ -> (Material(Δ, zero(m.color_diffuse), zero(m.color_specular), zero(m.specular_exponent), zero(m.reflection), isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient), isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse), isnothing(m.texture_specular) ? nothing : zero(m.texture_specular), isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates)), nothing) @adjoint literal_getproperty(m::Material, ::Val{:color_diffuse}) = getproperty(m, :color_diffuse), Δ -> (Material(zero(m.color_ambient), Δ, zero(m.color_specular), zero(m.specular_exponent), zero(m.reflection), isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient), isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse), isnothing(m.texture_specular) ? nothing : zero(m.texture_specular), isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates)), nothing) @adjoint literal_getproperty(m::Material, ::Val{:color_specular}) = getproperty(m, :color_specular), Δ -> (Material(zero(m.color_ambient), zero(m.color_diffuse), Δ, zero(m.specular_exponent), zero(m.reflection), isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient), isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse), isnothing(m.texture_specular) ? nothing : zero(m.texture_specular), isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates)), nothing) @adjoint literal_getproperty(m::Material, ::Val{:specular_exponent}) = getproperty(m, :specular_exponent), Δ -> (Material(zero(m.color_ambient), zero(m.color_diffuse), zero(m.color_specular), real.(Δ), zero(m.reflection), isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient), isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse), isnothing(m.texture_specular) ? nothing : zero(m.texture_specular), isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates)), nothing) @adjoint literal_getproperty(m::Material, ::Val{:reflection}) = getproperty(m, :reflection), Δ -> (Material(zero(m.color_ambient), zero(m.color_diffuse), zero(m.color_specular), zero(m.specular_exponent), Δ, isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient), isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse), isnothing(m.texture_specular) ? nothing : zero(m.texture_specular), isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates)), nothing) @adjoint literal_getproperty(m::Material, ::Val{:texture_ambient}) = getproperty(m, :texture_ambient), Δ -> (Material(zero(m.color_ambient), zero(m.color_diffuse), zero(m.color_specular), zero(m.specular_exponent), zero(m.reflection), Δ, isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse), isnothing(m.texture_specular) ? nothing : zero(m.texture_specular), isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates)), nothing) @adjoint literal_getproperty(m::Material, ::Val{:texture_diffuse}) = getproperty(m, :texture_diffuse), Δ -> (Material(zero(m.color_ambient), zero(m.color_diffuse), zero(m.color_specular), zero(m.specular_exponent), zero(m.reflection), isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient), Δ, isnothing(m.texture_specular) ? nothing : zero(m.texture_specular), isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates)), nothing) @adjoint literal_getproperty(m::Material, ::Val{:texture_specular}) = getproperty(m, :texture_specular), Δ -> (Material(zero(m.color_ambient), zero(m.color_diffuse), zero(m.color_specular), zero(m.specular_exponent), zero(m.reflection), isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient), isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse), Δ, isnothing(m.uv_coordinates) ? nothing : zero.(m.uv_coordinates)), nothing) @adjoint literal_getproperty(m::Material, ::Val{:uv_coordinates}) = getproperty(m, :uv_coordinates), Δ -> (Material(zero(m.color_ambient), zero(m.color_diffuse), zero(m.color_specular), zero(m.specular_exponent), zero(m.reflection), isnothing(m.texture_ambient) ? nothing : zero(m.texture_ambient), isnothing(m.texture_diffuse) ? nothing : zero(m.texture_diffuse), isnothing(m.texture_specular) ? nothing : zero(m.texture_specular), Δ), nothing) # ------- # # Objects # # ------- # # ---------- # # - Sphere - # # ---------- # @adjoint Sphere(center, radius, material::Material) = Sphere(center, radius, material), Δ -> (Δ.sphere, Δ.radius, Δ.material) @adjoint literal_getproperty(s::Sphere, ::Val{:center}) = getproperty(s, :center), Δ -> (Sphere(Δ, zero(s.radius), zero(s.material)), nothing) @adjoint literal_getproperty(s::Sphere, ::Val{:radius}) = getproperty(s, :radius), Δ -> (Sphere(zero(s.center), Δ, zero(s.material)), nothing) @adjoint literal_getproperty(s::Sphere, ::Val{:material}) = getproperty(s, :material), Δ -> (Sphere(zero(s.center), zero(s.radius), Δ), nothing) # ------------ # # - Triangle - # # ------------ # @adjoint Triangle(v1, v2, v3, material::Material) = Triangle(v1, v2, v3, material), Δ -> (Δ.v1, Δ.v2, Δ.v3, Δ.material) @adjoint literal_getproperty(t::Triangle, ::Val{:v1}) = getproperty(t, :v1), Δ -> (Triangle(Δ, zero(t.v2), zero(t.v3), zero(t.material)), nothing) @adjoint literal_getproperty(t::Triangle, ::Val{:v2}) = getproperty(t, :v2), Δ -> (Triangle(zero(t.v1), Δ, zero(t.v3), zero(t.material)), nothing) @adjoint literal_getproperty(t::Triangle, ::Val{:v3}) = getproperty(t, :v3), Δ -> (Triangle(zero(t.v1), zero(t.v2), Δ, zero(t.material)), nothing) @adjoint literal_getproperty(t::Triangle, ::Val{:material}) = getproperty(t, :material), Δ -> (Triangle(zero(t.v1), zero(t.v2), zero(t.v3), Δ), nothing) # ---------------- # # - TriangleMesh - # # ---------------- # #= @adjoint TriangleMesh(tm, mat, ftmp) = TriangleMesh(tm, mat, ftmp), Δ -> (Δ.triangulated_mesh, Δ.material, Δ.ftmp) @adjoint function literal_getproperty(t::TriangleMesh, ::Val{:triangulated_mesh}) tm = getproperty(t, :triangulated_mesh) z = eltype(tm[1].v1.x) mat = Material(PlainColor(rgb(z)), z) return tm, Δ -> (TriangleMesh(Δ, mat, FixedTriangleMeshParams(IdDict(), [Vec3(z)])), nothing) end @adjoint function literal_getproperty(t::TriangleMesh, ::Val{:material}) mat = getproperty(t, :material) z = eltype(t.triangulated_mesh[1].v1.x) tm = [Triangle([Vec3(z)]...) for _ in 1:length(t.triangulated_mesh)] return mat, Δ -> (TriangleMesh(tm, Δ, FixedTriangleMeshParams(IdDict(), [Vec3(z)])), nothing) end @adjoint function literal_getproperty(t::TriangleMesh, ::Val{:ftmp}) z = eltype(t.triangulated_mesh[1].v1.x) mat = Material(PlainColor(rgb(z)), z) tm = [Triangle([Vec3(z)]...) for _ in 1:length(t.triangulated_mesh)] return getproperty(t, :ftmp), Δ -> (TriangleMesh(tm, mat, Δ), nothing) end @adjoint FixedTriangleMeshParams(isect, n) = FixedTriangleMeshParams(isect, n), Δ -> (Δ.isect, Δ.n) # The gradients for this params are never used so fill them with anything as long # as they are consistent with the types @adjoint literal_getproperty(ftmp::FixedTriangleMeshParams, ::Val{f}) where {f} = getproperty(ftmp, f), Δ -> (FixedTriangleMeshParams(IdDict(), ftmp.normals[1:1])) =# # ------ # # Camera # # ------ # @adjoint Camera(lf, la, vfov, focus, fp) = Camera(lf, la, vfov, focus, fp), Δ -> (Δ.lookfrom, Δ.lookat, Δ.vfov, Δ.focus, Δ.fixedparams) @adjoint literal_getproperty(c::Camera, ::Val{:lookfrom}) = getproperty(c, :lookfrom), Δ -> (Camera(Δ, zero(c.lookat), zero(c.vfov), zero(c.focus), zero(c.fixedparams)), nothing) @adjoint literal_getproperty(c::Camera, ::Val{:lookat}) = getproperty(c, :lookat), Δ -> (Camera(zero(c.lookfrom), Δ, zero(c.vfov), zero(c.focus), zero(c.fixedparams)), nothing) @adjoint literal_getproperty(c::Camera, ::Val{:vfov}) = getproperty(c, :vfov), Δ -> (Camera(zero(c.lookfrom), zero(c.lookat), Δ, zero(c.focus), zero(c.fixedparams)), nothing) @adjoint literal_getproperty(c::Camera, ::Val{:focus}) = getproperty(c, :focus), Δ -> (Camera(zero(c.lookfrom), zero(c.lookat), zero(c.vfov), Δ, zero(c.fixedparams)), nothing) @adjoint literal_getproperty(c::Camera, ::Val{:fixedparams}) = getproperty(c, :fixedparams), Δ -> (Camera(zero(c.lookfrom), zero(c.lookat), zero(c.vfov), zero(c.focus), Δ), nothing) @adjoint FixedCameraParams(vup, w, h) = FixedCameraParams(vup, w, h), Δ -> (Δ.vup, Δ.width, Δ.height) @adjoint literal_getproperty(fcp::FixedCameraParams, ::Val{f}) where {f} = getproperty(fcp, f), Δ -> (zero(fcp), nothing) # ------- # # ImUtils # # ------- # @adjoint function zeroonenorm(x) mini, indmin = findmin(x) maxi, indmax = findmax(x) res = (x .- mini) ./ (maxi - mini) function ∇zeroonenorm(Δ) ∇x = similar(x) fill!(∇x, 1 / (maxi - mini)) res1 = (x .- maxi) ./ (maxi - mini)^2 ∇x[indmin] = sum(res1) - minimum(res1) res2 = - res ./ (maxi - mini) ∇x[indmax] = sum(res2) - minimum(res2) return (∇x .* Δ, ) end return res, ∇zeroonenorm end # ----------------- # # General Functions # # ----------------- # for func in (:findmin, :findmax) @eval begin @adjoint function $(func)(xs::AbstractArray; dims = :) y = $(func)(xs, dims = dims) function dfunc(Δ) res = zero(xs) res[y[2]] .= Δ[1] return (res, nothing) end return y, dfunc end end end @adjoint reducehcat(x) = reduce(hcat, x), Δ -> ([Δ[:, i] for i in 1:length(x)], ) @adjoint push!(arr, val) = push!(arr, val), Δ -> (Δ[1:end-1], Δ[end]) @nograd fill @nograd function update_index!(arr, i, j, val) arr[i, j] = val end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
8698
export load_obj # ------------------------- # # - Parse OBJ & MTL Files - # # ------------------------- # """ triangulate_faces(vertices::Vector, texture_coordinates::Vector, faces::Vector, material_map::Dict) Triangulates the `faces` and converts it into valid [`Triangle`](@ref) objects. !!! warning Avoid using this function in itself. It is designed to be used internally by the [`load_obj`](@ref) function. """ function triangulate_faces(vertices::Vector, texture_coordinates::Vector, faces::Vector, material_map::Dict) scene = Vector{Triangle}() for face in faces for i in 2:(length(face[1]) - 1) if isnothing(face[2]) uv_coordinates = nothing else uv_coordinates = [[texture_coordinates[face[2][1]]...], [texture_coordinates[face[2][i]]...], [texture_coordinates[face[2][i + 1]]...]] end mat = Material(;uv_coordinates = uv_coordinates, material_map[face[3]]...) push!(scene, Triangle(deepcopy(vertices[face[1][1]]), deepcopy(vertices[face[1][i]]), deepcopy(vertices[face[1][i + 1]]), mat)) end end try scene_stable = Vector{typeof(scene[1])}() for s in scene push!(scene_stable, s) end return scene_stable catch e # If all the triangles are not of the same type return the non-infered # version of the scene. In this case type inference for `raytrace` will # also fail @warn "Could not convert the triangles to the same type. Type inference for raytrace will fail" return scene end end """ parse_mtllib!(file, material_map, outtype) Parses `.mtl` file and creates a map from the material name to [`Material`](@ref) objects. Not all fields of the `mtl` file are parsed. We only parse : `newmtl`, `Ka`, `Kd`, `Ks`, `Ns`, `d`, `Tr`, `map_Kd`, `map_Ks`, and `map_Ka`. """ function parse_mtllib!(file, material_map, outtype) color_diffuse = Vec3(outtype(1.0f0)) color_ambient = Vec3(outtype(1.0f0)) color_specular = Vec3(outtype(1.0f0)) specular_exponent = outtype(50.0f0) reflection = outtype(0.5f0) texture_ambient = nothing texture_diffuse = nothing texture_specular = nothing last_mat = "RayTracer Default" if isnothing(file) material_map[last_mat] = (color_diffuse = color_diffuse, color_ambient = color_ambient, color_specular = color_specular, specular_exponent = specular_exponent, reflection = reflection, texture_ambient = texture_ambient, texture_diffuse = texture_diffuse, texture_specular = texture_specular) return nothing end for line in eachline(file) wrds = split(line) isempty(wrds) && continue if wrds[1] == "newmtl" material_map[last_mat] = (color_diffuse = color_diffuse, color_ambient = color_ambient, color_specular = color_specular, specular_exponent = specular_exponent, reflection = reflection, texture_ambient = texture_ambient, texture_diffuse = texture_diffuse, texture_specular = texture_specular) last_mat = wrds[2] # In case any of these values are not defined for the material # we shall use the default values color_diffuse = Vec3(outtype(1.0f0)) color_ambient = Vec3(outtype(1.0f0)) color_specular = Vec3(outtype(1.0f0)) specular_exponent = outtype(50.0f0) reflection = outtype(0.5f0) texture_ambient = nothing texture_diffuse = nothing texture_specular = nothing elseif wrds[1] == "Ka" color_ambient = Vec3(parse.(outtype, wrds[2:4])...) elseif wrds[1] == "Kd" color_diffuse = Vec3(parse.(outtype, wrds[2:4])...) elseif wrds[1] == "Ks" color_specular = Vec3(parse.(outtype, wrds[2:4])...) elseif wrds[1] == "Ns" specular_exponent = parse(outtype, wrds[2]) elseif wrds[1] == "d" reflection = parse(outtype, wrds[2]) elseif wrds[1] == "Tr" reflection = 1 - parse(outtype, wrds[2]) elseif wrds[1] == "map_Ka" texture_file = "$(rsplit(file, '/', limit = 2)[1])/$(wrds[2])" texture_ambient = Vec3([outtype.(permutedims(channelview(load(texture_file)), (3, 2, 1)))[:,end:-1:1,i] for i in 1:3]...) elseif wrds[1] == "map_Kd" texture_file = "$(rsplit(file, '/', limit = 2)[1])/$(wrds[2])" texture_diffuse = Vec3([outtype.(permutedims(channelview(load(texture_file)), (3, 2, 1)))[:,end:-1:1,i] for i in 1:3]...) elseif wrds[1] == "map_Ks" texture_file = "$(rsplit(file, '/', limit = 2)[1])/$(wrds[2])" texture_specular = Vec3([outtype.(permutedims(channelview(load(texture_file)), (3, 2, 1)))[:,end:-1:1,i] for i in 1:3]...) end end material_map[last_mat] = (color_diffuse = color_diffuse, color_ambient = color_ambient, color_specular = color_specular, specular_exponent = specular_exponent, texture_ambient = texture_ambient, texture_diffuse = texture_diffuse, texture_specular = texture_specular) return nothing end """ load_obj(file; outtype = Float32) Parser for `obj` file. It returns a set of Triangles that make up the scene. Only the following things are parsed as of now: `v`, `vt`, `vn`, `f`, `usemtl` and `mtllib`. """ function load_obj(file; outtype = Float32) vertices = Vector{Vec3{Vector{outtype}}}() texture_coordinates = Vector{Tuple}() normals = Vector{Vec3{Vector{outtype}}}() faces = Vector{Tuple{Vector{Int}, Union{Vector{Int}, Nothing}, String}}() material_map = Dict{String, Union{NamedTuple, Nothing}}() last_mat = "RayTracer Default" mtllib = nothing for line in eachline(file) wrds = split(line) isempty(wrds) && continue if wrds[1] == "v" # Vertices push!(vertices, Vec3(parse.(outtype, wrds[2:4])...)) elseif wrds[1] == "vt" # Texture Coordinates push!(texture_coordinates, tuple(parse.(outtype, wrds[2:3])...)) elseif wrds[1] == "vn" # Normal push!(normals, Vec3(parse.(outtype, wrds[2:4])...)) elseif wrds[1] == "f" # Faces # Currently we shall only be concerned with the vertices of the face # and safely throw away vertex normal information fstwrd = split(wrds[2], '/') texture_c = isempty(fstwrd[2]) ? nothing : [parse(Int, fstwrd[2])] @assert length(fstwrd) == 3 "Incorrect number of /'s in the obj file" push!(faces, ([parse(Int, fstwrd[1])], texture_c, last_mat)) for wrd in wrds[3:end] splitwrd = split(wrd, '/') @assert length(splitwrd) == 3 "Incorrect number of /'s in the obj file" push!(faces[end][1], parse(Int, splitwrd[1])) !isnothing(texture_c) && push!(faces[end][2], parse(Int, splitwrd[2])) end elseif wrds[1] == "usemtl" # Key for parsing mtllib file last_mat = wrds[2] material_map[last_mat] = nothing elseif wrds[1] == "mtllib" # Material file mtllib = "$(rsplit(file, '/', limit = 2)[1])/$(wrds[2])" end end if !isnothing(mtllib) parse_mtllib!(mtllib, material_map, outtype) else parse_mtllib!(nothing, material_map, outtype) end return triangulate_faces(vertices, texture_coordinates, faces, material_map) end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
2024
# ----------------- # # - Triangle Mesh - # # ----------------- # # The idea behind this special object is to implement acceleration structures over it # We shall not be supporting inverse rendering the exact coordinates for now. # This is not difficult. We have to store the vertices and the faces and at every # intersect call recompute everything, so we prefer to avoid this extra computation # for now. # The `intersections` store point to index of triangle mapping for getting the normals struct FixedTriangleMeshParams{V} <: FixedParams intersections::IdDict normals::Vector{Vec3{V}} end struct TriangleMesh{V, P, Q, R, S, T, U} <: Object triangulated_mesh::Vector{Triangle{V, P, Q, R, S, T, U}} material::Material{P, Q, R, S, T, U} ftmp::FixedTriangleMeshParams{V} end function construct_outer_normals(t::Vector{Triangle}) centroid = sum(map(x -> (x.v1 + x.v2 + x.v3) / 3, t)) / length(t) return map(x -> get_normal(x, Vec3(0.0f0), x.v1 - centroid), t) end @diffops TriangleMesh TriangleMesh(scene::Vector{Triangle}, mat::Material) = TriangleMesh(scene, mat, FixedTriangleMeshParams(IdDict(), construct_outer_normals(scene))) function intersect(t::TriangleMesh, origin, direction) distances = map(s -> intersect(s, origin, direction), t.triangulated_mesh) dist_reshaped = hcat(distances...) nearest = map(idx -> begin val, index = findmin(dist_reshaped[idx, :], dims = 1) t.ftmp.intersections[direction[idx]] = index return val end, 1:(size(dist_reshaped, 1))) return nearest end function get_normal(t::TriangleMesh, pt, dir) normal = zero(pt) for idx in 1:size(dir)[1] n = t.ftmp.normals[t.ftmp.intersections[dir[idx]]] normal.x[idx] = n.x[1] normal.y[idx] = n.y[1] normal.z[idx] = n.z[1] end return normal end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
1309
export Sphere # ---------- # # - Sphere - # # ---------- # """ Sphere Sphere is a primitive object. ### Fields: * `center` - Center of the Sphere in 3D world space * `radius` - Radius of the Sphere * `material` - Material of the Sphere """ struct Sphere{C, P, Q, R, S, T, U} <: Object center::Vec3{C} radius::C material::Material{P, Q, R, S, T, U} end show(io::IO, s::Sphere) = print(io, "Sphere Object:\n Center - ", s.center, "\n Radius - ", s.radius[], "\n ", s.material) @diffops Sphere function intersect(s::Sphere, origin, direction) b = dot(direction, origin - s.center) # direction is a vec3 with array c = l2norm(s.center) .+ l2norm(origin) .- 2 .* dot(s.center, origin) .- (s.radius .^ 2) disc = (b .^ 2) .- c function get_intersections(x, y) t = bigmul(x + y) # Hack to split the 0.0 gradient to both. Otherwise one gets nothing if y > 0 sqrty = sqrt(y) z1 = -x - sqrty z2 = -x + sqrty if z1 <= 0 && z2 > 0 t = z2 elseif z1 > 0 t = z1 end end return t end result = broadcast(get_intersections, b, disc) return result end get_normal(s::Sphere, pt, dir) = normalize(pt - s.center)
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
2086
export Triangle # ------------ # # - Triangle - # # ------------ # """ Triangle Triangle is a primitive object. Any complex object can be represented as a mesh of Triangles. ### Fields: * `v1` - Vertex 1 * `v2` - Vertex 2 * `v3` - Vertex 3 * `material` - Material of the Triangle """ struct Triangle{V, P, Q, R, S, T, U} <: Object v1::Vec3{V} v2::Vec3{V} v3::Vec3{V} material::Material{P, Q, R, S, T, U} end show(io::IO, t::Triangle) = print(io, "Triangle Object:\n Vertex 1 - ", t.v1, "\n Vertex 2 - ", t.v2, "\n Vertex 3 - ", t.v3, "\n ", t.material) @diffops Triangle get_intersections_triangle(a, b, c, d) = (a > 0 && b > 0 && c > 0 && d > 0) ? a : bigmul(a) Zygote.@adjoint function get_intersections_triangle(a::T, b::T, c::T, d::T) where {T} res = get_intersections_triangle(a, b, c, d) function ∇get_intersections_triangle(Δ) if a > 0 && b > 0 && c > 0 && d > 0 return (Δ, T(0), T(0), T(0)) else return (T(0), T(0), T(0), T(0)) end end return res, ∇get_intersections_triangle end function intersect(t::Triangle, origin, direction) normal = normalize(cross(t.v2 - t.v1, t.v3 - t.v1)) h = (-dot(normal, origin) .+ dot(normal, t.v1)) ./ dot(normal, direction) pt = origin + direction * h edge1 = t.v2 - t.v1 edge2 = t.v3 - t.v2 edge3 = t.v1 - t.v3 c₁ = pt - t.v1 c₂ = pt - t.v2 c₃ = pt - t.v3 val1 = dot(normal, cross(edge1, c₁)) val2 = dot(normal, cross(edge2, c₂)) val3 = dot(normal, cross(edge3, c₃)) result = broadcast(get_intersections_triangle, h, val1, val2, val3) return result end function get_normal(t::Triangle, pt, dir) # normal not expanded normal_nexp = normalize(cross(t.v2 - t.v1, t.v3 - t.v1)) direction = -sign.(dot(normal_nexp, dir)) normal = Vec3(repeat(normal_nexp.x, inner = size(pt.x)), repeat(normal_nexp.y, inner = size(pt.y)), repeat(normal_nexp.z, inner = size(pt.z))) return normal * direction end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
2244
function raytrace(origin::Vec3, direction::Vec3, scene::BoundingVolumeHierarchy, lgt::Light, eye_pos::Vec3, bounce::Int = 0) distances = intersect(scene, origin, direction) dist_reshaped = reducehcat([values(distances)...]) nearest = map(idx -> minimum(dist_reshaped[idx, :]), 1:size(dist_reshaped, 1)) h = .!isinf.(nearest) color = Vec3(0.0f0) for s in scene.scene_list !haskey(distances, s) && continue d = distances[s] hit = map((x, y, z) -> ifelse(y == z, x, zero(x)), h, d, nearest) if any(hit) dc = extract(hit, d) originc = extract(hit, origin) dirc = extract(hit, direction) cc = light(s, originc, dirc, dc, lgt, eye_pos, scene, bounce) color += place(cc, hit) end end return color end function light(s::Object, origin, direction, dist, lgt::Light, eye_pos, scene::BoundingVolumeHierarchy, bounce) pt = origin + direction * dist normal = get_normal(s, pt, direction) dir_light, intensity = get_shading_info(lgt, pt) dir_origin = normalize(eye_pos - pt) nudged = pt + normal * 0.0001f0 # Nudged to miss itself # Shadow light_distances = intersect(scene, nudged, dir_light) seelight = fseelight(s, light_distances) # Ambient color = get_color(s, pt, Val(:ambient)) # Lambert Shading (diffuse) visibility = max.(dot(normal, dir_light), 0.0f0) color += ((get_color(s, pt, Val(:diffuse)) * intensity) * visibility) * seelight # Reflection if bounce < 2 rayD = normalize(direction - normal * 2.0f0 * dot(direction, normal)) color += raytrace(nudged, rayD, scene, lgt, eye_pos, bounce + 1) * reflection(s) end # Blinn-Phong shading (specular) phong = dot(normal, normalize(dir_light + dir_origin)) color += (get_color(s, pt, Val(:specular)) * (clamp.(phong, 0.0f0, 1.0f0) .^ specular_exponent(s))) * seelight return color end function fseelight(t::Triangle, light_distances) ldist = reducehcat([values(light_distances)...]) seelight = map(idx -> minimum(ldist[idx, :]) == light_distances[t][idx], 1:size(ldist, 1)) return seelight end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
5481
export raytrace # ----------------- # # Blinn Phong Model # # ----------------- # """ light(s::Object, origin, direction, dist, lgt::Light, eye_pos, scene, obj_num, bounce) Implements the Blinn Phong rendering algorithm. This function is merely for internal usage and should in no case be called by the user. This function is quite general and supports user defined **Objects**. For support of custom Objects have a look at the examples. !!! warning Don't try to use this function by itself. But if you are a person who likes to ignore warnings look into the way [`raytrace`](@ref) calls this. """ function light(s::Object, origin, direction, dist, lgt::Light, eye_pos, scene, obj_num, bounce) pt = origin + direction * dist normal = get_normal(s, pt, direction) dir_light, intensity = get_shading_info(lgt, pt) dir_origin = normalize(eye_pos - pt) nudged = pt + normal * 0.0001f0 # Nudged to miss itself # Shadow light_distances = map(x -> intersect(x, nudged, dir_light), scene) seelight = fseelight(obj_num, light_distances) # Ambient color = get_color(s, pt, Val(:ambient)) # Lambert Shading (diffuse) visibility = max.(dot(normal, dir_light), 0.0f0) color += ((get_color(s, pt, Val(:diffuse)) * intensity) * visibility) * seelight # Reflection if bounce < 2 rayD = normalize(direction - normal * 2.0f0 * dot(direction, normal)) color += raytrace(nudged, rayD, scene, lgt, eye_pos, bounce + 1) * reflection(s) end # Blinn-Phong shading (specular) phong = dot(normal, normalize(dir_light + dir_origin)) color += (get_color(s, pt, Val(:specular)) * (clamp.(phong, 0.0f0, 1.0f0) .^ specular_exponent(s))) * seelight return color end """ raytrace(origin::Vec3, direction::Vec3, scene::Vector, lgt::Light, eye_pos::Vec3, bounce::Int) raytrace(origin::Vec3, direction::Vec3, scene, lgt::Vector{Light}, eye_pos::Vec3, bounce::Int) raytrace(origin::Vec3, direction::Vec3, scene::BoundingVolumeHierarchy, lgt::Light, eye_pos::Vec3, bounce::Int) raytrace(;origin = nothing, direction = nothing, scene = nothing, light_source = nothing, global_illumination = false) Computes the color contribution to every pixel by tracing every single ray. Internally it calls the `light` function which implements Blinn Phong Rendering and adds up the color contribution for each object. The `eye_pos` is simply the `origin` when called by the user. However, the origin keeps changing across the recursive calls to this function and hence it is necessary to keep track of the `eye_pos` separately. The `bounce` parameter allows the configuration of global illumination. To turn off global illumination set the `bounce` parameter to `>= 2`. As expected rendering is much faster if global illumination is off but at the same time is much less photorealistic. !!! note The support for multiple lights is primitive as we loop over the lights. Even though it is done in a parallel fashion, it is not the best way to do so. Nevertheless it exists just for the sake of experimentation. !!! note None of the parameters (except global_illumination) in the keyword argument version of [`raytrace`](@ref) is optional. It is just present for convenience. """ raytrace(;origin = nothing, direction = nothing, scene = nothing, light_source = nothing, global_illumination = false) = raytrace(origin, direction, scene, light_source, origin, global_illumination ? 0 : 2) function raytrace(origin::Vec3, direction::Vec3, scene::Vector, lgt::Light, eye_pos::Vec3, bounce::Int = 0) distances = map(x -> intersect(x, origin, direction), scene) dist_reshaped = reducehcat(distances) nearest = map(idx -> minimum(dist_reshaped[idx, :]), 1:size(dist_reshaped, 1)) h = .!isinf.(nearest) color = Vec3(0.0f0) for (c, (s, d)) in enumerate(zip(scene, distances)) hit = map((x, y, z) -> ifelse(y == z, x, zero(x)), h, d, nearest) if any(hit) dc = extract(hit, d) originc = extract(hit, origin) dirc = extract(hit, direction) cc = light(s, originc, dirc, dc, lgt, eye_pos, scene, c, bounce) color += place(cc, hit) end end return color end # FIXME: This is a temporary solution. Long term solution is to support # a light vector in the `light` function itself. function raytrace(origin::Vec3, direction::Vec3, scene, lgt::Vector{L}, eye_pos::Vec3, bounce::Int = 0) where {L<:Light} colors = pmap(x -> raytrace(origin, direction, scene, x, eye_pos, bounce), lgt) return sum(colors) end # ------------------------ # # General Helper Functions # # ------------------------ # """ fseelight(n::Int, light_distances) Checks if the ``n^{th}`` object in the scene list can see the light source. """ function fseelight(n, light_distances) ldist = reducehcat(light_distances) seelight = map(idx -> minimum(ldist[idx, :]) == ldist[idx,n], 1:size(ldist, 1)) return seelight end # fseelight(n, light_distances) = map((x...) -> min(x...) == x[n], light_distances...) """ reducehcat(x) This is simply `reduce(hcat(x))`. The version of Zygote we are currently using can't differentiate through this function. So we define a custom adjoint for this. """ reducehcat(x) = reduce(hcat, x)
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
7128
export rasterize # --------- # # Constants # # --------- # const film_aperture = (0.980f0, 0.735f0) # --------- # # Utilities # # --------- # """ edge_function(pt1::Vec3, pt2::Vec3, point::Vec3) Checks on which side of the line formed by `pt1` and `pt2` does `point` lie. """ edge_function(pt1::Vec3, pt2::Vec3, point::Vec3) = edge_function_vector(pt1, pt2, point)[] """ edge_function_vector(pt1::Vec3, pt2::Vec3, point::Vec3) Vectoried form of the [`edge_function`](@ref) """ edge_function_vector(pt1::Vec3, pt2::Vec3, point::Vec3) = ((point.x .- pt1.x) .* (pt2.y - pt1.y) .- (point.y .- pt1.y) .* (pt2.x .- pt1.x)) """ convert2raster(vertex_world::Vec3, world_to_camera, left::Real, right::Real, top::Real, bottom::Real, width::Int, height::Int) convert2raster(vertex_camera::Vec3{T}, left::Real, right::Real, top::Real, bottom::Real, width::Int, height::Int) where {T} Converts a Point in 3D world space to the 3D raster space. The conversion is done by the following steps: ```math V_{camera} = World2CameraTransform(V_{world}) ``` ```math V_{screen_x} = -\\frac{V_{camera_x}}{V_{camera_z}} ``` ```math V_{screen_y} = -\\frac{V_{camera_y}}{V_{camera_z}} ``` ```math V_{NDC_x} = \\frac{2 \\times V_{screen_x} - right - left}{right - left} ``` ```math V_{NDC_y} = \\frac{2 \\times V_{screen_y} - top - bottom}{top - bottom} ``` ```math V_{raster_x} = \\frac{V_{NDC_x} + 1}{2 \\times width} ``` ```math V_{raster_y} = \\frac{1 - V_{NDC_y}}{2 \\times height} ``` ```math V_{raster_z} = - V_{camera_z} ``` """ function convert2raster(vertex_world::Vec3, world_to_camera, left::Real, right::Real, top::Real, bottom::Real, width::Int, height::Int) vertex_camera = world2camera(vertex_world, world_to_camera) return convert2raster(vertex_camera, left, right, top, bottom, width, height) end function convert2raster(vertex_camera::Vec3{T}, left::Real, right::Real, top::Real, bottom::Real, width::Int, height::Int) where {T} outtype = eltype(T) vertex_screen = (x = vertex_camera.x[] / -vertex_camera.z[], y = vertex_camera.y[] / -vertex_camera.z[]) vertex_NDC = (x = outtype((2 * vertex_screen.x - right - left) / (right - left)), y = outtype((2 * vertex_screen.y - top - bottom) / (top - bottom))) vertex_raster = Vec3([(vertex_NDC.x + 1) / 2 * outtype(width)], [(1 - vertex_NDC.y) / 2 * outtype(height)], -vertex_camera.z) return vertex_raster end # ---------- # # Rasterizer # # ---------- # """ rasterize(cam::Camera, scene::Vector) rasterize(cam::Camera, scene::Vector, camera_to_world, world_to_camera, top, right, bottom, left) Implements the raterization algorithm. This is extremely fast when compared to the [`raytrace`](@ref) function. However, the image generated is much less photorealistic with no lighting effects. """ function rasterize(cam::Camera, scene::Vector) top, right, bottom, left = compute_screen_coordinates(cam, film_aperture) camera_to_world = get_transformation_matrix(cam) world_to_camera = inv(camera_to_world) return rasterize(cam, scene, camera_to_world, world_to_camera, top, right, bottom, left) end function rasterize(cam::Camera{T}, scene::Vector, camera_to_world, world_to_camera, top, right, bottom, left) where {T} width = cam.fixedparams.width height = cam.fixedparams.height frame_buffer = Vec3(zeros(eltype(T), width * height)) depth_buffer = fill(eltype(T)(Inf), width, height) for triangle in scene v1_camera = world2camera(triangle.v1, world_to_camera) v2_camera = world2camera(triangle.v2, world_to_camera) v3_camera = world2camera(triangle.v3, world_to_camera) normal = normalize(cross(v2_camera - v1_camera, v3_camera - v1_camera)) v1_raster = convert2raster(v1_camera, left, right, top, bottom, width, height) v2_raster = convert2raster(v2_camera, left, right, top, bottom, width, height) v3_raster = convert2raster(v3_camera, left, right, top, bottom, width, height) # Bounding Box xmin, xmax = extrema([v1_raster.x[], v2_raster.x[], v3_raster.x[]]) ymin, ymax = extrema([v1_raster.y[], v2_raster.y[], v3_raster.y[]]) (xmin > width || xmax < 1 || ymin > height || ymax < 1) && continue area = edge_function(v1_raster, v2_raster, v3_raster) # Loop over only the covered pixels x₁ = max( 1, Int(ceil(xmin))) x₂ = min( width, Int(ceil(xmax))) y₁ = max( 1, Int(ceil(ymin))) y₂ = min(height, Int(ceil(ymax))) y = y₁:y₂ x = x₁:x₂ y_space = repeat(collect(y), inner = length(x)) x_space = repeat(collect(x), outer = length(y)) w1_arr = Float32[] w2_arr = Float32[] w3_arr = Float32[] depth = Float32[] x_arr = Int[] y_arr = Int[] y_vec = y_space .+ 0.5f0 x_vec = x_space .+ 0.5f0 pixel = Vec3(x_vec, y_vec, zeros(eltype(x_vec), length(x) * length(y))) w1 = edge_function_vector(v2_raster, v3_raster, pixel) w2 = edge_function_vector(v3_raster, v1_raster, pixel) w3 = edge_function_vector(v1_raster, v2_raster, pixel) for (w1_val, w2_val, w3_val, x_val, y_val) in zip(w1, w2, w3, x_space, y_space) if w1_val >= 0 && w2_val >= 0 && w3_val >= 0 w1_val = w1_val / area w2_val = w2_val / area w3_val = w3_val / area depth_val = 1 / (w1_val / v1_raster.z[] + w2_val / v2_raster.z[] + w3_val / v3_raster.z[]) if depth_val < depth_buffer[x_val, y_val] update_index!(depth_buffer, x_val, y_val, depth_val) push!(w1_arr, w1_val) push!(w2_arr, w2_val) push!(w3_arr, w3_val) push!(depth, depth_val) push!(x_arr, x_val) push!(y_arr, y_val) end end end length(w1_arr) == 0 && continue px = (v1_camera.x[] / -v1_camera.z[]) .* w1_arr .+ (v2_camera.x[] / -v2_camera.z[]) .* w2_arr .+ (v3_camera.x[] / -v3_camera.z[]) .* w3_arr py = (v1_camera.y[] / -v1_camera.z[]) .* w1_arr .+ (v2_camera.y[] / -v2_camera.z[]) .* w2_arr .+ (v3_camera.y[] / -v3_camera.z[]) .* w3_arr # Passing these gradients as 1.0f0 is incorrect pt = Zygote.hook(Δ -> Vec3([1.0f0 for _ in pt.x]), camera2world(Vec3(px, py, ones(Float32, length(px)) * -1) * depth, camera_to_world)) col = get_color(triangle, pt, Val(:diffuse)) idx = x_arr .+ (y_arr .- 1) .* height frame_buffer = place_idx!(frame_buffer, col, idx) end return frame_buffer end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
2656
using Zygote using RayTracer: get_params, set_params! function loss_fn(θ, color) rendered_color = raytrace(origin, direction, θ, light, eye_pos, 0) loss = sum(abs2.(rendered_color.x .- color.x) .+ abs2.(rendered_color.y .- color.y) .+ abs2.(rendered_color.z .- color.z)) return loss end # Define the Scene Parameters screen_size = (w = 400, h = 300) light = PointLight( Vec3(1.0), 1000.0, Vec3(0.15, 0.5, -110.5) ) eye_pos = Vec3(0.0, 0.0, -5.0) cam = Camera(eye_pos, Vec3(0.0), Vec3(0.0, 1.0, 0.0), 45.0, 1.0, screen_size...) origin, direction = get_primary_rays(cam); @testset "Triangle" begin scene = [ Triangle(Vec3(-1.7, 1.0, 0.0), Vec3(1.0, 1.0, 0.0), Vec3(1.0, -1.0, 0.0), Material(color_ambient = Vec3(1.0), color_diffuse = Vec3(1.0), color_specular = Vec3(1.0), specular_exponent = 50.0, reflection = 1.0)) ] scene_new = [ Triangle(Vec3(-1.9, 1.3, 0.1), Vec3(1.2, 1.1, 0.3), Vec3(0.8, -1.2, -0.15), Material(color_ambient = Vec3(1.0), color_diffuse = Vec3(1.0), color_specular = Vec3(1.0), specular_exponent = 50.0, reflection = 1.0)) ] color = raytrace(origin, direction, scene, light, eye_pos, 0) zygote_grads = get_params(gradient(x -> loss_fn(x, color), scene_new)[1][1]) numerical_grads = get_params(numderiv(x -> loss_fn([x], color), scene_new[1])) @test isapprox(numerical_grads, zygote_grads, rtol = 1.0e-3) end @testset "Sphere" begin scene = [ Sphere(Vec3(-1.7, 1.0, 0.0), [0.6], Material(color_ambient = Vec3(1.0), color_diffuse = Vec3(1.0), color_specular = Vec3(1.0), specular_exponent = 50.0, reflection = 1.0)) ] scene_new = [ Sphere(Vec3(-1.9, 1.3, 0.1), [0.9], Material(color_ambient = Vec3(1.0), color_diffuse = Vec3(1.0), color_specular = Vec3(1.0), specular_exponent = 50.0, reflection = 1.0)) ] color = raytrace(origin, direction, scene, light, eye_pos, 0) zygote_grads = get_params(gradient(x -> loss_fn(x, color), scene_new)[1][1]) numerical_grads = get_params(numderiv(x -> loss_fn([x], color), scene_new[1])) @test isapprox(numerical_grads[1:4], zygote_grads[1:4], rtol = 1.0e-3) end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
688
screen_size = (w = 512, h = 512) cam = Camera( Vec3(0.5f0, 0.2f0, -0.5f0), Vec3(0.0f0, 0.1f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 0.5f0, screen_size... ) light = PointLight( Vec3(1.0f0), 2.0f8, Vec3(10.0f0, 10.0f0, 5.0f0) ) origin, direction = get_primary_rays(cam) @testset "Image Texture" begin scene = load_obj("./meshes/sign_yield.obj") @test_nowarn raytrace(origin, direction, scene, light, origin, 0) end @testset "Plain Color Texture" begin scene = load_obj("./meshes/tree.obj") @test_nowarn raytrace(origin, direction, scene, light, origin, 0) @inferred raytrace(origin, direction, scene, light, origin, 0) end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
234
using RayTracer, Test @testset "Rendering" begin include("utils.jl") include("mesh_render.jl") end @testset "Differentiable Ray Tracing" begin @testset "Gradient Checks" begin include("gradcheck.jl") end end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
code
2329
@testset "Basic Vec3 Functionality" begin # Check the constructors a = Vec3(1.0) @test a.x[] == 1.0 && a.y[] == 1.0 && a.z[] == 1.0 a = Vec3([1.0, 1.0]) @test a.x == [1.0, 1.0] && a.y == [1.0, 1.0] && a.z == [1.0, 1.0] # Operators +, -, * | Both Vec3 for op in (:+, :-, :*) len = rand(1:25) a1 = rand(len) b1 = rand(len) c1 = rand(len) a2 = rand(len) b2 = rand(len) c2 = rand(len) vec3_1 = Vec3(a1, b1, c1) vec3_2 = Vec3(a2, b2, c2) res = @eval $(op)($vec3_1, $vec3_2) res_x = @eval broadcast($(op), $a1, $a2) res_y = @eval broadcast($(op), $b1, $b2) res_z = @eval broadcast($(op), $c1, $c2) @test res.x == res_x && res.y == res_y && res.z == res_z end # Operators +, -, *, /, % | Only 1 Vec3 for op in (:+, :-, :*, :/, :%) len = rand(1:25) a = rand(len) b = rand(len) c = rand(len) num = rand() vec3_1 = Vec3(a, b, c) res1 = @eval $(op)($vec3_1, $num) res1_x = @eval broadcast($(op), $a, $num) res1_y = @eval broadcast($(op), $b, $num) res1_z = @eval broadcast($(op), $c, $num) @test res1.x == res1_x && res1.y == res1_y && res1.z == res1_z res2 = @eval $(op)($num, $vec3_1) res2_x = @eval broadcast($(op), $a, $num) res2_y = @eval broadcast($(op), $b, $num) res2_z = @eval broadcast($(op), $c, $num) @test res2.x == res2_x && res2.y == res2_y && res2.z == res2_z end # Other Operators a_vec = Vec3(1.0, 2.0, 3.0) b_vec = Vec3(4.0, 5.0, 6.0) neg_a_vec = - a_vec cross_prod = RayTracer.cross(a_vec, b_vec) b_clamped = clamp(b_vec, 4.5, 5.5) @test neg_a_vec.x[] == -1.0 && neg_a_vec.y[] == -2.0 && neg_a_vec.z[] == -3.0 @test RayTracer.dot(a_vec, b_vec)[] == 32.0 @test RayTracer.l2norm(a_vec)[] == 14.0 @test RayTracer.l2norm(RayTracer.normalize(a_vec))[] == 1.0 @test maximum(a_vec) == 3.0 @test minimum(a_vec) == 1.0 @test size(a_vec) == (1,) @test getindex(a_vec, 1) == (x = 1.0, y = 2.0, z = 3.0) @test cross_prod.x[] == -3.0 && cross_prod.y[] == 6.0 && cross_prod.z[] == -3.0 @test b_clamped.x[] == 4.5 && b_clamped.y[] == 5.0 && b_clamped.z[] == 5.5 end
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
5877
# RayTracer.jl ![CI](https://github.com/avik-pal/RayTracer.jl/workflows/CI/badge.svg?branch=master) [![codecov](https://codecov.io/gh/avik-pal/RayTracer.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/avik-pal/RayTracer.jl) [![Latest Docs](https://img.shields.io/badge/docs-latest-blue.svg)](https://avik-pal.github.io/RayTracer.jl/dev/) [![DOI](https://proceedings.juliacon.org/papers/10.21105/jcon.00037/status.svg)](https://doi.org/10.21105/jcon.00037) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.1442781.svg)](https://doi.org/10.5281/zenodo.1442781) <p align="center"> <video width="512" height="320" autoplay loop> <source src="docs/src/assets/udem1.gif" type="video/gif"> </video> </p> > This package was written in the early days of Flux / Zygote. Both these packages have significantly improved over time. Unfortunately the current state of this package of has not been updated to reflect those improvements. It also seems that it might be better to gradually transition to AD systems like Diffractor (which will potentially have good support for mutations) / define the adjoints directly using ChainRules since Zygote will likely not be having these features (note there has not been an official announcement and the statement is based on some discussions in zulip forum) A Ray Tracer written completely in Julia. This allows us to leverage the AD capablities provided by Zygote to differentiate through the Ray Tracer. ## INSTALLATION This package is registered. So open up a Julia 1.3+ repl and enter the pkg mode. ```julia julia> ] (v1.3) pkg> add RayTracer ``` To use the master branch (not recommended) do. ```julia julia> ] (v1.3) pkg> add RayTracer#master ``` ## TUTORIALS <div align="center"> <table> <tr> <th style="text-align:center"> <a href="examples/teapot_rendering.jl">Introductory Rendering Tutorial</a> </th> <th style="text-align:center"> <a href="examples/inverse_lighting.jl">Inverse Lighting Tutorial</a> </th> <th style="text-align:center"> <a href="examples/optim_compatibility.jl">Inverse Rendering with Optim.jl Tutorial</a> </th> </tr> <tr> <td align="center"> <a href="examples/teapot_rendering.jl"> <img border="0" src="paper/images/render/teapot_top.jpg" width="200" height="200"> </a> </td> <td align="center"> <a href="examples/inverse_lighting.jl"> <img border="0" src="docs/src/assets/inv_lighting.gif" width="200" height="200"> </a> </td> <td align="center"> <a href="examples/optim_compatibility.jl"> <img border="0" src="docs/src/assets/inv_lighting_optim.gif" width="200" height="200"> </a> </td> </tr> </table> </div> ## USAGE EXAMPLES Follow the instructions below to run individual examples or use `examples/script.sh` to run all of them together. First we need to get the versions of the packages used when these examples were written. ```bash $ cd examples $ julia --color=yes -e "using Pkg; Pkg.instantiate()" ``` Now we can run any of the file we need by `julia --project=. --color=yes "/path/to/file"` ### Running Individual Examples * [`teapot_rendering.jl`](examples/teapot_rendering.jl) -- We need to download the `teapot.obj` file. ``` wget https://raw.githubusercontent.com/McNopper/OpenGL/master/Binaries/teapot.obj ``` * [`performance_benchmarks.jl`](examples/performance_benchmarks.jl) -- We need the mesh and texture for the yield sign board. ```bash $ mkdir meshes $ cd meshes $ wget https://raw.githubusercontent.com/avik-pal/RayTracer.jl/master/test/meshes/sign_yield.obj $ wget https://raw.githubusercontent.com/avik-pal/RayTracer.jl/master/test/meshes/sign_yield.mtl $ cd .. $ mkdir textures $ cd textures $ wget https://raw.githubusercontent.com/avik-pal/RayTracer.jl/master/test/textures/wood_osb.jpg $ wget https://raw.githubusercontent.com/avik-pal/RayTracer.jl/master/test/textures/sign_yield.png $ cd .. ``` This example requires a few arguments to be passes from command line. Chack them using `julia --project=. --color=yes "performance_benchmarks.jl" --help` * [`inverse_lighting.jl`](examples/inverse_lighting.jl) & [`optim_compatibility.jl`](examples/optim_compatibility.jl) -- We need to the `tree.mtl` and `tree.obj` files. ``` $ wget https://raw.githubusercontent.com/tejank10/Duckietown.jl/master/src/meshes/tree.obj $ wget https://raw.githubusercontent.com/tejank10/Duckietown.jl/master/src/meshes/tree.mtl ``` ### Additional Examples [Duckietown.jl](https://github.com/tejank10/Duckietown.jl) uses RayTracer.jl for generating renders of a self-driving car environment. For more complex examples of RayTracer, checkout that project. ## SUPPORTING AND CITING: This software was developed as part of academic research. If you would like to help support it, please star the repository. If you use this software as part of your research, teaching, or other activities, we would be grateful if you could cite the following: ``` @article{Pal2020, doi = {10.21105/jcon.00037}, url = {https://doi.org/10.21105/jcon.00037}, year = {2020}, publisher = {The Open Journal}, volume = {1}, number = {1}, pages = {37}, author = {Avik Pal}, title = {RayTracer.jl: A Differentiable Renderer that supports Parameter Optimization for Scene Reconstruction}, journal = {Proceedings of the JuliaCon Conferences} } ``` ## CURRENT ROADMAP These are not listed in any particular order - [X] Add more types of common objects (use mesh rendering for this) - [X] Add support for rendering arbitrary mesh - [X] Inverse Rendering Examples - [X] Texture Rendering - [ ] Application in Machine Learning Models through Flux (work in progress) - [ ] Major Overhaul using Flux3D.jl - [ ] Exploit the latest improvements to Flux and Zygote
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
4440
# RayTracer : Differentiable Ray Tracing in Julia ```@raw html <p align="center"> <video width="512" height="320" autoplay loop> <source src="./assets/udem1.webm" type="video/webm"> </video> </p> ``` RayTracer.jl is a library for differentiable ray tracing. It provides utilities for 1. Render complex 3D scenes. 2. Differentiate the Ray Tracer wrt arbitrary scene parameters for Gradient Based Inverse Rendering. ## Installation Download [Julia 1.0](https://julialang.org/) or later. For the time being, the library is under active development and hence is not registered. But the master branch is pretty stable for experimentation. To install it simply open a julia REPL and do `] add RayTracer`. The master branch will do all computation on CPU. To try out the experimental GPU support do `] add RayTracer#ap/gpu`. To observe the potential performance gains of using GPU you will have to render scenes having more number of objects and the 2D image must be of reasonably high resolution. !!! note Only rendering is currently supported on GPUs. Gradient Computation is broken but will be supported in the future. ## Supporting and Citing This software was developed as part of academic research. If you would like to help support it, please star the repository. If you use this software as part of your research, teaching, or other activities, we would be grateful if you could cite: ``` @misc{pal2019raytracerjl, title={{RayTracer.jl: A Differentiable Renderer that supports Parameter Optimization for Scene Reconstruction}}, author={Avik Pal}, year={2019}, eprint={1907.07198}, archivePrefix={arXiv}, primaryClass={cs.GR} } ``` ## Contribution Guidelines This package is written and maintained by [Avik Pal](https://avik-pal.github.io). Please fork and send a pull request or create a [GitHub issue](https://github.com/avik-pal/RayTracer.jl/issues) for bug reports. If you are submitting a pull request make sure to follow the official [Julia Style Guide](https://docs.julialang.org/en/v1/manual/style-guide/index.html) and please use 4 spaces and NOT tabs. ### Adding a new feature * For adding a new feature open a Github Issue first to discuss about it. * Please note that we try and avoid having many primitive objects. This might speed up rendering in some rare cases (as most objects will end up being represented as [`Triangle`](@ref)s) but is really painful to maintain in the future. * If you wish to add rendering algorithms it needs to be added to the `src/renderers` directory. Ideally we wish that this is differentiable but we do accept algorithms which are not differentiable (simply add a note in the documentation). * Any new type that is defined should have a corresponding entry in `src/gradients/zygote.jl`. Look at existing types to understand how it is done. Note that it is a pretty ugly thing to do and becomes uglier as the number of fields in your struct increases, so do not define something that has a lot of fields unless you need it (see [`Material`](@ref)). * If you don't want a field in your custom type to be not updated while inverse rendering create a subtype of [`RayTracer.FixedParams`](@ref) and wrap those field in it and store it in your custom type. ### Adding a tutorial/example * We use Literate.jl to convert `examples` to `markdown` files. Look into its [documentation](https://fredrikekre.github.io/Literate.jl/stable/) * Next use the following commands to convert he script to markdown ``` julia> using Literate julia> Literate.markdown("examples/your_example.jl", "docs/src/getting_started/", documenter = false) ``` * Add an entry to `docs/make.jl` so that it is available in the side navigation bar. * Add an entry to the `docs/src/index.md` [Contents](@ref) section. ## Contents ### Home ```@contents Pages = [ "index.md" ] Depth = 2 ``` ### Getting Started Tutorials ```@contents Pages = [ "getting_started/teapot_rendering.md", "getting_started/inverse_lighting.md", "getting_started/optim_compatibility.md" ] Depth = 2 ``` ### API Documentation ```@contents Pages = [ "api/utilities.md", "api/differentiation.md", "api/scene.md", "api/optimization.md", "api/renderers.md", "api/accelerators.md" ] Depth = 2 ``` ## Index ```@index ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
521
```@meta CurrentModule = RayTracer ``` # Acceleration Structures !!! warning This is a Beta Feature and not all things work with this. ```@index Pages = ["accelerators.md"] ``` ## Bounding Volume Hierarchy Bounding Volume Hierarchy (or BVH) acts like a primitive object, just like [`Triangle`](@ref) or [`Sphere`](@ref). So we can simply pass a BVH object into [`raytrace`](@ref) function. !!! warning The backward pass for BVH is currently broken ```@autodocs Modules = [RayTracer] Pages = ["bvh.jl"] ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
553
```@meta CurrentModule = RayTracer ``` # Differentiation The recommended mode of differentation is by Automatic Differentiation using [Zygote](https://github.com/FluxML/Zygote.jl). Refer to the [Zygote docs](http://fluxml.ai/Zygote.jl/dev/#Taking-Gradients-1) for this. The API listed below is for numerical differentiation and is very restrictive (and unstable) in its current form. It should only be used as a validation for the gradients from Zygote. ```@index Pages = ["differentiation.md"] ``` ## Documentation ```@docs ngradient numderiv ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
756
```@meta CurrentModule = RayTracer ``` # Optimization One of the primary use cases of RayTracer.jl is to solve the Inverse Rendering Problem. In this problem, we try to predict the 3D scene given a 2D image of it. Since, "truly" solving this problem is very difficult, we focus on a subproblem where we assume that we have partial knowledge of the 3D scene and now using this image we need to figure out the correct remaining parameters. We do this by iteratively optimizing the parameters using the gradients obtained with the [Differentiation](@ref) API. We describe the current API for optimizing these parameters below. ```@index Pages = ["api/optimization.md"] ``` ## Documentation ```@autodocs Modules = [RayTracer] Pages = ["optimize.jl"] ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
303
```@meta CurrentModule = RayTracer ``` # Renderers This section describes the renderers available in RayTracer.jl ```@index Pages = ["renderers.md"] ``` ## Documentation ```@autodocs Modules = [RayTracer] Pages = ["blinnphong.jl", "rasterizer.jl", "accelerated_raytracer.jl"] ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
680
```@meta CurrentModule = RayTracer ``` # Scene Configuration This page provides the details about how to configure the parameters of the scene. For a more hands on tutorial see [Introduction to rendering using RayTracer.jl](@ref). ```@index Pages = ["scene.md"] ``` ## Camera ```@autodocs Modules = [RayTracer] Pages = ["camera.jl"] ``` ## Light ```@autodocs Modules = [RayTracer] Pages = ["light.jl"] ``` ## Materials ```@autodocs Modules = [RayTracer] Pages = ["materials.jl"] ``` ## Objects ```@autodocs Modules = [RayTracer] Pages = ["sphere.jl", "triangle.jl", "obj_parser.jl", "polygon_mesh.jl", "objects.jl"] ``` ```@docs ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
363
```@meta CurrentModule = RayTracer ``` # General Utilities List of the General Functions and Types provided by the RayTracer. Most of the other functionalities are built upon these. ```@index Pages = ["utilities.md"] ``` ## Documentation ```@autodocs Modules = [RayTracer] Pages = ["utils.jl", "imutils.jl"] ``` ```@docs get_params set_params! ```
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
4703
# Inverse Lighting Tutorial In this tutorial we shall explore the inverse lighting problem. Here, we shall try to reconstruct a target image by optimizing the parameters of the light source (using gradients). ```julia using RayTracer, Images, Zygote, Flux, Statistics ``` ## Configuring the Scene Reduce the screen_size if the optimization is taking a bit long ```julia screen_size = (w = 300, h = 300) ``` Now we shall load the scene using [`load_obj`](@ref) function. For this we need the [`obj`](https://en.wikipedia.org/wiki/Wavefront_.obj_file) and [`mtl`](https://en.wikipedia.org/wiki/Wavefront_.obj_file#Material_template_library) files. They can be downloaded using the following commands: ``` wget https://raw.githubusercontent.com/tejank10/Duckietown.jl/master/src/meshes/tree.obj wget https://raw.githubusercontent.com/tejank10/Duckietown.jl/master/src/meshes/tree.mtl ``` ```julia scene = load_obj("./tree.obj") ``` Let us set up the [`Camera`](@ref). For a more detailed understanding of the rendering process look into [Introduction to rendering using RayTracer.jl](@ref). ```julia cam = Camera( lookfrom = Vec3(0.0f0, 6.0f0, -10.0f0), lookat = Vec3(0.0f0, 2.0f0, 0.0f0), vup = Vec3(0.0f0, 1.0f0, 0.0f0), vfov = 45.0f0, focus = 0.5f0, width = screen_size.w, height = screen_size.h ) origin, direction = get_primary_rays(cam) ``` We should define a few convenience functions. Since we are going to calculate the gradients only wrt to `light` we have it as an argument to the function. Having `scene` as an additional parameters simply allows us to test our method for other meshes without having to run `Zygote.refresh()` repeatedly. ```julia function render(light, scene) packed_image = raytrace(origin, direction, scene, light, origin, 2) array_image = reshape(hcat(packed_image.x, packed_image.y, packed_image.z), (screen_size.w, screen_size.h, 3, 1)) return array_image end showimg(img) = colorview(RGB, permutedims(img[:,:,:,1], (3,2,1))) ``` ## [Ground Truth Image](@id inv_light) For this tutorial we shall use the [`PointLight`](@ref) source. We define the ground truth lighting source and the rendered image. We will later assume that we have no information about this lighting condition and try to reconstruct the image. ```julia light_gt = PointLight( color = Vec3(1.0f0, 1.0f0, 1.0f0), intensity = 20000.0f0, position = Vec3(1.0f0, 10.0f0, -50.0f0) ) target_img = render(light_gt, scene) ``` The presence of [`zeroonenorm`](@ref) is very important here. It rescales the values in the image to 0 to 1. If we don't perform this step `Images` will clamp the values while generating the image in RGB format. ```julia showimg(zeroonenorm(target_img)) ``` ```@raw html <p align="center"> <img width=300 height=300 src="../../assets/inv_light_original.png"> </p> ``` ## Initial Guess of Lighting Parameters We shall make some arbitrary guess of the lighting parameters (intensity and position) and try to get back the image in [Ground Truth Image](@ref inv_light) ```julia light_guess = PointLight( color = Vec3(1.0f0, 1.0f0, 1.0f0), intensity = 1.0f0, position = Vec3(-1.0f0, -10.0f0, -50.0f0) ) showimg(zeroonenorm(render(light_guess, scene))) ``` ```@raw html <p align="center"> <img width=300 height=300 src="../../assets/inv_light_initial.png"> </p> ``` We shall store the images in `results_inv_lighting` directory ```julia mkpath("results_inv_lighting") save("./results_inv_lighting/inv_light_original.png", showimg(zeroonenorm(render(light_gt, scene)))) save("./results_inv_lighting/inv_light_initial.png", showimg(zeroonenorm(render(light_guess, scene)))) ``` ## Optimization Loop We will use the ADAM optimizer from Flux. (Try experimenting with other optimizers as well). We can also use frameworks like Optim.jl for optimization. We will show how to do it in a future tutorial ```julia for i in 1:401 loss, back_fn = Zygote.forward(light_guess) do L sum((render(L, scene) .- target_img) .^ 2) end @show loss gs = back_fn(1.0f0) update!(opt, light_guess.intensity, gs[1].intensity) update!(opt, light_guess.position, gs[1].position) if i % 5 == 1 save("./results_inv_lighting/iteration_$i.png", showimg(zeroonenorm(render(light_guess, scene)))) end end ``` If we generate a `gif` for the optimization process it will look similar to this ```@raw html <p align="center"> <img width=300 height=300 src="../../assets/inv_lighting.gif"> </p> ``` *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
4028
# Optimizing Scene Parameters using Optim.jl In this tutorial we will explore the exact same problem as demonstrated in [Inverse Lighting Tutorial](@ref) but this time we will use the Optimization Package [Optim.jl](https://julianlsolvers.github.io/Optim.jl/stable/). I would recommend going through a few of the [tutorials on Optim](https://julianlsolvers.github.io/Optim.jl/stable/#user/minimization/#_top) before starting this one. If you have already read the previous tutorial, you can safely skip to [Writing the Optimization Loop using Optim](@ref). The part previous to this is same as the previous tutorial. ```julia using RayTracer, Images, Zygote, Flux, Statistics, Optim ``` ## Script for setting up the Scene ```julia screen_size = (w = 64, h = 64) scene = load_obj("./tree.obj") cam = Camera( Vec3(0.0f0, 6.0f0, -10.0f0), Vec3(0.0f0, 2.0f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 0.5f0, screen_size... ) origin, direction = get_primary_rays(cam) function render(light, scene) packed_image = raytrace(origin, direction, scene, light, origin, 2) array_image = reshape(hcat(packed_image.x, packed_image.y, packed_image.z), (screen_size.w, screen_size.h, 3, 1)) return array_image end showimg(img) = colorview(RGB, permutedims(img[:,:,:,1], (3,2,1))) light_gt = PointLight( Vec3(1.0f0, 1.0f0, 1.0f0), 20000.0f0, Vec3(1.0f0, 10.0f0, -50.0f0) ) target_img = render(light_gt, scene) showimg(zeroonenorm(render(light_gt, scene))) light_guess = PointLight( Vec3(1.0f0, 1.0f0, 1.0f0), 1.0f0, Vec3(-1.0f0, -10.0f0, -50.0f0) ) showimg(zeroonenorm(render(light_guess, scene))) ``` ## Writing the Optimization Loop using Optim Since, there is no direct support of Optim (unlike for Flux) in RayTracer the interface might seem a bit ugly. This is mainly due to the way the two optimization packages work. Flux allows inplace operation and ideally even RayTracer prefers that. But Optim requires us to give the parameters as an `AbstractArray`. Firstly, we shall extract the parameters, using the [`RayTracer.get_params`](@ref) function, we want to optimize. ```julia initial_parameters = RayTracer.get_params(light_guess)[end-3:end] ``` Since the input to the `loss_function` is an abstract array we need to convert it into a form that the RayTracer understands. For this we shall use the [`RayTracer.set_params!`](@ref) function which will modify the parameters inplace. In this function we simply compute the loss values and print it for our reference ```julia function loss_function(θ::AbstractArray) light_optim = deepcopy(light_guess) RayTracer.set_params!(light_optim.intensity, θ[1:1]) RayTracer.set_params!(light_optim.position, θ[2:end]) loss = sum((render(light_optim, scene) .- target_img) .^ 2) @show loss return loss end ``` RayTracer uses Zygote's Reverse Mode AD for computing the derivatives. However, the default in Optim is ForwardDiff. Hence, we need to override that by giving our own gradient function. ```julia function ∇loss_function!(G, θ::AbstractArray) light_optim = deepcopy(light_guess) RayTracer.set_params!(light_optim.intensity, θ[1:1]) RayTracer.set_params!(light_optim.position, θ[2:end]) gs = gradient(light_optim) do L sum((render(L, scene) .- target_img) .^ 2) end G .= RayTracer.get_params(gs[1])[end-3:end] end ``` Now we simply call the `optimize` function with `LBFGS` optimizer. ```julia res = optimize(loss_function, ∇loss_function!, initial_parameters, LBFGS()) @show res.minimizer ``` It might be interesting to note that convergence using LBFGS was much faster (only 252 iterations) compared to ADAM (401 iterations). If we generate a `gif` for the optimization process it will look similar to this ```@raw html <p align="center"> <img width=300 height=300 src="../../assets/inv_lighting_optim.gif"> </p> ``` *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.1.4
9b84b299ed0742f769b64f28384f3147a677a576
docs
4443
# Introduction to rendering using RayTracer.jl In this example we will render the famous UTAH Teapot model. We will go through the entire rendering API. We will load an obj file for the scene. This needs to be downloaded manually. Run this code in your terminal to get the file: `wget https://raw.githubusercontent.com/McNopper/OpenGL/master/Binaries/teapot.obj` If you are using REPL mode you need the `ImageView.jl` package ```julia using RayTracer, Images #, ImageView ``` ## General Attributes of the Scene Specify the dimensions of the image we want to generate. `screen_size` is never passed into the RayTracer directly so it need not be a named tuple. ```julia screen_size = (w = 256, h = 256) ``` Load the teapot object from an `obj` file. We can also specify the scene using primitive objects directly but that becomes a bit involved when there are complicated objects in the scene. ```julia scene = load_obj("teapot.obj") ``` We shall define a convenience function for rendering and saving the images. For understanding the parameters passed to the individual functions look into the documentations of [`get_primary_rays`](@ref), [`raytrace`](@ref) and [`get_image`](@ref) ```julia function generate_render_and_save(cam, light, filename) #src # Get the primary rays for the camera origin, direction = get_primary_rays(cam) #src # Render the scene color = raytrace(origin, direction, scene, light, origin, 2) #src # This will reshape `color` into the proper dimensions and return #src # an RGB image img = get_image(color, screen_size...) #src # Display the image #src # For REPL mode change this to `imshow(img)` display(img) #src # Save the generated image save(filename, img) end ``` ## Understanding the Light and Camera API ### DistantLight In this example we will be using the [`DistantLight`](@ref). This king of lighting is useful when we want to render a scene in which all parts of the scene receive the same intensity of light. For the DistantLight we need to provide three attributes: * Color - Color of the Light Rays. Must be a Vec3 Object * Intensity - Intensity of the Light * Direction - The direction of light rays. Again this needs to be a Vec3 Object ### Camera We use a perspective view [`Camera`](@ref) Model in RayTracer. Let us look into the arguments we need to pass into the Camera constructor. * LookFrom - The position of the Camera * LookAt - The point in 3D space where the Camera is pointing * vup - The UP vector of the world (typically Vec3(0.0, 1.0, 0.0), i.e. the y-axis) * vfov - Field of View of the Camera * Focus - The focal length of the Camera * Width - Width of the output image * Height - Height of the output image ## Rendering Different Views of the Teapot Now that we know what each argument means let us render the teapot ### TOP VIEW Render ```julia light = DistantLight( Vec3(1.0f0), 100.0f0, Vec3(0.0f0, 1.0f0, 0.0f0) ) cam = Camera( Vec3(1.0f0, 10.0f0, -1.0f0), Vec3(0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 1.0f0, screen_size... ) generate_render_and_save(cam, light, "teapot_top.jpg") ``` ```@raw html <p align="center"> <img width=256 height=256 src="../../assets/teapot_top.jpg"> </p> ``` ### SIDE VIEW Render ```julia light = DistantLight( Vec3(1.0f0), 100.0f0, Vec3(1.0f0, 1.0f0, -1.0f0) ) cam = Camera( Vec3(1.0f0, 2.0f0, -10.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 1.0f0, screen_size... ) generate_render_and_save(cam, light, "teapot_side.jpg") ``` ```@raw html <p align="center"> <img width=256 height=256 src="../../assets/teapot_side.jpg"> </p> ``` ### FRONT VIEW Render ```julia light = DistantLight( Vec3(1.0f0), 100.0f0, Vec3(1.0f0, 1.0f0, 0.0f0) ) cam = Camera( Vec3(10.0f0, 2.0f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), Vec3(0.0f0, 1.0f0, 0.0f0), 45.0f0, 1.0f0, screen_size... ) generate_render_and_save(cam, light, "teapot_front.jpg") ``` ```@raw html <p align="center"> <img width=256 height=256 src="../../assets/teapot_front.jpg"> </p> ``` ## Next Steps * Try Rendering complex environments with RayTracer * Look into the other examples in `examples/` * Read about inverse rendering and see the examples on that *This page was generated using [Literate.jl](https://github.com/fredrikekre/Literate.jl).*
RayTracer
https://github.com/avik-pal/RayTracer.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
462
using Documenter, HeatTransferFluids makedocs( modules = [HeatTransferFluids], sitename = "HeatTransferFluids.jl", pages = Any[ "HeatTransferFluids.jl"=>"index.md", "API references"=>Any[ "api/fluid.md", "api/structures.md", "api/flow.md", "api/pressure_drop.md", "api/heat_transfer.md", ], ], ) deploydocs(repo = "github.com/ryd-yb/HeatTransferFluids.jl.git")
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
199
module HeatTransferFluids using DynamicQuantities include("fluid.jl") include("structure.jl") include("flow.jl") include("friction.jl") include("pressure_drop.jl") include("heat_transfer.jl") end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
3009
export reynolds_number, nusselt_number, prandtl_number, dean_number """ reynolds_number(f::Fluid, t::Tube) Computes the Reynolds number of a `fluid` flowing through a `tube`. # Arguments - `f::Fluid`: the fluid flowing through the tube - `t::Tube`: the tube through which the fluid flows # Returns - `Float`: the Reynolds number of the fluid flowing through the tube """ function reynolds_number(f::Fluid, t::Tube) ϱ = f.density v = f.velocity μ = f.viscosity D = t.diameter return ustrip(ϱ * v * D / μ) end function critical_reynolds_number(t::Tube) return 2300 end """ pressure_drop(h::Helix) Computes the critical Reynolds number for a Helix. See VDI Heat Atlas, p. 1062 to 1063 for details. # Arguments - `h::Helix`: the coiled tube through which the fluid flows # Returns - `DynamicQuantity.AbstractQuantity`: the pressure drop of the fluid flowing through the tube """ function critical_reynolds_number(h::Helix) Dw = h.diameter H = h.pitch D = Dw * (1 + (H / (π * Dw))^2) d = h.tube.diameter return ustrip(2300 * (1 + 8.6 * (d / D)^0.45)) end """ prandtl_number(f::Fluid) Computes the Prandtl number of a `fluid``. # Arguments - `f::Fluid`: the fluid # Returns - `Float`: the Prandtl number of the fluid """ function prandtl_number(f::Fluid) c = f.heat_capacity μ = f.viscosity k = f.thermal_conductivity return ustrip(c * μ / k) end """ nusselt_number(f::Fluid, t::Tube) Computes the Nusselt number of a `fluid` flowing through a `tube`. Depending on the regime (laminar or turbulent), different formula have to be used to compute the Nusselt number. For the intermediate region, we perform a linear interpolation between the laminar and turbulent regimes. See VDI Heat Atlas, p. 696 for details. # Arguments - `f::Fluid`: the fluid flowing through the tube - `t::Tube`: the tube through which the fluid flows # Returns - `Float`: the Nusselt number of the fluid flowing through the tube """ function nusselt_number(f::Fluid, t::Tube) Re = reynolds_number(f, t) γ = clamp((Re - 2300) / (1e4 - 2300), 0.0, 1.0) Nu_laminar = nusselt_number_laminar(f, t) Nu_turbulent = nusselt_number_turbulent(f, t) return (1 - γ) * Nu_laminar + γ * Nu_turbulent end function nusselt_number_laminar(f::Fluid, t::Tube) Re = reynolds_number(f, t) Pr = prandtl_number(f) λ = t.diameter / t.length Nu₁ = 4.354 Nu₂ = 1.953(Re * Pr * λ)^(1 / 3) Nu₃ = (0.924Pr)^(1 / 3) * (Re * λ)^(1 / 2) return (Nu₁^3 + 0.6^3 + (Nu₂ - 0.6)^3 + Nu₃^3)^(1 / 3) end function nusselt_number_turbulent(f::Fluid, t::Tube) Re = reynolds_number(f, t) Pr = prandtl_number(f) λ = t.diameter / t.length ξ = (1.8log10(Re) - 1.5)^(-2) return ((ξ / 8)Re * Pr) * (1 + λ^(2 / 3)) / (1 + 12.7(ξ / 8)^(1 / 2) * (Pr^(2 / 3) - 1)) end function dean_number(f::Fluid, b::Bend) Re = reynolds_number(f, b.tube) d = b.tube.diameter D = 2 * b.radius return Re * √(d / D) end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
2665
export Fluid, Water """ Fluid{T<:AbstractQuantity} A fluid with the important physical properties to be used in heat transfer calculations. # Fields - `density::T`: the density of the fluid - `velocity::T`: the velocity of the fluid - `viscosity::T`: the viscosity of the fluid - `heat_capacity::T`: the specific heat capacity of the fluid - `thermal_conductivity::T`: the thermal conductivity of the fluid - `temperature::T`: the temperature of the fluid """ struct Fluid{T<:AbstractQuantity} density::T velocity::T viscosity::T heat_capacity::T thermal_conductivity::T temperature::T function Fluid(; density::T, velocity::T, viscosity::T, heat_capacity::T, thermal_conductivity::T, temperature::T, ) where {T} @assert dimension(density) == dimension(u"kg/m^3") "density must have units of mass per volume" @assert dimension(velocity) == dimension(u"m/s") "velocity must have units of length per time" @assert dimension(viscosity) == dimension(u"Pa*s") "viscosity must have units of pressure times time" @assert dimension(heat_capacity) == dimension(u"J/(kg*K)") "heat_capacity must have units of energy per mass per temperature" @assert dimension(thermal_conductivity) == dimension(u"W/(m*K)") "thermal_conductivity must have units of power per length per temperature" @assert dimension(temperature) == dimension(u"K") "temperature must have units of temperature" @assert ustrip(density) > 0 "density must be positive" @assert ustrip(velocity) > 0 "velocity must be positive" @assert ustrip(viscosity) > 0 "viscosity must be positive" @assert ustrip(heat_capacity) > 0 "heat_capacity must be positive" @assert ustrip(thermal_conductivity) > 0 "thermal_conductivity must be positive" @assert ustrip(temperature) > 0 "temperature must be positive" new{T}(density, velocity, viscosity, heat_capacity, thermal_conductivity, temperature) end end """ Water Returns a Fluid with the properties of water close to room temperature. # Keywords - `velocity::AbstractQuantity`: the velocity of the water - `temperature::AbstractQuantity`: the temperature of the water # Returns - `Fluid`: the fluid with the properties of water close to room temperature at the given velocity and temperature """ Water(; velocity::AbstractQuantity, temperature::AbstractQuantity) = Fluid( density = 997u"kg/m^3", velocity = velocity, viscosity = 1e-3u"Pa*s", heat_capacity = 4186u"J/(kg*K)", thermal_conductivity = 0.591u"W/(m*K)", temperature = temperature, )
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
1651
""" pressure_drop(f::Fluid, t::Tube) Computes the friction coefficient of a `fluid` flowing through a `tube`. See VDI Heat Atlas, p. 1057 for details. # Arguments - `f::Fluid`: the fluid flowing through the tube - `t::Tube`: the tube through which the fluid flows # Keywords - `friction::Float`: the friction factor of the fluid flowing through the tube # Returns - `DynamicQuantities.AbstractQuantity`: the pressure drop of the fluid flowing through the tube """ function friction(f::Fluid, t::Tube) Re = reynolds_number(f, t) Re_c = critical_reynolds_number(t) # laminar regime if Re < Re_c return 64 / Re end # turbulent regime if Re > Re_c # Blasius equation if Re > 3000 && Re < 2e4 return 0.316 / Re^0.25 end # Hermann equation if Re > 2e4 && Re < 2e6 return 0.0054 + 0.3964 / Re^0.3 end end throw(DomainError(Re, "no analytical formula for flow regime")) end function friction(f::Fluid, b::Bend) De = dean_number(f, b) ξ = friction(f, b.tube) # laminar flow as in straight tube if De < 11.6 return ξ end # laminar flow with additional friction if De >= 11.6 && De <= 2000 return ξ / (1 - (1 - (11.6 / De)^0.45)^(1 / 0.45)) end r = b.tube.diameter / 2 R = b.radius # turbulent flow Re_c = critical_reynolds_number(b.tube) * 7.5 * (r / R)^0.25 Re = reynolds_number(f, b.tube) if Re > Re_c return (r / R)^0.5 * (0.003625 + 0.038 * (Re * (r / R)^2)^-0.25) end throw(DomainError(De, "no analytical formula for flow regime")) end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
529
export heat_transfer """ heat_transfer(f::Fluid, t::Tube) Computes the heat transfer coefficient of a `fluid`` flowing through a `tube`. # Arguments - `f::Fluid`: the fluid flowing through the tube - `t::Tube`: the tube through which the fluid flows # Returns - `DynamicQuantity.AbstractQuantity`: the heat transfer coefficient of the fluid flowing through the tube """ function heat_transfer(f::Fluid, t::Tube) k = f.thermal_conductivity D = t.diameter Nu = nusselt_number(f, t) return Nu * (k / D) end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
2920
export pressure_drop """ pressure_drop(f::Fluid, t::Tube[; friction]) Computes the pressure drop of a `fluid` flowing through a `tube` with a particular `friction`. See VDI Heat Atlas, p. 1057 for details. # Arguments - `f::Fluid`: the fluid flowing through the tube - `t::Tube`: the tube through which the fluid flows # Keywords - `friction::Float`: the friction factor of the fluid flowing through the tube # Returns - `DynamicQuantities.AbstractQuantity`: the pressure drop of the fluid flowing through the tube """ function pressure_drop(f::Fluid, t::Tube; friction = friction(f,t)) Re = reynolds_number(f, t) L = t.length d = t.diameter ρ = f.density u = f.velocity ξ = friction return uconvert(us"bar", ξ * (L / d) * (ρ * u^2 / 2)) end """ pressure_drop(f::Fluid, h::Helix) Computes the pressure drop of a `fluid` flowing through a `helix`. # Arguments - `f::Fluid`: the fluid flowing through the tube - `h::Helix`: the helix through which the fluid flows # Returns - `DynamicQuantity.AbstractQuantity`: the pressure drop of the fluid flowing through the tube """ function pressure_drop(f::Fluid, h::Helix) Dw = h.diameter H = h.pitch D = Dw * (1 + (H / (π * Dw))^2) d = h.tube.diameter Re = reynolds_number(f, h.tube) Re_crit = critical_reynolds_number(h) if 1 < (Re * sqrt(d / D)) < (Re_crit * sqrt(d / D)) ξ = (64 / Re) * (1 + 0.033(log10(Re * sqrt(d / D)))^4.0) else ξ = (0.3164 / Re^(1 / 4)) * (1 + 0.095sqrt(d / D) * Re^(1 / 4)) end return pressure_drop(f, h.tube, friction = ξ) end """ pressure_drop(f::Fluid, v::Valve) Computes the pressure drop of a `fluid` flowing through a `valve`. # Arguments - `f::Fluid`: the fluid flowing through the tube - `v::Valve`: the valve through which the fluid flows # Returns - `DynamicQuantity.AbstractQuantity`: the pressure drop of the fluid flowing through the tube """ # https://en.wikipedia.org/wiki/Flow_coefficient function pressure_drop(f::Fluid, v::Valve) Q = uconvert(us"m^3/hr", v.flow_rate) Kv = uconvert(us"m^3/hr", v.flow_factor) ρ = f.density ρ₀ = 1000u"kg/m^3" p₀ = 1u"bar" return p₀ * (Q / Kv)^2 * ρ / ρ₀ end """ pressure_drop(f::Fluid, b::Bend) Computes the pressure drop of a `fluid` flowing through a `bend`. So far, we only support 90-degree bends, see Spedding, P.L., Bernard, E. and McNally, G.M., ‘Fluid flow through 90 degree bends’, Dev. Chem. Eng Mineral Process, 12: 107–128, 2004. # Arguments - `f::Fluid`: the fluid flowing through the tube - `b::Bend`: the valve through which the fluid flows # Returns - `DynamicQuantity.AbstractQuantity`: the pressure drop of the fluid flowing through the tube """ function pressure_drop(f::Fluid, b::Bend) @assert b.angle == 90u"deg" "only 90-degree bends are supported at the moment" return pressure_drop(f, b.tube; friction=friction(f, b)) end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
2982
export Structure, Tube, Helix, Valve, Bend, Elbow """ Structure A structure is an element through which a fluid flows. """ abstract type Structure end """ Tube{T<:AbstractQuantity} A tube with a diameter and length through which a fluid flows. # Fields - `diameter::T`: the diameter of the tube - `length::T`: the length of the tube """ struct Tube{T<:AbstractQuantity} <: Structure diameter::T length::T function Tube(; diameter::T, length::T) where {T} @assert dimension(diameter) == dimension(u"m") "diameter must have units of length" @assert dimension(length) == dimension(u"m") "length must have units of length" @assert ustrip(diameter) > 0 "diameter must be positive" @assert ustrip(length) > 0 "length must be positive" new{T}(diameter, length) end end """ Helix{T<:Tube,V<:AbstractQuantity} A tube in the shape of a helix with a diameter and pitch. # Fields - `tube::T`: the tube that is coiled - `diameter::V`: the diameter of the coil - `pitch::V`: the pitch of the coil """ struct Helix{T<:Tube,V<:AbstractQuantity} <: Structure tube::T diameter::V pitch::V function Helix(t::T; diameter::V, pitch::V) where {T,V} @assert dimension(diameter) == dimension(u"m") "diameter must have units of length" @assert dimension(pitch) == dimension(u"m") "pitch must have units of length" @assert ustrip(diameter) > 0 "diameter must be positive" @assert ustrip(pitch) > 0 "pitch must be positive" new{T,V}(t, diameter, pitch) end end """ Valve{T<:AbstractQuantity} A valve parametrized by a flow rate and flow factor. # Fields - `flow_rate::T`: the flow rate of the valve - `flow_factor::T`: the flow factor of the valve """ struct Valve{T<:AbstractQuantity} <: Structure flow_rate::T flow_factor::T function Valve(; flow_rate::T, flow_factor::T) where {T} @assert dimension(flow_rate) == dimension(u"m^3/s") "flow_rate must have units of volume per time" @assert dimension(flow_factor) == dimension(u"m^3/s") "flow_factor must have units of volume per time" @assert ustrip(flow_rate) > 0 "flow_rate must be positive" @assert ustrip(flow_factor) > 0 "flow_factor must be positive" new{T}(flow_rate, flow_factor) end end struct Bend{T<:AbstractQuantity} <: Structure tube::Tube radius::T angle::T function Bend(tube::Tube; radius::T, angle::T) where {T} @assert dimension(radius) == dimension(u"m") "radius must have units of length" @assert dimension(angle) == dimension(u"rad") "angle must have units of angle" @assert ustrip(radius) > 0 "radius must be positive" @assert angle > 0u"deg" "angle must be positive" @assert angle < 180u"deg" "angle must be less than 180 degrees" new{T}(tube, radius, angle) end end Elbow(tube::Tube; radius::AbstractQuantity) = Bend(tube, radius = radius, angle = π / 2u"rad")
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
588
@testset "Flow" begin fluid = Water(velocity = 0.58u"m/s", temperature = 293.15u"K") tube = Tube(diameter = 2.7u"mm", length = 9.5153u"m") @testset "reynolds_number" begin @test reynolds_number(fluid, tube) ≈ 1561 atol = 1 end @testset "prandtl_number" begin @test prandtl_number(fluid) ≈ 7 atol = 1 end @testset "nusselt_number" begin @test nusselt_number(fluid, tube) ≈ 5 atol = 1 end @testset "dean_number" begin @test dean_number(fluid, Elbow(tube, radius = 10u"mm")) ≈ 1561 * √(2.7 / 20) atol = 1 end end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
323
@testset "Fluid" begin @test Water(velocity = 1u"m/s", temperature = 293.15u"K") == Fluid( density = 997u"kg/m^3", velocity = 1u"m/s", viscosity = 1e-3u"Pa*s", heat_capacity = 4186u"J/(kg*K)", thermal_conductivity = 0.591u"W/(m*K)", temperature = 293.15u"K", ) end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
294
@testset "heat_transfer" begin fluid = Water(velocity = 3u"m/s", temperature = 293.15u"K") tube = Tube(diameter = 2.7u"mm", length = 14u"m") #coil = Coil(tube; diameter = 95u"mm", pitch = 5.2u"mm") @test heat_transfer(fluid, tube) ≈ 12u"kW/(K*m^2)" atol = 1u"kW/(K*m^2)" end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
895
@testset "pressure_drop" begin fluid = Water(velocity = 0.58u"m/s", temperature = 293.15u"K") tube = Tube(diameter = 2.7u"mm", length = 9.5153u"m") @testset "tube" begin @test pressure_drop(fluid, tube) ≈ 0.25u"bar" atol = 0.01u"bar" @test pressure_drop(Water(velocity = 3u"m/s", temperature = 262.15u"K"), Tube(diameter = 5u"mm", length = 1u"m")) ≈ 0.25u"bar" atol = 0.3u"bar" end @testset "coil" begin @test pressure_drop(fluid, Helix(tube, diameter = 63.1u"mm", pitch = 2.6u"mm")) ≈ 0.56u"bar" atol = 0.01u"bar" end @testset "valve" begin @test pressure_drop(fluid, Valve(flow_rate = 62u"L/hr", flow_factor = 1.5u"m^3/hr")) ≈ 0.0017u"bar" atol = 0.0001u"bar" end @testset "bend" begin @test pressure_drop(fluid, Elbow(tube, radius = 10u"mm")) ≈ 0.7u"bar" atol = 0.1u"bar" end end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
180
using HeatTransferFluids using Test using DynamicQuantities include("fluid.jl") include("structure.jl") include("flow.jl") include("pressure_drop.jl") include("heat_transfer.jl")
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
code
1418
@testset "Structure" begin tube = Tube(diameter = 2.7u"mm", length = 9u"m") @testset "Tube" begin @test tube.diameter == 2.7u"mm" @test tube.length == 9u"m" end @testset "Helix" begin h = Helix(tube; diameter = 2.7u"mm", pitch = 9u"m") @test h.tube == tube @test h.diameter == 2.7u"mm" @test h.pitch == 9u"m" end @testset "Valve" begin v = Valve(flow_rate = 62u"L/hr", flow_factor = 1.5u"m^3/hr") @test v.flow_rate == 62u"L/hr" @test v.flow_factor == 1.5u"m^3/hr" @test_throws AssertionError Valve(flow_rate = 0u"L/hr", flow_factor = 1.5u"m^3/hr") @test_throws AssertionError Valve(flow_rate = 10u"L/hr", flow_factor = 0u"m^3/hr") @test_throws AssertionError Valve(flow_rate = 10u"m/hr", flow_factor = 1.5u"m^3/hr") @test_throws AssertionError Valve(flow_rate = 10u"L/hr", flow_factor = 1.5u"m^2/hr") end @testset "Bend" begin t = Elbow(tube, radius = 10u"mm") @test t.tube == tube @test t.radius == 10u"mm" @test t.angle == 90u"deg" @test_throws AssertionError Elbow(tube, radius = 0u"mm") @test_throws AssertionError Elbow(tube, radius = -10u"mm") @test_throws AssertionError Bend(tube, radius = 10u"m", angle = 0u"deg") @test_throws AssertionError Bend(tube, radius = 10u"m", angle = 180u"deg") end end
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
docs
866
# HeatTransferFluids.jl | **Build Status** | **Code Coverage** | |:-----------------------------------------:|:-------------------------------:| | [![][CI-img]][CI-url] | [![][codecov-img]][codecov-url] | HeatTransferFluids.jl is a Julia library that provides various types and functions for engineering heat transfer with fluids. ## Installation ```julia using Pkg Pkg.add("https://github.com/ryd-yb/HeatTransferFluids.jl") ``` ## Usage See the tests in `test`. [CI-img]: https://github.com/ryd-yb/HeatTransferFluids.jl/actions/workflows/CI.yml/badge.svg [CI-url]: https://github.com/ryd-yb/HeatTransferFluids.jl/actions/workflows/CI.yml [codecov-img]: https://codecov.io/gh/ryd-yb/HeatTransferFluids.jl/branch/main/graph/badge.svg?token=CNF55N4HDZ [codecov-url]: https://codecov.io/gh/ryd-yb/HeatTransferFluids.jl
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
docs
222
# HeatTransferFluids.jl HeatTransferFluids.jl is a Julia library that provides various types and functions for engineering heat transfer with fluids. ## Installation ```julia using Pkg; Pkg.add("HeatTransferFluids") ```
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
docs
152
# Flow ```@docs HeatTransferFluids.reynolds_number ``` ```@docs HeatTransferFluids.prandtl_number ``` ```@docs HeatTransferFluids.nusselt_number ```
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
docs
85
# Fluid ```@docs HeatTransferFluids.Fluid ``` ```@docs HeatTransferFluids.Water ```
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
docs
63
# Heat transfer ```@docs HeatTransferFluids.heat_transfer ```
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
docs
63
# Pressure drop ```@docs HeatTransferFluids.pressure_drop ```
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
0.2.0
9b3895644c4ca9a43b8650f315c0526fee907f6f
docs
169
# Structure ```@docs HeatTransferFluids.Structure ``` ```@docs HeatTransferFluids.Tube ``` ```@docs HeatTransferFluids.Coil ``` ```@docs HeatTransferFluids.Valve ```
HeatTransferFluids
https://github.com/rydyb/HeatTransferFluids.jl.git
[ "MIT" ]
1.0.4
ecfe2e9a260c4723026b4a71460cf0420def9e40
code
290
module CircStats using Statistics,LinearAlgebra,Distributions,SpecialFunctions,HypothesisTests include("src.jl") # export all symbols for n in names(@__MODULE__, all=true) if Base.isidentifier(n) && n ∉ (nameof(@__MODULE__), :eval, :include) @eval export $n end end end
CircStats
https://github.com/circstat/CircStats.jl.git
[ "MIT" ]
1.0.4
ecfe2e9a260c4723026b4a71460cf0420def9e40
code
36679
""" Computes mean resultant vector length for circular data. 1. α: sample of angles in radians - w: number of incidences in case of binned angle data - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians - dims: compute along this dimension(default=1) return: mean resultant length """ function circ_r(α; w = ones(size(α)), d = 0, dims = 1) # compute weighted sum of cos and sin of angles r = sum(w .* cis.(α); dims) # obtain length r = abs.(r) ./ sum(w; dims) # for data with known spacing, apply correction factor to correct for bias in the estimation of r (see Zar, p. 601, equ. 26.16) if d != 0 c = d / 2 / sin(d / 2) r *= c end length(r) == 1 ? r[1] : r end """ Computes the mean direction for circular data. 1. α: sample of angles in radians - w: weightings in case of binned angle data - dims: compute along this dimension(default=1) return: - μ: mean direction - ul: upper 95% confidence limit - ll: lower 95% confidence limit """ function circ_mean(α; w = ones(size(α)), dims = 1) # compute weighted sum of cos and sin of angles r = sum(w .* cis.(α); dims) # obtain mean by μ = angle.(r) μ = length(μ) == 1 ? μ[1] : μ # confidence limits t = circ_confmean(α; xi = 0.05, w, d = 0, dims) ul = μ .+ t ll = μ .- t return (; μ, ul, ll) end """ Transforms p-axial data to a common scale. 1. α: sample of angles in radians 2. p: number of modes(default=1) return: transformed data """ circ_axial(α, p = 1) = mod2pi.(α * p) """ Computes the median direction for circular data. 1. α: sample of angles in radians return: median direction """ function circ_median(α::AbstractVector) α = mod2pi.(α) n = length(α) dd = circ_dist2(α) m1 = dropdims(count(>=(0), dd; dims = 1), dims = 1) m2 = dropdims(count(<=(0), dd; dims = 1), dims = 1) dm = abs.(m1 .- m2) m = minimum(dm) md = circ_mean(α[dm.==m]).μ αμ = circ_mean(α).μ if abs(circ_dist(αμ, md)) > abs(circ_dist(αμ, md + π)) md = mod2pi(md + π) end return md end """ Computes circular standard deviation for circular data (equ. 26.20, Zar). 1. α: sample of angles in radians - w: weightings in case of binned angle data - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians - dims: compute along this dimension(default=1) return: - s: angular deviation - s0: circular standard deviation """ function circ_std(α; w = ones(size(α)), d = 0, dims = 1) # compute mean resultant vector length r = circ_r(α; w, d, dims) s = sqrt.(2 .* (1 .- r)) # 26.20 s0 = sqrt.(-2 .* log.(r)) # 26.21 return (; s, s0) end """ Computes circular variance for circular data (equ. 26.17/18, Zar). 1. α: sample of angles in radians - w: number of incidences in case of binned angle data - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians - dims: compute along this dimension(default=1) return: - S: circular variance 1-r - s: angular variance 2(1-r) """ function circ_var(α; w = ones(size(α)), d = 0, dims = 1) # compute mean resultant vector length r = circ_r(α; w, d, dims) # apply transformation to var S = 1 .- r s = 2 * S return (; S, s) end """ Computes the confidence limits on the mean for circular data. 1. α: sample of angles in radians - xi: (1-xi) confidence limits are computed, default=0.05 - w: number of incidences in case of binned angle data - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians - dims: compute along this dimension(default=1) return: mean ± d yields upper/lower (1-xi)% confidence limit """ function circ_confmean(α; xi = 0.05, w = ones(size(α)), d = 0, dims = 1) # compute ingredients for conf. lim. r = circ_r(α; w, d, dims) n = sum(w; dims) R = n .* r c2 = quantile(Chisq(1), 1 - xi) # check for resultant vector length and select appropriate formula t = zeros(size(r)) for i = 1:length(r) if r[i] < 0.9 && r[i] > sqrt(c2 / 2 / n[i]) t[i] = sqrt((2 * n[i] * (2 * R[i]^2 - n[i] * c2)) / (4 * n[i] - c2)) # equ. 26.24 elseif r[i] >= 0.9 t[i] = sqrt(n[i]^2 - (n[i]^2 - R[i]^2) * exp(c2 / n[i])) # equ. 26.25 else t[i] = NaN @warn "Requirements for confidence levels not met." end end # apply final transform t = acos.(clamp.(t ./ R, -1, 1)) t = length(t) == 1 ? t[1] : t end """ Calculates a measure of angular skewness. 1. α: sample of angles in radians - w: weightings in case of binned angle data - dims: compute along this dimension(default=1) return: - b: skewness (from Pewsey) - b0: alternative skewness measure (from Fisher) """ function circ_skewness(α; w = ones(size(α)), dims = 1) # compute neccessary values R = circ_r(α; w, d = 0, dims) θ = circ_mean(α; w, dims).μ _, ρ₂, μ₂ = circ_moment(α; w, p = 2, cent = false, dims) # compute skewness if ndims(θ) > 0 θ₂ = repeat(θ, outer = Int.(size(α) ./ size(θ))) else θ₂ = θ end b = sum(w .* sin.(2 * circ_dist(α, θ₂)); dims) ./ sum(w; dims) b0 = ρ₂ .* sin.(circ_dist(μ₂, 2θ)) ./ (1 .- R) .^ (3 / 2) # (formula 2.29) b = length(b) == 1 ? b[1] : b b0 = length(b0) == 1 ? b0[1] : b0 return (; b, b0) end """ Calculates a measure of angular kurtosis. 1. α: sample of angles in radians - w: weightings in case of binned angle data - dims: compute along this dimension(default=1) return: - k: kurtosis (from Pewsey) - k0: kurtosis (from Fisher) """ function circ_kurtosis(α; w = ones(size(α)), dims = 1) # compute mean direction R = circ_r(α; w, d = 0, dims) θ = circ_mean(α; w, dims).μ _, ρ₂, _ = circ_moment(α; w, p = 2, cent = true, dims) _, _, μ₂ = circ_moment(α; w, p = 2, cent = false, dims) # compute skewness if ndims(θ) > 0 θ₂ = repeat(θ, outer = Int.(size(α) ./ size(θ))) else θ₂ = θ end k = sum(w .* cos.(2 * circ_dist(α, θ₂)); dims) ./ sum(w; dims) k0 = (ρ₂ .* cos.(circ_dist(μ₂, 2θ)) .- R .^ 4) ./ (1 .- R) .^ 2 # (formula 2.30) k = length(k) == 1 ? k[1] : k k0 = length(k0) == 1 ? k0[1] : k0 return (; k, k0) end """ Calculates the complex p-th centred or non-centred moment of the angular data in angle. 1. α: sample of angles in radians - w: number of incidences in case of binned angle data - p: p-th moment to be computed, default=1 - cent: if true, central moments are computed, default = false - dims: compute along this dimension(default=1) return: - mp: complex p-th moment - ρp: magnitude of the p-th moment - μp: angle of th p-th moment """ function circ_moment(α; w = ones(size(α)), p = 1, cent = false, dims = 1) if cent θ = circ_mean(α; w, dims).μ if ndims(θ) > 0 v = Int.(size(α) ./ size(θ)) θ = repeat(θ, outer = v) end α = circ_dist(α, θ) end n = size(α, dims) c̄ = sum(cos.(p * α) .* w; dims) / n s̄ = sum(sin.(p * α) .* w; dims) / n mp = c̄ .+ im * s̄ ρp = abs.(mp) μp = angle.(mp) mp = length(mp) == 1 ? mp[1] : mp ρp = length(ρp) == 1 ? ρp[1] : ρp μp = length(μp) == 1 ? μp[1] : μp return (; mp, ρp, μp) end """ Pairwise difference α-β around the circle computed efficiently. 1. α: sample of linear random variable 2. β: sample of linear random variable or one single angle return: matrix with differences """ circ_dist(α, β) = angle.(cis.(α) ./ cis.(β)) """ All pairwise difference α-β around the circle computed efficiently. 1. α: sample of linear random variable 2. β: sample of linear random variable return: matrix with pairwise differences """ circ_dist2(α) = circ_dist2(α, α) circ_dist2(α, β) = angle.(cis.(α) ./ cis.(β')) """ Computes descriptive statistics for circular data. 1. α: sample of angles in radians - w: weightings in case of binned angle data - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians return: descriptive statistics """ function circ_stats(α::AbstractVector; w = ones(size(α)), d = 0) # mean mean = circ_mean(α; w).μ # median median = circ_median(α) # variance var = circ_var(α; w, d) # standard deviation std, std0 = circ_std(α; w, d) # skewness skewness, skewness0 = circ_skewness(α; w) # kurtosis kurtosis, kurtosis0 = circ_kurtosis(α; w) return (; mean, median, var,std,std0, skewness,skewness0,kurtosis,kurtosis0) end """ Computes Rayleigh test for non-uniformity of circular data. H0: the population is uniformly distributed around the circle HA: the populatoin is not distributed uniformly around the circle Assumption: the distribution has maximally one mode and the data is sampled from a von Mises distribution! 1. α: sample of angles in radians - w: number of incidences in case of binned angle data - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians return: - p: p-value of Rayleigh's test - z: value of the z-statistic """ function circ_rtest(α; w = ones(size(α)), d = 0) r = circ_r(α; w, d) n = sum(w) # compute Rayleigh's R (equ. 27.1) R = n * r # compute Rayleigh's z (equ. 27.2) z = R^2 / n # compute p value using approxation in Zar, p. 617 p = exp(sqrt(1 + 4n + 4(n^2 - R^2)) - (1 + 2n)) return (; p, z) end """ Computes Omnibus or Hodges-Ajne test for non-uniformity of circular data. H0: the population is uniformly distributed around the circle HA: the population is not distributed uniformly around the circle Alternative to the Rayleigh and Rao's test. Works well for unimodal, bimodal or multimodal data. If requirements of the Rayleigh test are met, the latter is more powerful. 1. α: sample of angles in radians - sz: step size for evaluating distribution, default 1 degree - w: number of incidences in case of binned angle data return: - p: p-value - m: minimum number of samples falling in one half of the circle """ function circ_otest(α; sz = deg2rad(1), w = ones(size(α))) α = mod2pi.(α) n = sum(w) dg = 0:sz:π m1 = zeros(size(dg)) m2 = zeros(size(dg)) for i = 1:length(dg) m1[i] = sum((α .> dg[i]) .& (α .< π + dg[i]) .* w) m2[i] = n - m1[i] end m = min(minimum(m1), minimum(m2)) if n > 50 # approximation by Ajne (1968) A = π * sqrt(n) / 2 / (n - 2m) p = sqrt(2π) / A * exp(-π^2 / 8 / A^2) else # exact formula by Hodges (1955) # p = 2^(1-n) * (n-2m) * nchoosek(n,m) # revised below for numerical stability p = exp((1 - n) * log(2) + log(n - 2m) + loggamma(n + 1) - loggamma(m + 1) - loggamma(n - m + 1)) end return (; p, m) end """ Calculates Rao's spacing test by comparing distances between points on a circle to those expected from a uniform distribution. H0: Data is distributed uniformly around the circle. H1: Data is not uniformly distributed around the circle. Alternative to the Rayleigh test and the Omnibus test. Less powerful than the Rayleigh test when the distribution is unimodal on a global scale but uniform locally. Due to the complexity of the distributioin of the test statistic, we resort to the tables published by Russell, Gerald S. and Levitin, Daniel J.(1995) An expanded table of probability values for rao's spacing test, Communications in Statistics - Simulation and Computation Therefore the reported p-value is the smallest α level at which the test would still be significant. If the test is not significant at the α=0.1 level, we return the critical value for α = 0.05 and p = 0.5. 1. α: sample of angles in radians return: - p: smallest p-value at which test would be significant - u: computed value of the test-statistic u - UC: critical value of the test statistic at sig-level """ function circ_raotest(α) # for the purpose of the test, convert to angles α = sort(rad2deg.(α)) n = length(α) # compute test statistic u = 0 λ = 360 / n for j = 1:n-1 ti = α[j+1] - α[j] u += abs(ti - λ) end tn = 360 - α[n] + α[1] u = 0.5(u + abs(tn - λ)) getVal = (N, u) -> begin # Table II from Russel and Levitin, 1995 α = [0.001, 0.01, 0.05, 0.10] table = [ 4 247.32 221.14 186.45 168.02 5 245.19 211.93 183.44 168.66 6 236.81 206.79 180.65 166.30 7 229.46 202.55 177.83 165.05 8 224.41 198.46 175.68 163.56 9 219.52 195.27 173.68 162.36 10 215.44 192.37 171.98 161.23 11 211.87 189.88 170.45 160.24 12 208.69 187.66 169.09 159.33 13 205.87 185.68 167.87 158.50 14 203.33 183.90 166.76 157.75 15 201.04 182.28 165.75 157.06 16 198.96 180.81 164.83 156.43 17 197.05 179.46 163.98 155.84 18 195.29 178.22 163.20 155.29 19 193.67 177.08 162.47 154.78 20 192.17 176.01 161.79 154.31 21 190.78 175.02 161.16 153.86 22 189.47 174.10 160.56 153.44 23 188.25 173.23 160.01 153.05 24 187.11 172.41 159.48 152.68 25 186.03 171.64 158.99 152.32 26 185.01 170.92 158.52 151.99 27 184.05 170.23 158.07 151.67 28 183.14 169.58 157.65 151.37 29 182.28 168.96 157.25 151.08 30 181.45 168.38 156.87 150.80 35 177.88 165.81 155.19 149.59 40 174.99 163.73 153.82 148.60 45 172.58 162.00 152.68 147.76 50 170.54 160.53 151.70 147.05 75 163.60 155.49 148.34 144.56 100 159.45 152.46 146.29 143.03 150 154.51 148.84 143.83 141.18 200 151.56 146.67 142.35 140.06 300 148.06 144.09 140.57 138.71 400 145.96 142.54 139.50 137.89 500 144.54 141.48 138.77 137.33 600 143.48 140.70 138.23 136.91 700 142.66 140.09 137.80 136.59 800 142.00 139.60 137.46 136.33 900 141.45 139.19 137.18 136.11 1000 140.99 138.84 136.94 135.92] ridx = findfirst(table[:, 1] .>= N) cidx = findfirst(table[ridx, 2:end] .< u) if isnothing(cidx) UC = table[ridx, end-1] p = 0.5 else UC = table[ridx, cidx+1] p = α[cidx] end return p, UC end # get critical value from table p, UC = getVal(n, u) return (; p, u, UC) end """ Computes V test for non-uniformity of circular data with a specified mean direction. H0: the population is uniformly distributed around the circle HA: the population is not distributed uniformly around the circle but has a mean of `m`. !!!note Not rejecting H0 may mean that the population is uniformly distributed around the circle OR that it has a mode but that this mode is not centered at `m`. The V test has more power than the Rayleigh test and is preferred if there is reason to believe in a specific mean direction. 1. α: sample of angles in radians - m: suspected mean direction, default=0 - w: number of incidences in case of binned angle data - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians return: - p: p-value of V test - v: value of the V statistic """ function circ_vtest(α; m = 0, w = ones(size(α)), d = 0) # compute some ingredients r = circ_r(α; w, d) μ, = circ_mean(α; w) n = sum(w) # compute Rayleigh's R (equ. 27.1) R = n * r # compute the V statistic (equ. 27.5) v = R * cos(μ - m) # compute u (equ. 27.6) u = v * sqrt(2 / n) # compute p-value from one tailed normal approximation p = 1 - cdf(Normal(), u) return (; p, v) end """ Tests for significance of the median. H0: the population has median angle `md` HA: the population has not median angle `md` 1. α: sample of angles in radians - md: median to test, default=0 return: p-value """ function circ_medtest(α; md = 0) n = length(α) # compute deviations from median d = circ_dist(α, md) n1 = sum(d .< 0) n2 = sum(d .> 0) # compute p-value with binomial test sum(pdf.(Binomial(n, 0.5), [0:min(n1, n2); max(n1, n2):n])) end """ One-Sample test for the mean angle. H0: the population has mean `m`. HA: the population has not mean `m`. !!!note: This is the equvivalent to a one-sample t-test with specified mean direction. 1. α: sample of angles in radians - m: assumed mean direction, default=0 - w: number of incidences in case of binned angle data - d: spacing of bin centers for binned data, used to correct for bias in estimation of r, in radians - xi: alpha level of the test return: - h: false if H0 can not be rejected, true otherwise - μ: mean - ul: upper (1-xi) confidence level - ll: lower (1-xi) confidence level """ function circ_mtest(α; xi = 0.05, m = 0, w = ones(size(α)), d = 0) # compute ingredients μ, = circ_mean(α; w) t = circ_confmean(α; xi, w, d) ul = μ + t ll = μ - t # compute test via confidence limits (example 27.3) h = abs(circ_dist2(m, μ)) > t return (; h, μ, ul, ll) end """ Parametric Watson-Williams multi-sample test for equal means. Can be used as a one-way ANOVA test for circular data. H0: the s populations have equal means HA: the s populations have unequal means !!! note Use with binned data is only advisable if binning is finer than 10 deg. In this case, α is assumed to correspond to bin centers. The Watson-Williams two-sample test assumes underlying von-Mises distributrions. All groups are assumed to have a common concentration parameter k. 1. α: angles in radians 2. idx: indicates which population the respective angle in α comes from, 1:s - w: number of incidences in case of binned angle data return: - p: p-value of the Watson-Williams multi-sample test. Discard H0 if p is small. - F: F statistics """ function circ_wwtest(α, idx; w = ones(size(α))) # number of groups u = unique(idx) s = length(u) # number of samples n = sum(w) # compute relevant quantitites pn = zeros(s) pr = zeros(s) for t = 1:s pidx = idx .== u[t] pn[t] = sum(pidx .* w) pr[t] = circ_r(α[pidx]; w = w[pidx]) end r = circ_r(α; w) rw = sum(pn .* pr) / n # make sure assumptions are satisfied checkAssumption = (rw, n) -> begin if n >= 11 && rw < 0.45 @warn "Test not applicable. Average resultant vector length < 0.45." elseif n < 11 && n >= 7 && rw < 0.5 @warn "Test not applicable. Average number of samples per population 6 < x < 11 and average resultant vector length < 0.5." elseif n >= 5 && n < 7 && rw < 0.55 @warn "Test not applicable. Average number of samples per population 4 < x < 7 and average resultant vector length < 0.55." elseif n < 5 @warn "Test not applicable. Average number of samples per population < 5." end end checkAssumption(rw, mean(pn)) # test statistic kk = circ_kappa(rw) β = 1 + 3 / (8 * kk) # correction factor A = sum(pr .* pn) - r * n B = n - sum(pr .* pn) F = β * (n - s) * A / (s - 1) / B # p = 1 - fcdf(F, s - 1, n - s) p = 1 - cdf(FDist(s - 1, n - s), F) # fprintf('\nANALYSIS OF VARIANCE TABLE (WATSON-WILLIAMS TEST)\n\n'); # fprintf('%s\t\t\t\t%s\t%s\t\t%s\t\t%s\t\t\t%s\n', ' ' ,'d.f.', 'SS', 'MS', 'F', 'P-Value'); # fprintf('--------------------------------------------------------------------\n'); # fprintf('%s\t\t\t%u\t\t%.2f\t%.2f\t%.2f\t\t%.4f\n', 'Columns', s-1 , A, A/(s-1), F, pval); # fprintf('%s\t\t%u\t\t%.2f\t%.2f\n', 'Residual ', n-s, B, B/(n-s)); # fprintf('--------------------------------------------------------------------\n'); # fprintf('%s\t\t%u\t\t%.2f', 'Total ',n-1,A+B); # fprintf('\n\n') # table = ["Source",'d.f.','SS','MS','F','P-Value'; # 'Columns', s-1 , A, A/(s-1), F, pval; # 'Residual ', n-s, B, B/(n-s), [], []; # 'Total',n-1,A+B,[],[],[]] return (; p, F) end """ Parametric two-way ANOVA for circular data with interations. !!!note The test assumes underlying von-Mises distributrions. All groups are assumed to have a common concentration parameter k, between 0 and 2. 1. α: angles in radians 2. idp: indicates the level of factor 1 (1:p) 3. idq: indicates the level of factor 2 (1:q) - inter: whether to include effect of interaction - fn: string array containing names of the factors return: - p: pvalues for factors and interaction - s: statistic of each p value """ function circ_hktest(α, idp, idq; inter = true, fn = ['A', 'B']) # number of groups for every factor pu = unique(idp) p = length(pu) qu = unique(idq) q = length(qu) # number of samples n = length(α) # compute important sums for the test statistics cn = zeros(p, q) cr = zeros(p, q) pm = zeros(p) pr = zeros(p) pn = zeros(p) qm = zeros(q) qr = zeros(q) qn = zeros(q) for pp = 1:p p_id = idp .== pu[pp] # indices of factor1 = pp for qq = 1:q q_id = idq .== qu[qq] # indices of factor2 = qq idx = p_id .& q_id cn[pp, qq] = sum(idx) # number of items in cell cr[pp, qq] = cn[pp, qq] * circ_r(α[idx]) # R of cell end # R and mean angle for factor 1 pr[pp] = sum(p_id) * circ_r(α[p_id]) pm[pp] = circ_mean(α[p_id]).μ pn[pp] = sum(p_id) end # R and mean angle for factor 2 for qq = 1:q q_id = idq .== qu[qq] qr[qq] = sum(q_id) * circ_r(α[q_id]) qm[qq] = circ_mean(α[q_id]).μ qn[qq] = sum(q_id) end # R and mean angle for whole sample (total) tr = n * circ_r(α) # estimate kappa kk = circ_kappa(tr / n) # different formulas for different width of the distribution if kk > 2 # large kappa # effect of factor 1 eff_1 = sum(pr .^ 2 ./ dropdims(sum(cn, dims = 2), dims = 2)) - tr .^ 2 / n df_1 = p - 1 ms_1 = eff_1 / df_1 # effect of factor 2 eff_2 = sum(qr .^ 2 ./ dropdims(sum(cn, dims = 1), dims = 1)) - tr .^ 2 / n df_2 = q - 1 ms_2 = eff_2 / df_2 # total effect eff_t = n - tr .^ 2 / n df_t = n - 1 m = mean(cn) if inter # correction factor for improved F statistic β = 1 / (1 - 1 / (5kk) - 1 / (10kk^2)) # residual effects eff_r = n - sum(cr .^ 2 ./ cn) df_r = p * q * (m - 1) ms_r = eff_r / df_r # interaction effects eff_i = sum(cr .^ 2 ./ cn) - sum(qr .^ 2 ./ qn) - sum(pr .^ 2 ./ pn) + tr .^ 2 / n df_i = (p - 1) * (q - 1) ms_i = eff_i / df_i # interaction test statistic FI = ms_i / ms_r pI = 1 - cdf(FDist(df_i, df_r), FI) else # residual effect eff_r = n - sum(qr .^ 2 ./ qn) - sum(pr .^ 2 ./ pn) + tr .^ 2 / n df_r = (p - 1) * (q - 1) ms_r = eff_r / df_r # interaction effects eff_i = [] df_i = [] ms_i = [] # interaction test statistic FI = [] pI = NaN β = 1 end # compute all test statistics as F = β * MS(A) / MS(R) F1 = β * ms_1 / ms_r p1 = 1 - cdf(FDist(df_1, df_r), F1) F2 = β * ms_2 / ms_r p2 = 1 - cdf(FDist(df_2, df_r), F2) s = [F1, F2, FI] else # small kappa # correction factor rr = besseli(1, kk) / besseli(0, kk) f = 2 / (1 - rr^2) chi1 = f * (sum(pr .^ 2 ./ pn) - tr .^ 2 / n) df_1 = 2 * (p - 1) p1 = 1 - cdf(Chisq(df_1), chi1) chi2 = f * (sum(qr .^ 2 ./ qn) - tr .^ 2 / n) df_2 = 2 * (q - 1) p2 = 1 - cdf(Chisq(df_2), chi2) chiI = f * ( sum(cr .^ 2 ./ cn) - sum(pr .^ 2 ./ pn) - sum(qr .^ 2 ./ qn) + tr .^ 2 / n ) df_i = (p - 1) * (q - 1) pI = 1 - cdf(Chisq(df_i), chiI) s = [chi1, chi2, chiI] end p = [p1, p2, pI] # # if kk>2 # # fprintf('\nANALYSIS OF VARIANCE TABLE (HIGH KAPPA MODE)\n\n'); # # fprintf('%s\t\t\t\t%s\t%s\t\t%s\t\t%s\t\t\t%s\n', ' ' ,'d.f.', 'SS', 'MS', 'F', 'P-Value'); # fprintf('--------------------------------------------------------------------\n'); # fprintf('%s\t\t\t\t%u\t\t%.2f\t%.2f\t%.2f\t\t%.4f\n', fn{1}, df_1 , eff_1, ms_1, F1, p1); # fprintf('%s\t\t\t\t%u\t\t%.2f\t%.2f\t%.2f\t\t%.4f\n', fn{2}, df_2 , eff_2, ms_2, F2, p2); # if (inter) # fprintf('%s\t\t%u\t\t%.2f\t%.2f\t%.2f\t\t%.4f\n', 'Interaction', df_i , eff_i, ms_i, FI, pI); # end # fprintf('%s\t\t%u\t\t%.2f\t%.2f\n', 'Residual ', df_r, eff_r, ms_r); # fprintf('--------------------------------------------------------------------\n'); # fprintf('%s\t\t%u\t\t%.2f', 'Total ',df_t,eff_t); # fprintf('\n\n') # else # fprintf('\nANALYSIS OF VARIANCE TABLE (LOW KAPPA MODE)\n\n'); # # fprintf('%s\t\t\t\t%s\t%s\t\t\t%s\n', ' ' ,'d.f.', 'CHI2', 'P-Value'); # fprintf('--------------------------------------------------------------------\n'); # fprintf('%s\t\t\t\t%u\t\t%.2f\t\t\t%.4f\n', fn{1}, df_1 , chi1, p1); # fprintf('%s\t\t\t\t%u\t\t%.2f\t\t\t%.4f\n', fn{2}, df_2 , chi2, p2); # if (inter) # fprintf('%s\t\t%u\t\t%.2f\t\t\t%.4f\n', 'Interaction', df_i , chiI, pI); # end # fprintf('--------------------------------------------------------------------\n'); # fprintf('\n\n') # # end return (; p, s) end """ A parametric two-sample test to determine whether two concentration parameters are different. H0: The two concentration parameters are equal. HA: The two concentration parameters are different. Assumptions: both samples are drawn from von Mises type distributions and their joint resultant vector length should be > .7 1. α₁: sample of angles in radians 2. α₂: sample of angles in radians return: - p: p-value that samples have different concentrations - f: f-statistic calculated """ function circ_ktest(α₁, α₂) n1 = length(α₁) n2 = length(α₂) R1 = n1 * circ_r(α₁) R2 = n2 * circ_r(α₂) # make sure that r̄ > .7 r̄ = (R1 + R2) / (n1 + n2) if r̄ < 0.7 @warn "Resultant vector length should be > 0.7" end # calculate test statistic f = ((n2 - 1) * (n1 - R1)) / ((n1 - 1) * (n2 - R2)) if f > 1 p = 2 * (1 - cdf(FDist(n1, n2), f)) else f = 1 / f p = 2 * (1 - cdf(FDist(n2, n1), f)) end return (; p, f) end """ Tests for symmetry about the median. H0: the population is symmetrical around the median HA: the population is not symmetrical around the median 1. α: sample of angles in radians return: p-value """ function circ_symtest(α) # compute median md = circ_median(α) # compute deviations from median d = circ_dist(α, md) # compute wilcoxon sign rank test pvalue(SignedRankTest(d)) end const kuipertable= [5 1.45800000000000 1.56500000000000 1.68200000000000 1.76300000000000 1.83800000000000 1.92000000000000 1.97000000000000; 6 1.47100000000000 1.58200000000000 1.71100000000000 1.79300000000000 1.86700000000000 1.95700000000000 2.02000000000000; 7 1.48300000000000 1.59800000000000 1.72700000000000 1.81400000000000 1.89400000000000 1.98700000000000 2.05100000000000; 8 1.49300000000000 1.60800000000000 1.74100000000000 1.83000000000000 1.91100000000000 2.00900000000000 2.07700000000000; 9 1.50000000000000 1.61800000000000 1.75200000000000 1.84300000000000 1.92600000000000 2.02700000000000 2.09700000000000; 10 1.50700000000000 1.62500000000000 1.76100000000000 1.85400000000000 1.93800000000000 2.04100000000000 2.11300000000000; 11 1.51300000000000 1.63100000000000 1.76900000000000 1.86200000000000 1.94800000000000 2.05300000000000 2.12600000000000; 12 1.51700000000000 1.63700000000000 1.77600000000000 1.87000000000000 1.95700000000000 2.06200000000000 2.13700000000000; 13 1.52200000000000 1.64200000000000 1.78200000000000 1.87600000000000 1.96400000000000 2.07100000000000 2.15400000000000; 14 1.52500000000000 1.64600000000000 1.78700000000000 1.88200000000000 1.97000000000000 2.07800000000000 2.15400000000000; 15 1.52900000000000 1.65000000000000 1.79100000000000 1.88700000000000 1.97600000000000 2.08500000000000 2.16100000000000; 16 1.53200000000000 1.65300000000000 1.79500000000000 1.89200000000000 1.98100000000000 2.09000000000000 2.16800000000000; 17 1.53400000000000 1.65700000000000 1.79900000000000 1.89600000000000 1.98600000000000 2.09600000000000 2.17300000000000; 18 1.53700000000000 1.65900000000000 1.80200000000000 1.89900000000000 1.99000000000000 2.10000000000000 2.17800000000000; 19 1.53900000000000 1.66200000000000 1.80500000000000 1.90300000000000 1.99300000000000 2.10400000000000 2.18300000000000; 20 1.54100000000000 1.66400000000000 1.80800000000000 1.90600000000000 1.99700000000000 2.10800000000000 2.18700000000000; 21 1.54300000000000 1.66700000000000 1.81000000000000 1.90800000000000 2 2.11200000000000 2.19100000000000; 22 1.54500000000000 1.66900000000000 1.81300000000000 1.91100000000000 2.00300000000000 2.11500000000000 2.19400000000000; 23 1.54700000000000 1.67000000000000 1.81500000000000 1.91300000000000 2.00500000000000 2.11800000000000 2.19800000000000; 24 1.54900000000000 1.67200000000000 1.81700000000000 1.91600000000000 2.00800000000000 2.12100000000000 2.20100000000000; 25 1.55000000000000 1.67400000000000 1.81900000000000 1.91800000000000 2.01000000000000 2.12300000000000 2.20300000000000; 30 1.55600000000000 1.68100000000000 1.82600000000000 1.92600000000000 2.01900000000000 2.13400000000000 2.21500000000000; 35 1.56100000000000 1.68600000000000 1.83200000000000 1.93300000000000 2.02600000000000 2.14100000000000 2.22300000000000; 40 1.56500000000000 1.69000000000000 1.83700000000000 1.93800000000000 2.03200000000000 2.14800000000000 2.23000000000000; 45 1.56800000000000 1.69400000000000 1.84100000000000 1.94200000000000 2.03600000000000 2.15200000000000 2.23500000000000; 50 1.57100000000000 1.69700000000000 1.84400000000000 1.94600000000000 2.04000000000000 2.15700000000000 2.23900000000000; 100 1.58800000000000 1.71400000000000 1.86200000000000 1.96500000000000 2.06000000000000 2.17800000000000 2.26200000000000; 200 1.60000000000000 1.72600000000000 1.87600000000000 1.97900000000000 2.07500000000000 2.19400000000000 2.27900000000000; 500 1.61000000000000 1.73700000000000 1.88700000000000 1.99000000000000 2.08700000000000 2.20700000000000 2.29200000000000; 501 1.62000000000000 1.74700000000000 1.89800000000000 2.00100000000000 2.09800000000000 2.21800000000000 2.30300000000000] """ The Kuiper two-sample test tests whether the two samples differ significantly. The difference can be in any property, such as mean location and dispersion. It is a circular analogue of the Kolmogorov-Smirnov test. H0: The two distributions are identical. HA: The two distributions are different. 1. α₁: sample of angles in radians 2. α₂: sample of angles in radians - n: resolution at which the cdf are evaluated return: - p: p-value; the smallest of .10, .05, .02, .01, .005, .002, .001, for which the test statistic is still higher than the respective critical value. this is due to the use of tabulated values. if p>.1, pval is set to 1. - k: test statistic - K: critical value """ function circ_kuipertest(α₁, α₂; n = 100) n = length(α₁) m = length(α₂) # create cdfs of both samples ϕ₁, cdf1 = circ_samplecdf(α₁; n) _, cdf2 = circ_samplecdf(α₂; n) # maximal difference between sample cdfs dplus, gdpi = findmax([0; cdf1 .- cdf2]) dminus, gdmi = findmax([0; cdf2 .- cdf1]) # calculate k-statistic k = n * m * (dplus + dminus) # find p-value p, K = kuiperlookup(min(n, m), k / sqrt(n * m * (n + m))) K *= sqrt(n * m * (n + m)) return (; p, k, K) end function kuiperlookup(n, k) α = [0.10, 0.05, 0.02, 0.01, 0.005, 0.002, 0.001] nn = kuipertable[:, 1] # find correct row of the table row = findfirst(n.==nn) if isnothing(row) # find closest value if no entry is present row = length(nn) - sum(n .< nn) if row == 0 error("n too small.") else @warn "n=$n not found in table, using closest n=$(nn[row]) present." end end # find minimal p-value and test-statistic idx = findlast(kuipertable[row, 2:end] .< k) if isnothing(idx) p = 1 K = NaN else p = α[idx] K = kuipertable[row, idx+1] end return (; p, K) end """ Circular correlation coefficient for two circular random variables. 1. α₁: sample of angles in radians 2. α₂: sample of angles in radians return: - ρ: correlation coefficient - p: p-value """ function circ_corrcc(α₁, α₂) # compute mean directions n = length(α₁) ᾱ₁ = circ_mean(α₁).μ ᾱ₂ = circ_mean(α₂).μ # compute correlation coeffcient from p. 176 num = sum(sin.(α₁ .- ᾱ₁) .* sin.(α₂ .- ᾱ₂)) den = sqrt(sum(sin.(α₁ .- ᾱ₁) .^ 2) .* sum(sin.(α₂ .- ᾱ₂) .^ 2)) ρ = num / den # compute pvalue l20 = mean(sin.(α₁ .- ᾱ₁) .^ 2) l02 = mean(sin.(α₂ .- ᾱ₂) .^ 2) l22 = mean((sin.(α₁ .- ᾱ₁) .^ 2) .* (sin.(α₂ .- ᾱ₂) .^ 2)) ts = sqrt((n * l20 * l02) / l22) * ρ p = 2 * (1 - cdf(Normal(), abs(ts))) return (; ρ, p) end """ Correlation coefficient between one circular and one linear random variable. 1. α: sample of angles in radians 2. x: sample of linear random variable return: - ρ: correlation coefficient - p: p-value """ function circ_corrcl(α, x) n = length(α) # compute correlation coefficent for sin and cos independently rxs = cor(x, sin.(α)) rxc = cor(x, cos.(α)) rcs = cor(sin.(α), cos.(α)) # compute angular-linear correlation (equ. 27.47) ρ = sqrt((rxc^2 + rxs^2 - 2 * rxc * rxs * rcs) / (1 - rcs^2)) # compute pvalue p = 1 - cdf(Chisq(2), n * ρ^2) return (; ρ, p) end """ Computes an approximation to the ML estimate of the concentration parameter kappa of the von Mises distribution. 1. α: angles in radians OR α is length resultant - w: number of incidences in case of binned angle data return: estimated value of kappa """ function circ_kappa(α; w = ones(size(α))) N = length(α) if N > 1 R = circ_r(α; w) else R = α end if R < 0.53 κ = 2R + R^3 + 5R^5 / 6 elseif R >= 0.53 && R < 0.85 κ = -0.4 + 1.39R + 0.43 / (1 - R) else κ = 1 / (R^3 - 4R^2 + 3R) end if N < 15 && N > 1 if κ < 2 κ = max(κ - 2 * (N * κ)^-1, 0) else κ = (N - 1)^3 * κ / (N^3 + N) end end κ end """ Performs a simple agglomerative clustering of angular data. 1. α: sample of angles in radians - k: number of clusters desired, default=2 return: - cid: cluster id for each entry of α - α: sorted angles, matched with cid - μ: mean direction of angles in each cluster """ function circ_clust(α; k = 2) n = length(α) n < k && error("Not enough data for clusters.") # prepare data cid = 1:n # main clustering loop num_unique = length(unique(cid)) while (num_unique > k) # find centroid means... # calculate the means for each putative cluster μ = fill(NaN, n) for j = 1:n if sum(cid .== j) > 0 μ[j], = circ_mean(α(cid .== j)) end end # find distance between centroids... μdist = abs.(circ_dist2(μ)) # find closest pair of clusters/datapoints mindist = minimum(μdist[tril(ones(size(μdist), size(μdist)), -1)==1]) row, col = findall(μdist .== mindist) # update cluster id's cid[cid.==maximum(row)] = minimum(col) # update stop criteria num_unique = length(unique(cid)) end # renumber cluster ids (so cids [1 3 7 10] => [1 2 3 4]) cid2 = deepcopy(cid) uniquecids = unique(cid) for j = 1:length(uniquecids) cid[cid2.==uniquecids[j]] = j end # compute final cluster means μ = fill(NaN, num_unique) for j = 1:num_unique if sum(cid .== j) > 0 μ[j], = circ_mean(α[cid.==j]') end end return (; cid, α, μ) end """ Helper function for circ_kuipertest. Evaluates CDF of sample. 1. α: sample of angles in radians - n: resolution at which the cdf are evaluated return: - ϕ: angles at which CDF are evaluated - c: CDF values at ϕ """ function circ_samplecdf(α; n = 100) ϕ = range(0, 2π, length = n + 1) # ensure all points in α are on interval [0, 2pi) α = sort(mod2pi.(α)) dp = 1 / length(α) # incremental change in probability c = cumsum(map((l, r) -> dp * sum(l .<= α .< r), ϕ[1:end-1], ϕ[2:end])) ϕ = ϕ[1:end-1] return (; ϕ, c) end
CircStats
https://github.com/circstat/CircStats.jl.git
[ "MIT" ]
1.0.4
ecfe2e9a260c4723026b4a71460cf0420def9e40
code
3672
using Test, CircStats @testset "CircStats" begin av = [0:0.2:π;0.4π:0.05:0.6π;π:0.4:2π] am = [av av] aa = [am;;;am] wv = [0:0.1:0.5π;0.4π:0.05:0.6π;0:0.2:0.5π] wm = [wv wv] wa = [wm;;;wm] d = 0.1 @test circ_r(av) ≈ 0.481125184946105 @test circ_r(av;w=wv) ≈ 0.634569454038054 @test circ_r(av;w=wv,d) ≈ 0.634833935115386 circ_r(am) circ_r(am;w=wm) circ_r(am;w=wm,d) circ_r(am;w=wm,d,dims=2) circ_r(aa) circ_r(aa;w=wa) circ_r(aa;w=wa,d) circ_r(aa;w=wa,d,dims=3) μ, ul, ll = circ_mean(av) @test μ ≈ 1.568889360630885 @test ul ≈ 2.037005335388447 @test ll ≈ 1.100773385873324 μ, ul, ll = circ_mean(av;w=wv) @test μ ≈ 1.691236041279729 @test ul ≈ 2.018457532767024 @test ll ≈ 1.364014549792434 circ_mean(am) circ_mean(am;w=wm) circ_mean(aa) circ_mean(aa;w=wa) @test circ_median(av) ≈ 1.556637061435917 s, s0 = circ_std(av) @test s ≈ 1.018699970603607 @test s0 ≈ 1.209651009981690 circ_std(am) circ_std(am;dims=2) circ_std(aa) circ_std(am;dims=3) S, s = circ_var(av) @test S ≈ 0.518874815053895 @test s ≈ 1.037749630107790 circ_var(am) circ_var(am;dims=2) circ_var(aa) circ_var(am;dims=3) α = [1,2,3];β=[2,3,4] circ_dist(α,π) circ_dist(α,β) circ_dist2(α) circ_dist2(α,β) mp, ρp, μp = circ_moment(av) @test mp ≈ 0.000917488892268 + 0.481124310135703im @test ρp ≈ 0.481125184946105 @test μp ≈ 1.568889360630885 mp, ρp, μp = circ_moment(av;cent=true) @test mp ≈ 0.481125184946105 - 0.000000000000000im @test ρp ≈ 0.481125184946105 @test μp ≈ 3.741981750042832e-17 atol=1e-16 mp, ρp, μp = circ_moment(am) mp, ρp, μp = circ_moment(am;cent=true) b, b0 = circ_skewness(av) @test b ≈ -0.005585405160200 @test b0 ≈ -0.014943791328267 b, b0 = circ_skewness(am) k, k0 = circ_kurtosis(av) @test k ≈ 0.315477455279792 @test k0 ≈ 0.972747287142949 k, k0 = circ_kurtosis(am) circ_stats(av) p,z = circ_rtest(av) @test p ≈ 1.247327496731614e-04 @test z ≈ 8.564813412808679 p,m = circ_otest(av) @test p ≈ 0.003445833222941 @test m ≈ 7 idx = [fill(1,18);fill(2,19)] p,F = circ_wwtest(av,idx) @test p ≈ 0.489205605248093 @test F ≈ 0.488523443700675 idp = [repeat([1,2,3,4],outer=9);1] idq = [repeat([1,2],outer=18);1] p,s = circ_hktest(av,idp,idq) @test p[1] ≈ 0.988563843496855 @test p[2] ≈ 0.865090769456459 @test isnan(p[3]) @test s[1] ≈ 0.917000658130361 @test s[2] ≈ 0.289841683535636 @test isnan(s[3]) p,f = circ_ktest(av,reverse(av)) @test p ≈ 0.999999999999993 @test f ≈ 1 p = circ_symtest(av) # @test p ≈ 0.850454511827570 # diff in signrank in matlab? p,k,K=circ_kuipertest(av,reverse(av)) @test p ≈ 1 @test k ≈ 0 p, u, UC = circ_raotest(av) @test p ≈ 0.5 @test u ≈ 121.1858500639162 @test UC ≈ 153.82 p, v = circ_vtest(av) @test p ≈ 0.496851365629160 @test v ≈ 0.033947089013911 p = circ_medtest(av) @test p ≈ .0004719867429230360 h, μ, ul, ll = circ_mtest(av) @test h @test μ ≈ 1.568889360630885 @test ul ≈ 2.037005335388447 @test ll ≈ 1.100773385873324 ρ,p = circ_corrcc(av,reverse(av)) @test ρ ≈ 0.204639214081096 @test p ≈ 0.187332538620452 ρ,p = circ_corrcl(av,reverse(av)) @test ρ ≈ 0.591325482630456 @test p ≈ 0.001551058328371 @test circ_kappa(av) ≈ 1.095105628679724 ϕ,c = circ_samplecdf(av,n=8) @test ϕ[4] ≈ 2.356194490192345 @test c[4] ≈ 0.783783783783784 end
CircStats
https://github.com/circstat/CircStats.jl.git
[ "MIT" ]
1.0.4
ecfe2e9a260c4723026b4a71460cf0420def9e40
docs
149
# CircStats This package is a straight forward translation of the [CircStat](https://github.com/circstat/circstat-matlab) MATLAB toolbox for Julia.
CircStats
https://github.com/circstat/CircStats.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
1675
module GLTF using JSON3, StructTypes, PrecompileTools export load, save # constants const ARRAY_BUFFER = 34962 const ELEMENT_ARRAY_BUFFER = 34963 const BYTE = 5120 const UNSIGNED_BYTE = 5121 const SHORT = 5122 const UNSIGNED_SHORT = 5123 const UNSIGNED_INT = 5125 const FLOAT = 5126 const POINTS = 0 const LINES = 1 const LINE_LOOP = 2 const LINE_STRIP = 3 const TRIANGLES = 4 const TRIANGLE_STRIP = 5 const TRIANGLE_FAN = 6 const NEAREST = 9728 const LINEAR = 9729 const NEAREST_MIPMAP_NEAREST = 9984 const LINEAR_MIPMAP_NEAREST = 9985 const NEAREST_MIPMAP_LINEAR = 9986 const LINEAR_MIPMAP_LINEAR = 9987 const CLAMP_TO_EDGE = 33071 const MIRRORED_REPEAT = 33648 const REPEAT = 10497 include("zvector.jl") include("accessor.jl") include("animation.jl") include("asset.jl") include("buffer.jl") include("bufferView.jl") include("camera.jl") include("image.jl") include("material.jl") include("mesh.jl") include("node.jl") include("sampler.jl") include("scene.jl") include("skin.jl") include("texture.jl") include("object.jl") include("show.jl") function load(path::AbstractString) open(path) do f JSON3.read(read(f, String), Object) end end function save(path::AbstractString, obj::Object) open(path, write=true) do f write(f, JSON3.write(obj)) end end @compile_workload begin filenames = ["DamagedHelmet.gltf"] for filename in filenames path = joinpath(pkgdir(GLTF), "assets", filename) asset = load(path)::Object sprint(show, asset) sprint(show, MIME"text/plain"(), asset) tmp = tempname() save(tmp, asset) load(tmp)::Object rm(tmp) end end end # module
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
5388
mutable struct Indices bufferView::Int byteOffset::Union{Nothing,Int} componentType::Int extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Indices() obj = new() obj.byteOffset = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::Indices, sym::Symbol) x = getfield(obj, sym) sym === :byteOffset && x === nothing && return 0 return x end function Base.setproperty!(obj::Indices, sym::Symbol, x) if sym === :bufferView x ≥ 0 || throw(ArgumentError("the index of the bufferView should be ≥ 0")) elseif sym === :byteOffset && x !== nothing x ≥ 0 || throw(ArgumentError("byteOffset should be ≥ 0")) elseif sym === :componentType x === UNSIGNED_BYTE || x === UNSIGNED_SHORT || x === UNSIGNED_INT || throw(ArgumentError("componentType should be one of: UNSIGNED_BYTE(5121), UNSIGNED_SHORT(5123), UNSIGNED_INT(5125)")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Indices}) = JSON3.Mutable() StructTypes.omitempties(::Type{Indices}) = (:byteOffset, :extensions, :extras) mutable struct Values bufferView::Int byteOffset::Union{Nothing,Int} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Values() obj = new() obj.byteOffset = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::Values, sym::Symbol) x = getfield(obj, sym) sym === :byteOffset && x === nothing && return 0 return x end function Base.setproperty!(obj::Values, sym::Symbol, x) if sym === :bufferView x ≥ 0 || throw(ArgumentError("the index of the bufferView should be ≥ 0")) elseif sym === :byteOffset && x !== nothing x ≥ 0 || throw(ArgumentError("byteOffset should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Values}) = JSON3.Mutable() StructTypes.omitempties(::Type{Values}) = (:byteOffset, :extensions, :extras) mutable struct Sparse count::Int indices::Indices values::Values extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Sparse() obj = new() obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Sparse, sym::Symbol, x) if sym === :count x ≥ 1 || throw(ArgumentError("the number of attributes encoded in this sparse accessor should be ≥ 1")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Sparse}) = JSON3.Mutable() StructTypes.omitempties(::Type{Sparse}) = (:extensions, :extras) mutable struct Accessor bufferView::Union{Nothing,Int} byteOffset::Union{Nothing,Int} componentType::Int normalized::Union{Nothing,Bool} count::Int type::String max::Union{Nothing,Vector} min::Union{Nothing,Vector} sparse::Union{Nothing,Sparse} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Accessor() obj = new() obj.bufferView = nothing obj.byteOffset = nothing obj.normalized = nothing obj.max = nothing obj.min = nothing obj.sparse = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::Accessor, sym::Symbol) x = getfield(obj, sym) sym === :byteOffset && x === nothing && return 0 sym === :normalized && x === nothing && return false return x end function Base.setproperty!(obj::Accessor, sym::Symbol, x) if sym === :bufferView && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the bufferView should be ≥ 0")) elseif sym === :byteOffset && x !== nothing x ≥ 0 || throw(ArgumentError("byteOffset should be ≥ 0")) elseif sym === :componentType x === BYTE || x === UNSIGNED_BYTE || x === SHORT || x === UNSIGNED_SHORT || x === UNSIGNED_INT || x === FLOAT || throw(ArgumentError("componentType should be one of: BYTE(5120), UNSIGNED_BYTE(5121), SHORT(5122), UNSIGNED_SHORT(5123), UNSIGNED_INT(5125), FLOAT(5126)")) elseif sym === :count x ≥ 1 || throw(ArgumentError("the number of attributes referenced by this accessor should be ≥ 1")) elseif sym === :type x === "SCALAR" || x === "VEC2" || x === "VEC3" || x === "VEC4" || x === "MAT2" || x === "MAT3" || x === "MAT4" || throw(ArgumentError("""type should be one of: "SCALAR", "VEC2", "VEC3", "VEC4", "MAT2", "MAT3", "MAT4" """)) elseif sym === :max && x !== nothing len = length(x) len === 1 || len === 2 || len === 3 || len === 4 || len === 9 || len === 16 || throw(ArgumentError("""the length should be one of: 1, 2, 3, 4, 9, 16 """)) elseif sym === :min && x !== nothing len = length(x) len === 1 || len === 2 || len === 3 || len === 4 || len === 9 || len === 16 || throw(ArgumentError("""the length should be one of: 1, 2, 3, 4, 9, 16 """)) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Accessor}) = JSON3.Mutable() StructTypes.omitempties(::Type{Accessor}) = (:bufferView, :byteOffset, :normalized, :max, :min, :sparse, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
3235
mutable struct Target node::Union{Nothing,Int} path::String extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Target() obj = new() obj.node = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Target, sym::Symbol, x) if sym === :node && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the node to target should be ≥ 0")) elseif sym === :path x === "translation" || x === "rotation" || x === "scale" || x === "weights" || throw(ArgumentError("""path should be one of: "translation", "rotation", "scale", "weights" """)) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Target}) = JSON3.Mutable() StructTypes.omitempties(::Type{Target}) = (:node, :extensions, :extras) mutable struct Channel sampler::Int target::Target extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Channel() obj = new() obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Channel, sym::Symbol, x) if sym === :sampler x ≥ 0 || throw(ArgumentError("the index of a sampler used to compute the value for the target should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Channel}) = JSON3.Mutable() StructTypes.omitempties(::Type{Channel}) = (:extensions, :extras) mutable struct AnimationSampler input::Int interpolation::Union{Nothing,String} output::Int extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function AnimationSampler() obj = new() obj.interpolation = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::AnimationSampler, sym::Symbol) x = getfield(obj, sym) sym === :interpolation && x === nothing && return "LINEAR" return x end function Base.setproperty!(obj::AnimationSampler, sym::Symbol, x) if sym === :input x ≥ 0 || throw(ArgumentError("the index of an accessor containing keyframe input values should be ≥ 0")) elseif sym === :interpolation && x !== nothing x === "LINEAR" || x === "STEP" || x === "CUBICSPLINE" || throw(ArgumentError("""interpolation should be one of: "LINEAR", "STEP", "CUBICSPLINE" """)) elseif sym === :output x ≥ 0 || throw(ArgumentError("the index of an accessor containing keyframe output values should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{AnimationSampler}) = JSON3.Mutable() StructTypes.omitempties(::Type{AnimationSampler}) = (:interpolation, :extensions, :extras) mutable struct Animation channels::ZVector{Channel} samplers::ZVector{AnimationSampler} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Animation() obj = new() obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end JSON3.StructType(::Type{Animation}) = JSON3.Mutable() StructTypes.omitempties(::Type{Animation}) = (:name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
597
mutable struct Asset copyright::Union{Nothing,String} generator::Union{Nothing,String} version::String minVersion::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Asset() obj = new() obj.copyright = nothing obj.generator = nothing obj.minVersion = nothing obj.extensions = nothing obj.extras = nothing obj end end JSON3.StructType(::Type{Asset}) = JSON3.Mutable() StructTypes.omitempties(::Type{Asset}) = (:copyright, :generator, :minVersion, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
673
mutable struct Buffer uri::Union{Nothing,String} byteLength::Int name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Buffer() obj = new() obj.uri = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Buffer, sym::Symbol, x) if sym === :byteLength x ≥ 1 || throw(ArgumentError("byteLength should be ≥ 1")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Buffer}) = JSON3.Mutable() StructTypes.omitempties(::Type{Buffer}) = (:uri, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
1589
mutable struct BufferView buffer::Int byteOffset::Union{Nothing,Int} byteLength::Int byteStride::Union{Nothing,Int} target::Union{Nothing,Int} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function BufferView() obj = new() obj.byteOffset = nothing obj.byteStride = nothing obj.target = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::BufferView, sym::Symbol) x = getfield(obj, sym) sym === :byteOffset && x === nothing && return 0 return x end function Base.setproperty!(obj::BufferView, sym::Symbol, x) if sym === :buffer x ≥ 0 || throw(ArgumentError("the index of the buffer should be ≥ 0")) elseif sym === :byteOffset && x !== nothing x ≥ 0 || throw(ArgumentError("byteOffset should be ≥ 0")) elseif sym === :byteLength x ≥ 1 || throw(ArgumentError("byteLength should be ≥ 1")) elseif sym === :byteStride && x !== nothing 4 ≤ x ≤ 252 || throw(ArgumentError("byteStride should be ≥ 4 and ≤ 252")) elseif sym === :target && x !== nothing x === ARRAY_BUFFER || x === ELEMENT_ARRAY_BUFFER || throw(ArgumentError("target should be ARRAY_BUFFER(34962) or ELEMENT_ARRAY_BUFFER(34963)")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{BufferView}) = JSON3.Mutable() StructTypes.omitempties(::Type{BufferView}) = (:byteOffset, :byteStride, :target, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
2791
mutable struct Orthographic xmag::Cfloat ymag::Cfloat zfar::Cfloat znear::Cfloat extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Orthographic() obj = new() obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Orthographic, sym::Symbol, x) if sym === :zfar x > 0 || throw(ArgumentError("the distance to the far clipping plane should be > 0")) elseif sym === :znear x ≥ 0 || throw(ArgumentError("the distance to the near clipping plane should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Orthographic}) = JSON3.Mutable() StructTypes.omitempties(::Type{Orthographic}) = (:extensions, :extras) mutable struct Perspective aspectRatio::Union{Nothing,Cfloat} yfov::Cfloat zfar::Union{Nothing,Cfloat} znear::Cfloat extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Perspective() obj = new() obj.aspectRatio = nothing obj.zfar = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Perspective, sym::Symbol, x) if sym === :aspectRatio && x !== nothing x > 0 || throw(ArgumentError("the aspect ratio of the field of view should be > 0")) elseif sym === :yfov x > 0 || throw(ArgumentError("the vertical field of view in radians should be > 0")) elseif sym === :zfar && x !== nothing x > 0 || throw(ArgumentError("the distance to the far clipping plane should be > 0")) elseif sym === :znear x > 0 || throw(ArgumentError("the distance to the near clipping plane should be > 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Perspective}) = JSON3.Mutable() StructTypes.omitempties(::Type{Perspective}) = (:aspectRatio, :zfar, :extensions, :extras) mutable struct Camera orthographic::Union{Nothing,Orthographic} perspective::Union{Nothing,Perspective} type::String name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Camera() obj = new() obj.orthographic = nothing obj.perspective = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Camera, sym::Symbol, x) if sym === :type x == "perspective" || x == "orthographic" || throw(ArgumentError("""type should be "perspective" or "orthographic" """)) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Camera}) = JSON3.Mutable() StructTypes.omitempties(::Type{Camera}) = (:orthographic, :perspective, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
1061
mutable struct Image uri::Union{Nothing,String} mimeType::Union{Nothing,String} bufferView::Union{Nothing,Int} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Image() obj = new() obj.uri = nothing obj.mimeType = nothing obj.bufferView = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Image, sym::Symbol, x) if sym === :mimeType && x !== nothing x == "image/jpeg" || x == "image/png" || throw(ArgumentError("""the image's MIME type should be "image/jpeg" or "image/png" """)) elseif sym === :bufferView && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the bufferView that contains the image should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Image}) = JSON3.Mutable() StructTypes.omitempties(::Type{Image}) = (:uri, :mimeType, :bufferView, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
7634
mutable struct TextureInfo index::Int texCoord::Union{Nothing,Int} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function TextureInfo() obj = new() obj.texCoord = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::TextureInfo, sym::Symbol) x = getfield(obj, sym) sym === :texCoord && x === nothing && return 0 return x end function Base.setproperty!(obj::TextureInfo, sym::Symbol, x) if sym === :index x ≥ 0 || throw(ArgumentError("the index of the texture should be ≥ 0")) elseif sym === :texCoord && x !== nothing x ≥ 0 || throw(ArgumentError("the set index of texture's TEXCOORD attribute used for texture coordinate mapping should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{TextureInfo}) = JSON3.Mutable() StructTypes.omitempties(::Type{TextureInfo}) = (:texCoord, :extensions, :extras) mutable struct NormalTextureInfo index::Int texCoord::Union{Nothing,Int} scale::Union{Nothing,Cfloat} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function NormalTextureInfo() obj = new() obj.texCoord = nothing obj.scale = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::NormalTextureInfo, sym::Symbol) x = getfield(obj, sym) sym === :texCoord && x === nothing && return 0 sym === :scale && x === nothing && return 1 return x end function Base.setproperty!(obj::NormalTextureInfo, sym::Symbol, x) if sym === :index x ≥ 0 || throw(ArgumentError("the index of the texture should be ≥ 0")) elseif sym === :texCoord && x !== nothing x ≥ 0 || throw(ArgumentError("the set index of texture's TEXCOORD attribute used for texture coordinate mapping should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{NormalTextureInfo}) = JSON3.Mutable() StructTypes.omitempties(::Type{NormalTextureInfo}) = (:texCoord, :scale, :extensions, :extras) mutable struct OcclusionTextureInfo index::Int texCoord::Union{Nothing,Int} strength::Union{Nothing,Cfloat} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function OcclusionTextureInfo() obj = new() obj.texCoord = nothing obj.strength = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::OcclusionTextureInfo, sym::Symbol) x = getfield(obj, sym) sym === :texCoord && x === nothing && return 0 sym === :strength && x === nothing && return 1 return x end function Base.setproperty!(obj::OcclusionTextureInfo, sym::Symbol, x) if sym === :index x ≥ 0 || throw(ArgumentError("the index of the texture should be ≥ 0")) elseif sym === :texCoord && x !== nothing x ≥ 0 || throw(ArgumentError("the set index of texture's TEXCOORD attribute used for texture coordinate mapping should be ≥ 0")) elseif sym === :strength && x !== nothing 0 ≤ x ≤ 1 || throw(ArgumentError("strength should be should be ≥ 0 and ≤ 1")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{OcclusionTextureInfo}) = JSON3.Mutable() StructTypes.omitempties(::Type{OcclusionTextureInfo}) = (:texCoord, :strength, :extensions, :extras) mutable struct PBRMetallicRoughness baseColorFactor::Union{Nothing,Vector{Cfloat}} baseColorTexture::Union{Nothing,TextureInfo} metallicFactor::Union{Nothing,Cfloat} roughnessFactor::Union{Nothing,Cfloat} metallicRoughnessTexture::Union{Nothing,TextureInfo} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function PBRMetallicRoughness() obj = new() obj.baseColorFactor = nothing obj.baseColorTexture = nothing obj.metallicFactor = nothing obj.roughnessFactor = nothing obj.metallicRoughnessTexture = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::PBRMetallicRoughness, sym::Symbol) x = getfield(obj, sym) sym === :baseColorFactor && x === nothing && return Cfloat[1,1,1,1] sym === :metallicFactor && x === nothing && return 1 sym === :roughnessFactor && x === nothing && return 1 return x end function Base.setproperty!(obj::PBRMetallicRoughness, sym::Symbol, x) if sym === :baseColorFactor && x !== nothing length(x) == 4 || throw(ArgumentError("the material's base color factor should exactly contain 4 values(RGBA)")) all(0 .≤ x .≤ 1) || throw(ArgumentError("the material's base color factor value should ≥ 0 and ≤ 1")) elseif sym === :metallicFactor && x !== nothing 0 ≤ x ≤ 1 || throw(ArgumentError("the metalness of the material factor should ≥ 0 and ≤ 1")) elseif sym === :roughnessFactor && x !== nothing 0 ≤ x ≤ 1 || throw(ArgumentError("the roughness of the material factor should ≥ 0 and ≤ 1")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{PBRMetallicRoughness}) = JSON3.Mutable() StructTypes.omitempties(::Type{PBRMetallicRoughness}) = (:baseColorFactor, :baseColorTexture, :metallicFactor, :roughnessFactor, :metallicRoughnessTexture, :extensions, :extras) mutable struct Material pbrMetallicRoughness::Union{Nothing,PBRMetallicRoughness} normalTexture::Union{Nothing,NormalTextureInfo} occlusionTexture::Union{Nothing,OcclusionTextureInfo} emissiveTexture::Union{Nothing,TextureInfo} emissiveFactor::Union{Nothing,Vector{Cfloat}} alphaMode::Union{Nothing,String} alphaCutoff::Union{Nothing,Cfloat} doubleSided::Union{Nothing,Bool} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Material() obj = new() obj.pbrMetallicRoughness = nothing obj.normalTexture = nothing obj.occlusionTexture = nothing obj.emissiveTexture = nothing obj.emissiveFactor = nothing obj.alphaMode = nothing obj.alphaCutoff = nothing obj.doubleSided = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::Material, sym::Symbol) x = getfield(obj, sym) sym === :emissiveFactor && x === nothing && return Cfloat[0,0,0] sym === :alphaMode && x === nothing && return "OPAQUE" sym === :alphaCutoff && x === nothing && return 0.5 sym === :doubleSided && x === nothing && return false return x end function Base.setproperty!(obj::Material, sym::Symbol, x) if sym === :emissiveFactor && x !== nothing length(x) == 3 || throw(ArgumentError("the RGB components of the emissive color of the material should exactly contain 3 values")) all(0 .≤ x .≤ 1) || throw(ArgumentError("the emissive color should be ≥ 0 and ≤ 1")) elseif sym === :alphaMode && x !== nothing x === "OPAQUE" || x === "MASK" || x === "BLEND" || throw(ArgumentError("""the material's alpha rendering mode should be one of: "OPAQUE", "MASK", "BLEND" """)) elseif sym === :alphaCutoff && x !== nothing x ≥ 0 || throw(ArgumentError("alphaCutoff should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Material}) = JSON3.Mutable() StructTypes.omitempties(::Type{Material}) = (:pbrMetallicRoughness, :normalTexture, :occlusionTexture, :emissiveTexture, :emissiveFactor, :alphaMode, :alphaCutoff, :doubleSided, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
2135
mutable struct Primitive attributes::Dict{String,Int} indices::Union{Nothing,Int} material::Union{Nothing,Int} mode::Union{Nothing,Int} targets::Union{Nothing,Vector{Dict}} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Primitive() obj = new() obj.indices = nothing obj.material = nothing obj.mode = nothing obj.targets = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::Primitive, sym::Symbol) x = getfield(obj, sym) sym === :mode && x === nothing && return 4 return x end function Base.setproperty!(obj::Primitive, sym::Symbol, x) if sym === :indices && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the accessor that contains mesh indices should be ≥ 0")) elseif sym === :material && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the material to apply to this primitive when rendering should be ≥ 0")) elseif sym === :mode && x !== nothing x === POINTS || x === LINES || x === LINE_LOOP || x === LINE_STRIP || x === TRIANGLES || x === TRIANGLE_STRIP || x === TRIANGLE_FAN || throw(ArgumentError("the type of primitives to render should be one of: POINTS(0), LINES(1), LINE_LOOP(2), LINE_STRIP(3), TRIANGLES(4), TRIANGLE_STRIP(5), TRIANGLE_FAN(6)")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Primitive}) = JSON3.Mutable() StructTypes.omitempties(::Type{Primitive}) = (:indices, :material, :mode, :targets, :extensions, :extras) mutable struct Mesh primitives::ZVector{Primitive} weights::Union{Nothing,Vector{Cfloat}} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Mesh() obj = new() obj.weights = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end JSON3.StructType(::Type{Mesh}) = JSON3.Mutable() StructTypes.omitempties(::Type{Mesh}) = (:weights, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
2873
mutable struct Node camera::Union{Nothing,Int} children::Union{Nothing,Vector{Int}} skin::Union{Nothing,Int} matrix::Union{Nothing,Vector{Cfloat}} mesh::Union{Nothing,Int} rotation::Union{Nothing,Vector{Cfloat}} scale::Union{Nothing,Vector{Cfloat}} translation::Union{Nothing,Vector{Cfloat}} weights::Union{Nothing,Vector{Cfloat}} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Node() obj = new() obj.camera = nothing obj.children = nothing obj.skin = nothing obj.matrix = nothing obj.mesh = nothing obj.rotation = nothing obj.scale = nothing obj.translation = nothing obj.weights = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::Node, sym::Symbol) x = getfield(obj, sym) sym === :matrix && x === nothing && return Cfloat[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1] sym === :rotation && x === nothing && return Cfloat[0,0,0,1] sym === :scale && x === nothing && return Cfloat[1,1,1] sym === :translation && x === nothing && return Cfloat[0,0,0] return x end function Base.setproperty!(obj::Node, sym::Symbol, x) if sym === :camera && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the camera referenced by this node should be ≥ 0")) elseif sym === :children && x !== nothing all(c->c ≥ 0, x) || throw(ArgumentError("the indices of this node's children should be ≥ 0")) allunique(x) || throw(ArgumentError("children must be unique.")) elseif sym === :skin && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the skin referenced by this node should be ≥ 0")) elseif sym === :matrix && x !== nothing length(x) == 16 || throw(ArgumentError("the length of matrix should be exactly 16")) elseif sym === :mesh && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the mesh in this node should be ≥ 0")) elseif sym === :rotation && x !== nothing length(x) == 4 || throw(ArgumentError("the length of rotation should be exactly 4")) all(-1 .≤ x .≤ 1) || throw(ArgumentError("each element in the unit quaternion rotation should be ≥ -1 and ≤ 1")) elseif sym === :scale && x !== nothing length(x) == 3 || throw(ArgumentError("the length of scale should be exactly 3")) elseif sym === :translation && x !== nothing length(x) == 3 || throw(ArgumentError("the length of translation should be exactly 3")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Node}) = JSON3.Mutable() StructTypes.omitempties(::Type{Node}) = (:camera, :children, :skin, :matrix, :mesh, :rotation, :scale, :translation, :weights, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
1827
mutable struct Object extensionsUsed::Union{Nothing,Vector{String}} extensionsRequired::Union{Nothing,Vector{String}} accessors::Union{Nothing,ZVector{Accessor}} animations::Union{Nothing,ZVector{Animation}} asset::Asset buffers::Union{Nothing,ZVector{Buffer}} bufferViews::Union{Nothing,ZVector{BufferView}} cameras::Union{Nothing,ZVector{Camera}} images::Union{Nothing,ZVector{Image}} materials::Union{Nothing,ZVector{Material}} meshes::Union{Nothing,ZVector{Mesh}} nodes::Union{Nothing,ZVector{Node}} samplers::Union{Nothing,ZVector{Sampler}} scene::Union{Nothing,Int} scenes::Union{Nothing,ZVector{Scene}} skins::Union{Nothing,ZVector{Skin}} textures::Union{Nothing,ZVector{Texture}} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Object() obj = new() obj.extensionsUsed = nothing obj.extensionsRequired = nothing obj.accessors = nothing obj.animations = nothing obj.buffers = nothing obj.bufferViews = nothing obj.cameras = nothing obj.images = nothing obj.materials = nothing obj.meshes = nothing obj.nodes = nothing obj.samplers = nothing obj.scene = nothing obj.scenes = nothing obj.skins = nothing obj.textures = nothing obj.extensions = nothing obj.extras = nothing obj end end JSON3.StructType(::Type{Object}) = JSON3.Mutable() StructTypes.omitempties(::Type{Object}) = (:extensionsUsed, :extensionsRequired, :accessors, :animations, :buffers, :bufferViews, :cameras, :images, :materials, :meshes, :nodes, :samplers, :scene, :scenes, :skins, :textures, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
2066
mutable struct Sampler magFilter::Union{Nothing,Int} minFilter::Union{Nothing,Int} wrapS::Union{Nothing,Int} wrapT::Union{Nothing,Int} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Sampler() obj = new() obj.magFilter = nothing obj.minFilter = nothing obj.wrapS = nothing obj.wrapT = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.getproperty(obj::Sampler, sym::Symbol) x = getfield(obj, sym) sym === :wrapS && x === nothing && return 10497 sym === :wrapT && x === nothing && return 10497 return x end function Base.setproperty!(obj::Sampler, sym::Symbol, x) if sym === :magFilter && x !== nothing x === NEAREST || x === LINEAR || throw(ArgumentError("magFilter should be one of: NEAREST(9728), LINEAR(9729)")) elseif sym === :minFilter && x !== nothing x === NEAREST || x === LINEAR || x === NEAREST_MIPMAP_NEAREST || x === LINEAR_MIPMAP_NEAREST || x === NEAREST_MIPMAP_LINEAR || x === LINEAR_MIPMAP_LINEAR || throw(ArgumentError("minFilter should be one of: NEAREST(9728), LINEAR(9729), NEAREST_MIPMAP_NEAREST(9984), LINEAR_MIPMAP_NEAREST(9985), NEAREST_MIPMAP_LINEAR(9986), LINEAR_MIPMAP_LINEAR(9987)")) elseif sym === :wrapS && x !== nothing x === CLAMP_TO_EDGE || x === MIRRORED_REPEAT || x === REPEAT || throw(ArgumentError("wrapS should be one of: CLAMP_TO_EDGE(33071), MIRRORED_REPEAT(33648), REPEAT(10497)")) elseif sym === :wrapT && x !== nothing x === CLAMP_TO_EDGE || x === MIRRORED_REPEAT || x === REPEAT || throw(ArgumentError("wrapT should be one of: CLAMP_TO_EDGE(33071), MIRRORED_REPEAT(33648), REPEAT(10497)")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Sampler}) = JSON3.Mutable() StructTypes.omitempties(::Type{Sampler}) = (:magFilter, :minFilter, :wrapS, :wrapT, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
833
mutable struct Scene nodes::Union{Nothing,Vector{Int}} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Scene(; nodes=Set(), name=nothing, extensions=Dict(), extras=nothing) obj = new() obj.nodes = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Scene, sym::Symbol, x) if sym === :nodes && x !== nothing all(n->n ≥ 0, x) || throw(ArgumentError("the indices of each root node should be ≥ 0")) allunique(x) || throw(ArgumentError("nodes must be unique.")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Scene}) = JSON3.Mutable() StructTypes.omitempties(::Type{Scene}) = (:nodes, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
722
for ty = (:Primitive, :Mesh, :Skin, :Node, :Scene, :Indices, :Values, :Sparse, :Accessor, :Orthographic, :Perspective, :Camera, :Target, :Channel, :AnimationSampler, :Animation, :Object, :Asset, :Buffer, :BufferView, :Image, :Texture, :Sampler, :TextureInfo, :NormalTextureInfo, :OcclusionTextureInfo, :PBRMetallicRoughness, :Material) @eval begin function Base.show(io::IO, ::MIME"text/plain", x::$ty) print(io, $ty, ":") for name in fieldnames($ty) isdefined(x, name) || continue v = getfield(x, name) v != nothing && print(io, "\n $name: ", v) end end end end
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
1197
mutable struct Skin inverseBindMatrices::Union{Nothing,Int} skeleton::Union{Nothing,Int} joints::Vector{Int} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Skin() obj = new() obj.inverseBindMatrices = nothing obj.skeleton = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Skin, sym::Symbol, x) if sym === :inverseBindMatrices && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the accessor containing the inverse-bind matrices should be ≥ 0")) elseif sym === :skeleton && x !== nothing skeleton ≥ 0 || throw(ArgumentError("the index of the node used as a skeleton root should be ≥ 0")) elseif sym === :joints isempty(x) && throw(ArgumentError("joints should not be empty.")) allunique(x) || throw(ArgumentError("joint number must be unique.")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Skin}) = JSON3.Mutable() StructTypes.omitempties(::Type{Skin}) = (:inverseBindMatrices, :skeleton, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
933
mutable struct Texture sampler::Union{Nothing,Int} source::Union{Nothing,Int} name::Union{Nothing,String} extensions::Union{Nothing,Dict} extras::Union{Nothing,Dict} function Texture() obj = new() obj.sampler = nothing obj.source = nothing obj.name = nothing obj.extensions = nothing obj.extras = nothing obj end end function Base.setproperty!(obj::Texture, sym::Symbol, x) if sym === :sampler && x !== nothing x ≥ 0 || throw(ArgumentError("the index of the sampler used by this texture should be ≥ 0")) elseif sym === :source && x !== nothing source ≥ 0 || throw(ArgumentError("the index of the image used by this texture should be ≥ 0")) end setfield!(obj, sym, x) end JSON3.StructType(::Type{Texture}) = JSON3.Mutable() StructTypes.omitempties(::Type{Texture}) = (:sampler, :source, :name, :extensions, :extras)
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
4381
import Base: IdentityUnitRange, @propagate_inbounds # from https://github.com/JuliaArrays/CustomUnitRanges.jl/blob/master/src/ZeroRange.jl """ ZeroRange(n) Defines an `AbstractUnitRange` corresponding to the half-open interval [0,n), equivalent to `0:n-1` but with the lower bound guaranteed to be zero by Julia's type system. """ struct ZeroRange{T<:Integer} <: AbstractUnitRange{T} len::T ZeroRange{T}(len) where {T} = new{T}(max(zero(T), len)) end ZeroRange(len::T) where {T<:Integer} = ZeroRange{T}(len) Base.length(r::ZeroRange) = r.len Base.length(r::ZeroRange{T}) where {T<:Union{Int,Int64}} = T(r.len) let smallint = (Int === Int64 ? Union{Int8,UInt8,Int16,UInt16,Int32,UInt32} : Union{Int8,UInt8,Int16,UInt16}) Base.length(r::ZeroRange{T}) where {T<:smallint} = Int(r.len) end Base.first(r::ZeroRange{T}) where {T} = zero(T) Base.last(r::ZeroRange{T}) where {T} = r.len-one(T) function Base.iterate(r::ZeroRange{T}) where T r.len <= 0 && return nothing x = oftype(one(T) + one(T), zero(T)) return (x,x) end function Base.iterate(r::ZeroRange{T}, i) where T x = i + one(T) return (x >= oftype(x, r.len) ? nothing : (x,x)) end @inline function Base.getindex(v::ZeroRange{T}, i::Integer) where T @boundscheck ((i > 0) & (i <= length(v))) || Base.throw_boundserror(v, i) convert(T, i-1) end @inline function Base.getindex(r::ZeroRange{R}, s::AbstractUnitRange{S}) where {R,S<:Integer} @boundscheck checkbounds(r, s) R(first(s)-1):R(last(s)-1) end Base.intersect(r::ZeroRange, s::ZeroRange) = ZeroRange(min(r.len,s.len)) Base.promote_rule(::Type{ZeroRange{T1}},::Type{ZeroRange{T2}}) where {T1,T2} = ZeroRange{promote_type(T1,T2)} Base.convert(::Type{ZeroRange{T}}, r::ZeroRange{T}) where {T<:Real} = r Base.convert(::Type{ZeroRange{T}}, r::ZeroRange) where {T<:Real} = ZeroRange{T}(r.len) ZeroRange{T}(r::ZeroRange) where {T} = convert(ZeroRange{T}, r) Base.show(io::IO, r::ZeroRange) = print(io, typeof(r), "(", r.len, ")") Base.show(io::IO, ::MIME"text/plain", r::ZeroRange) = show(io, r) """ ZVector{T} <: AbstractVector{T} Simple 0-based Vector. For a more generic solution, see OffsetArrays.jl. """ struct ZVector{T} <: AbstractVector{T} x::Vector{T} end ZVector() = ZVector(Vector{Any}(undef, 0)) ZVector(::UndefInitializer, m::Integer) = ZVector(Vector{Any}(undef, Int(m))) Base.parent(A::ZVector) = A.x Base.size(A::ZVector) = size(parent(A)) Base.size(A::ZVector, d) = size(parent(A), d) @inline Base.axes(A::ZVector) = (axes(A, 1),) @inline Base.axes(A::ZVector, d) = d == 1 ? IdentityUnitRange(ZeroRange(length(parent(A)))) : IdentityUnitRange(0:0) Base.IndexStyle(::Type{T}) where {T<:ZVector} = IndexLinear() Base.eachindex(::IndexLinear, A::ZVector) = axes(A, 1) Base.length(A::ZVector) = prod(size(A)) Base.isassigned(A::ZVector, i::Integer, j::Integer) = isassigned(A, i) && j == 0 @inline @propagate_inbounds function Base.getindex(A::ZVector{T}, i::Int) where {T} @boundscheck checkbounds(A, i) @inbounds ret = parent(A)[i + 1] ret end @inline @propagate_inbounds function Base.getindex(A::ZVector{T}, I::Vararg{Int,N}) where {T,N} @boundscheck checkbounds(parent(A), (I .+ 1)...) @inbounds ret = parent(A)[(I .+ 1)...] ret end @inline @propagate_inbounds function Base.setindex!(A::ZVector{T}, val, i::Int) where {T} @boundscheck checkbounds(A, i) @inbounds parent(A)[i + 1] = val val end @inline @propagate_inbounds function Base.setindex!(A::ZVector{T}, val, I::Vararg{Int,N}) where {T,N} @boundscheck checkbounds(parent(A), (I .+ 1)...) @inbounds parent(A)[(I .+ 1)...] = val val end indexlength(r::AbstractRange) = length(r) indexlength(i::Integer) = i ZeroRangeIUR{T} = IdentityUnitRange{ZeroRange{T}} Base.similar(A::ZVector) = similar(A, eltype(A), size(A)) Base.similar(A::ZVector, ::Type{T}) where {T} = similar(A, T, size(A)) Base.similar(A::ZVector, dims::Dims{1}) = similar(A, eltype(A), dims) Base.similar(A::ZVector, ::Type{T}, dims::Dims{1}) where {T} = ZVector{T}(undef, first(dims)) Base.similar(A::AbstractVector, ::Type{T}, inds::Tuple{ZeroRangeIUR,Vararg{ZeroRangeIUR}}) where {T} = ZVector(similar(A, T, map(indexlength, inds))) Base.similar(::Type{T}, shape::Tuple{ZeroRangeIUR,Vararg{ZeroRangeIUR}}) where {T<:AbstractArray} = ZVector(T(undef, map(indexlength, shape)))
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
code
1210
using GLTF using Test using Downloads using Pkg const TEST_ASSETS_URL = "https://github.com/KhronosGroup/glTF-Asset-Generator/releases/download/v0.6.1/GeneratedAssets-0.6.1.zip" const TEST_LOCAL_PATH = joinpath(@__DIR__, "download.zip") const ASSETS_LOCAL_PATH = joinpath(@__DIR__, "assets") if !isfile(TEST_LOCAL_PATH) @info "downloading test assets..." Downloads.download(TEST_ASSETS_URL, TEST_LOCAL_PATH) end if Sys.islinux() isdir(ASSETS_LOCAL_PATH) || run(`unzip -x $TEST_LOCAL_PATH -d $ASSETS_LOCAL_PATH`) else p7z = VERSION >= v"1.3.0" ? Pkg.PlatformEngines.find7z() : joinpath(Sys.BINDIR, "7z.exe") isdir(ASSETS_LOCAL_PATH) || run(`$p7z x $TEST_LOCAL_PATH -o$ASSETS_LOCAL_PATH`) end extra_assets = ["DamagedHelmet.gltf"] for asset in extra_assets cp(joinpath(pkgdir(GLTF), "assets", asset), joinpath(ASSETS_LOCAL_PATH, asset); force = true) end @testset "glTF-Asset-Generator" begin for (root, dirs, files) in walkdir(ASSETS_LOCAL_PATH) for file in files if endswith(file, ".gltf") path = joinpath(root, file) @info "loading $path..." @test_nowarn load(path) end end end end;
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.4.0
d9924f00084281f97780846bcc0ae2b8c939b6fe
docs
1742
# GLTF [![CI](https://github.com/Gnimuc/GLTF.jl/actions/workflows/ci.yml/badge.svg)](https://github.com/Gnimuc/GLTF.jl/actions/workflows/ci.yml) [![TagBot](https://github.com/Gnimuc/GLTF.jl/actions/workflows/TagBot.yml/badge.svg)](https://github.com/Gnimuc/GLTF.jl/actions/workflows/TagBot.yml) [![Codecov](https://codecov.io/gh/Gnimuc/GLTF.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/Gnimuc/GLTF.jl) [glTF](https://github.com/KhronosGroup/glTF) 2.0 loader and writer based on [JSON3](https://github.com/quinnj/JSON3.jl). This package only handles .gltf and not .glb. ## Installation ```julia pkg> add GLTF ``` ## Usage glTF file format is just a JSON file + raw binaries. This package defines Julia types that map to the corresponding glTF objects. ```julia julia> using JSON3, GLTF julia> accessor_str = """{ "bufferView": 0, "componentType": 5126, "count": 24, "type": "VEC3", "max": [ 0.3, 0.3, 0.3 ], "min": [ -0.3, -0.3, -0.3 ], "name": "Positions Accessor" }""" "{\n \"bufferView\": 0,\n \"componentType\": 5126,\n \"count\": 24,\n \"type\": \"VEC3\",\n \"max\": [\n 0.3,\n 0.3,\n 0.3\n ],\n \"min\": [\n -0.3,\n -0.3,\n -0.3\n ],\n \"name\": \"Positions Accessor\"\n}" julia> accessor = JSON3.read(accessor_str, GLTF.Accessor) GLTF.Accessor: bufferView: 0 componentType: 5126 count: 24 type: VEC3 max: Any[0.3, 0.3, 0.3] min: Any[-0.3, -0.3, -0.3] name: Positions Accessor ``` load/save file from/to disk: ``` load("path/to/xxx.gltf") # -> GLTF.Object save("path/to/xxx.gltf", x) # where x is of type GLTF.Object ```
GLTF
https://github.com/Gnimuc/GLTF.jl.git
[ "MIT" ]
0.1.2
bb85619109cf797662628ed74c20cda2912e5462
code
572
using SimpleTypePrint using Documenter makedocs(; modules=[SimpleTypePrint], authors="Jiayi Wei <wjydzh1@gmail.com> and contributors", repo="https://github.com/MrVPlusOne/SimpleTypePrint.jl/blob/{commit}{path}#L{line}", sitename="SimpleTypePrint.jl", format=Documenter.HTML(; prettyurls=get(ENV, "CI", "false") == "true", canonical="https://MrVPlusOne.github.io/SimpleTypePrint.jl", assets=String[], ), pages=[ "Home" => "index.md", ], ) deploydocs(; repo="github.com/MrVPlusOne/SimpleTypePrint.jl", )
SimpleTypePrint
https://github.com/MrVPlusOne/SimpleTypePrint.git
[ "MIT" ]
0.1.2
bb85619109cf797662628ed74c20cda2912e5462
code
5592
module SimpleTypePrint export show_type, repr_type, config_type_display """ # Examples ```jldoctest julia> using SimpleTypePrint: print_multiple print_multiple(show, stdout, 1:10, "{", ",", "}") {1,2,3,4,5,6,7,8,9,10} ``` """ function print_multiple(f, io::IO, xs, left="{", sep=",", right="}") n = length(xs)::Int print(io, left) for (i, x) in enumerate(xs) f(io,x) i < n && print(io, sep) end print(io, right) end """ show_type(io, type; kwargs...) """ function show_type(io::IO, @nospecialize(ty::Type); max_depth::Int = 3, short_type_name::Bool = true) t_var_scope::Set{Symbol} = Set{Symbol}() function rec(x::DataType, d) # to be consistent with the Julia Compiler. (x === Tuple) && return Base.show_type_name(io, x.name) if x.name === Tuple.name n = length(x.parameters)::Int if n > 3 && all(i -> (x.parameters[1] === i), x.parameters) # Print homogeneous tuples with more than 3 elements compactly as NTuple print(io, "NTuple{", n, ',') rec(x.parameters[1], d-1) print(io, "}") return end end # hanlde function type specially is_func = startswith(string(nameof(x)), "#") if short_type_name && !is_func print(io, nameof(x)) else Base.show_type_name(io, x.name) end if !isempty(x.parameters) if d ≤ 1 print(io, "{...}") else print_multiple((_,p) -> rec(p, d-1), io, x.parameters) end end end function rec(x::Union, d) if x.a isa DataType && Core.Compiler.typename(x.a) === Core.Compiler.typename(DenseArray) T, N = x.a.parameters if x == StridedArray{T,N} print(io, "StridedArray") print_multiple(show, io, (T,N)) return elseif x == StridedVecOrMat{T} print(io, "StridedVecOrMat") print_multiple(show, io, (T,)) return elseif StridedArray{T,N} <: x print(io, "Union") elems = vcat(StridedArray{T,N}, Base.uniontypes(Core.Compiler.typesubtract(x, StridedArray{T,N}))) print_multiple((_, p) -> rec(p, d-1), io, elems) return end end print(io, "Union") print_multiple((_, p) -> rec(p, d-1), io, Base.uniontypes(x)) end function show_tv_def(tv::TypeVar, d) function show_bound(io::IO, @nospecialize(b)) parens = isa(b,UnionAll) && !Base.print_without_params(b) parens && print(io, "(") rec(b, d-1) parens && print(io, ")") end lb, ub = tv.lb, tv.ub if lb !== Base.Bottom if ub === Any Base.show_unquoted(io, tv.name) print(io, ">:") show_bound(io, lb) else show_bound(io, lb) print(io, "<:") Base.show_unquoted(io, tv.name) end else Base.show_unquoted(io, tv.name) end if ub !== Any print(io, "<:") show_bound(io, ub) end nothing end function rec(x::UnionAll, d, var_group::Vector{TypeVar}=TypeVar[]) # rename tvar as needed var_symb = x.var.name if var_symb === :_ || var_symb ∈ t_var_scope counter = 1 while true newname = Symbol(var_symb, counter) if newname ∉ t_var_scope newtv = TypeVar(newname, x.var.lb, x.var.ub) x = UnionAll(newtv, x{newtv}) break end counter += 1 end end var_symb = x.var.name push!(var_group, x.var) push!(t_var_scope, var_symb) if x.body isa UnionAll # current var group continues rec(x.body, d, var_group) else # current var group ends rec(x.body, d) print(io, " where ") if length(var_group) == 1 show_tv_def(var_group[1], d) else print_multiple((_, v) -> show_tv_def(v, d), io, var_group) end end delete!(t_var_scope, var_symb) end function rec(tv::TypeVar, d) Base.show_unquoted(io, tv.name) end function rec(ohter, d) @nospecialize(other) show(io, ohter) end rec(ty, max_depth) end """ repr_type(ty::Type; kwargs...)::String """ repr_type(ty::Type; kwargs...) = sprint((io,t) -> show_type(io,t; kwargs...), ty) """ config_type_display(;kwargs...) Replace `Base.show(io::IO, x::Type)` with the simpler type printing funciton `show_type`. See also: `show_type`, `repr_type`. """ function config_type_display(;kwargs...) @eval Base.show(io::IO, x::Type) = show_type(io, x; $(kwargs)...) end """ # Keyword args - `max_depth=3`: the maximal type AST depth to show. Type arguments deeper than this value will be printed as `...`. - `short_type_name=true`: when set to `true`, will print simple type names without their corresponding module path. e.g. "Name" instead of "ModuleA.ModuleB.Name". Note that the shorter name will always be used if the type is visible from the current scope. """ show_type, repr_type, config_type_display end # module SimpleTypePrint
SimpleTypePrint
https://github.com/MrVPlusOne/SimpleTypePrint.git
[ "MIT" ]
0.1.2
bb85619109cf797662628ed74c20cda2912e5462
code
2235
module TestSimpleTypePrint if isdefined(@__MODULE__, :LanguageServer) # hack to make vscode linter work properly include("../src/SimpleTypePrint.jl") using .SimpleTypePrint else using SimpleTypePrint: repr_type end using Test module A module B struct Foo{A} end f(x) = x end end macro type_print_test(ty, result) esc(:(@test repr_type($ty) == $result)) end @testset "type simple print" begin @test repr_type(Array{Int64, 2}) == "Array{Int64,2}" @test repr_type(Array{Int64}) == "Array{Int64,N} where N" @test repr_type(Tuple{A,B,C} where {A, B, C}) == "Tuple{A,B,C} where {A,B,C}" let nested = Tuple{Tuple{Tuple{A,B},C},D} where {A,B,C,D} expected = [ "Tuple{...} where {A,B,C,D}", "Tuple{Tuple{...},D} where {A,B,C,D}", "Tuple{Tuple{Tuple{...},C},D} where {A,B,C,D}", "Tuple{Tuple{Tuple{A,B},C},D} where {A,B,C,D}", "Tuple{Tuple{Tuple{A,B},C},D} where {A,B,C,D}", ] @testset "with different depth limit" begin for d in 1:5 @test repr_type(nested, max_depth=d) == expected[d] end end end @test repr_type(A.B.Foo) == "Foo{A} where A" @test endswith(repr_type(A.B.Foo; short_type_name=false), "A.B.Foo{A} where A") @test (repr_type(Tuple{A,B,C} where {A, B >: A, A<:C<:B}) == "Tuple{A,B,C} where {A,B>:A,A<:C<:B}") @test (repr_type(Tuple{A} where {A <: Tuple{Tuple{Tuple{Int64}}}}, max_depth=3) == "Tuple{A} where A<:Tuple{Tuple{...}}") @type_print_test(Tuple{(Tuple{A} where A), A} where A, "Tuple{Tuple{A1} where A1,A} where A") union_s = repr_type(Union{A,B} where {A,B}) @test union_s ∈ ["Union{A,B} where {A,B}", "Union{B,A} where {A,B}"] @type_print_test(StridedArray{T,N} where {T, N}, "StridedArray{T,N} where {T,N}") @type_print_test(StridedVecOrMat{String}, "StridedVecOrMat{String}") @type_print_test NTuple{2, Int64} "Tuple{Int64,Int64}" @type_print_test NTuple{5, Int64} "NTuple{5,Int64}" f_repr = repr_type(typeof(A.B.f)) @test startswith(f_repr, "typeof(") && endswith(f_repr, "A.B.f)") end end # module TestSimpleTypePrint
SimpleTypePrint
https://github.com/MrVPlusOne/SimpleTypePrint.git
[ "MIT" ]
0.1.2
bb85619109cf797662628ed74c20cda2912e5462
docs
2719
# SimpleTypePrint.jl [![Build Status](https://travis-ci.com/MrVPlusOne/SimpleTypePrint.svg?branch=master)](https://travis-ci.com/MrVPlusOne/SimpleTypePrint) [![Coverage](https://codecov.io/gh/MrVPlusOne/SimpleTypePrint/branch/master/graph/badge.svg)](https://codecov.io/gh/MrVPlusOne/SimpleTypePrint) **Display Julia types in a more human-friendly way.** ## Motivation This package provides alternative type printing functions to make it easier to read Julia types. So instead of having to read messy outputs like this: ![Before.png](images/Before.png) Using this package, we can overwrite `Base.show(::IO, ::Type)` to achieve a much cleaner result: ![After.png](images/After.png) ## Usages First, install the package with ```julia Using Pkg; Pkg.add("SimpleTypePrint") ``` You can then override the default type printing behavior by calling ```julia config_type_display(max_depth=3, short_type_name=true) ``` If you prefer not to override the Julia default, you can instead use the provided `show_type(io, type; kwargs...)` and `repr_type(type; kwargs...)` function to manually print selected types. ## Changes compared to `Base.show` - Merging nested where clauses ```julia julia> using SimpleTypePrint: repr_type julia> repr(Tuple{A,B,C} where {A, B, C}) "Tuple{A,B,C} where C where B where A" # By default, Julia display multiple where clauses separately julia> repr_type(Tuple{A,B,C} where {A, B, C}) "Tuple{A,B,C} where {A,B,C}" # Where clauses are correctly merged, just like how you would write them ``` - Displaying deep parts as ellipsis ```julia julia> repr_type(Tuple{Tuple{Tuple{A,B},C},D} where {A,B,C,D}) "Tuple{Tuple{Tuple{...},C},D} where {A,B,C,D}" # By default, the maximal display depth is 3 julia> repr_type(Tuple{Tuple{Tuple{A,B},C},D} where {A,B,C,D}; max_depth=5) "Tuple{Tuple{Tuple{A,B},C},D} where {A,B,C,D}" # You can always increase `max_depth` as needed julia> repr_type(Tuple{A} where {A <: Tuple{Tuple{Tuple{Int}}}}) "Tuple{A} where A<:Tuple{Tuple{...}}" # depth limit also applies to type constraints ``` - Displaying type names without module prefixes ```julia julia> module A module B struct Foo{A} end end end # Foo is nested inside A and B. Main.A julia> repr(A.B.Foo) "Main.A.B.Foo" # By default, Julia displays with module prefixes unless the type is directly visible from the current scope julia> repr_type(A.B.Foo; short_type_name=true) "Foo{A} where A" ``` - Renaming type variables with conflicting names ```julia julia> repr(Tuple{(Tuple{A} where A), A} where A) "Tuple{Tuple{A} where A,A} where A" julia> repr_type(Tuple{(Tuple{A} where A), A} where A) "Tuple{Tuple{A1} where A1,A} where A" ```
SimpleTypePrint
https://github.com/MrVPlusOne/SimpleTypePrint.git
[ "MIT" ]
0.1.2
bb85619109cf797662628ed74c20cda2912e5462
docs
125
```@meta CurrentModule = SimpleTypePrint ``` # SimpleTypePrint ```@index ``` ```@autodocs Modules = [SimpleTypePrint] ```
SimpleTypePrint
https://github.com/MrVPlusOne/SimpleTypePrint.git
[ "MIT" ]
1.1.1
e98272c197bd0dc45fe11299fcf90196f595ba6a
code
7001
# ------------------------------------------------------------------ # Licensed under the MIT License. See LICENSE in the project root. # ------------------------------------------------------------------ module Biplots using Tables using LinearAlgebra using Statistics using Printf import Makie # ----------------------- # TYPES OF NORMALIZATION # ----------------------- center(X) = X .- mean(X, dims=1) function logcenter(X) L = log.(X) μn = mean(L, dims=1) μp = mean(L, dims=2) μ = mean(L) L .- μn .- μp .+ μ end formtransform(X) = (Z=center(X), α=1.0, κ=√(size(X,1)-1)) covtransform(X) = (Z=center(X), α=0.0, κ=1.0 ) rformtransform(X) = (Z=logcenter(X), α=1.0, κ=1.0 ) rcovtransform(X) = (Z=logcenter(X), α=0.0, κ=√size(X,2) ) biplotof = Dict( :form => formtransform, :cov => covtransform, :rform => rformtransform, :rcov => rcovtransform ) """ factors(table; kind=:form, dim=2) Return `F`, `G/k` and `σ²` where `F` and `G` are the factors (i.e. matrices with rank `dim`) of the design matrix `Z` obtained with a given `kind` of transformation. The scalar `κ` scales the column vectors for plotting purposes and the variance explained `σ²` is also returned. """ function factors(table; kind=:form, dim=2) # sanity checks @assert dim ∈ [2,3] "dim must be 2 or 3" @assert kind ∈ [:form,:cov,:rform,:rcov] "$kind is not a valid kind of biplot" # original design matrix X = Tables.matrix(table) # matrix transformation Z, α, κ = biplotof[kind](X) # singular value decomposition U, σ, V = svd(Z) # matrix factors Z ≈ F*G' F = U[:,1:dim] .* (σ[1:dim] .^ α)' G = V[:,1:dim] .* (σ[1:dim] .^ (1 - α))' # variance explained σ² = σ[1:dim] .^ 2 / sum(σ .^ 2) # return scaled factors F, G/κ, σ² end """ biplot(table; kind=:form, dim=2, [aesthetics...]) Biplot of `table` of given `kind` in `dim`-dimensional space. There are four kinds of biplots: * `:form` - standard biplot with shape parameter `α = 1` * `:cov` - standard biplot with shape parameter `α = 0` * `:rform` - relative variation biplot with `α = 1` * `:rcov` - relative variation biplot with `α = 0` # Biplot attributes * `kind` - kind of biplot (`:form`, `:cov`, `:rform` or `:rcov`) * `dim` - number of dimensions `dim ∈ {2,3}` (default to `2`) # Aesthetics attributes * `axescolormap` - colormap of principal axes (default to theme colormap) * `dotcolormap` - colormap of sample dots (default to theme colormap) * `fontsize` - font size in axes and dots (default to `12`) * `axesbody` - size of principal axes' body (depends on `dim`) * `axeshead` - size of principal axes' head (depends on `dim`) * `axescolor` - color of principal axes (default to `:black`) * `axeslabel` - names of principal axes (default to `x1,x2,...`) * `dotsize` - size of sample dots (depends on `dim`) * `dotcolor` - color of sample dots (default to `:black`) * `dotlabel` - names of sample dots (default to `1:nobs`) * `showdots` - show names of dots (default to `true`) * `showlinks` - show links between principal axes (default to`false`) See https://en.wikipedia.org/wiki/Biplot. ## References * Gabriel, K. 1971. [The Biplot Graphic Display of Matrices with Application to Principal Component Analysis] (https://www.jstor.org/stable/2334381) * Aitchison, J. & Greenacre, M. 2002. [Biplots of Compositional data] (https://rss.onlinelibrary.wiley.com/doi/abs/10.1111/1467-9876.00275) """ @Makie.recipe(Biplot, table) do scene Makie.Attributes(; # biplot attributes kind = :form, dim = 2, # aesthetic attributes axescolormap = Makie.theme(scene, :colormap), dotcolormap = Makie.theme(scene, :colormap), fontsize = 12, axesbody = nothing, axeshead = nothing, axescolor = :black, dotsize = nothing, dotcolor = :black, dotlabel = nothing, showdots = true, showlinks = false, ) end function Makie.plot!(plot::Biplot{<:Tuple{Any}}) # biplot attributes table = plot[:table][] kind = plot[:kind][] dim = plot[:dim][] # aesthetics attributes axescolormap = plot[:axescolormap][] dotcolormap = plot[:dotcolormap][] fontsize = plot[:fontsize][] axesbody = plot[:axesbody][] axeshead = plot[:axeshead][] axescolor = plot[:axescolor][] dotsize = plot[:dotsize][] dotcolor = plot[:dotcolor][] dotlabel = plot[:dotlabel][] showdots = plot[:showdots][] showlinks = plot[:showlinks][] # biplot factors F, G, σ² = factors(table, kind=kind, dim=dim) # n samples x p variables n = size(F, 1) p = size(G, 1) # defaults differ on 2 or 3 dimensions if isnothing(axesbody) axesbody = dim == 2 ? 2 : 0.01 end if isnothing(axeshead) axeshead = dim == 2 ? 14 : 0.03 end if axescolor isa AbstractVector{<:Number} min, max = extrema(axescolor) axesscale(x) = x / (max-min) - min / (max - min) axescolor = Makie.cgrad(axescolormap)[axesscale.(axescolor)] end if isnothing(dotsize) dotsize = dim == 2 ? 4 : 10 end if isnothing(dotlabel) dotlabel = string.(1:n) end if dotcolor isa AbstractVector{<:Number} min, max = extrema(dotcolor) dotscale(x) = x / (max-min) - min / (max - min) dotcolor = Makie.cgrad(dotcolormap)[dotscale.(dotcolor)] end # plot principal axes points = fill(Makie.Point(ntuple(i->0., dim)), n) direcs = [Makie.Vec{dim}(v) for v in eachrow(G)] Makie.arrows!(plot, points, direcs, linewidth = axesbody, arrowsize = axeshead, arrowcolor = axescolor, linecolor = axescolor, ) # plot axes names position = Tuple.(direcs) names = Tables.columnnames(table) Makie.text!(plot, collect(string.(names)), position = position, fontsize = fontsize, color = axescolor, ) # plot links between axes if showlinks links = Makie.Vec{dim}[] for i in 1:p for j in i+1:p push!(links, direcs[i]) push!(links, direcs[j]) end end position = Tuple.(links) Makie.linesegments!(plot, position, color = :gray, linestyle = :dash, linewidth = 0.5, ) end # plot samples points = [Makie.Point{dim}(v) for v in eachrow(F)] Makie.scatter!(plot, points, markersize = dotsize, color = dotcolor, ) if showdots # plot samples names position = Tuple.(points) Makie.text!(plot, dotlabel, position = position, fontsize = fontsize, color = dotcolor, ) end # plot variance explained minpos = fill(Inf, dim) for i in 1:dim for direc in direcs if direc[i] < minpos[i] minpos[i] = direc[i] end end for point in points if point[i] < minpos[i] minpos[i] = point[i] end end end textdim = [(@sprintf "Dim %d (%.01f " i 100*v)*"%)" for (i, v) in enumerate(σ²)] Makie.text!(plot, join(textdim, "\n"), position = Tuple(minpos), ) end end
Biplots
https://github.com/MakieOrg/Biplots.jl.git
[ "MIT" ]
1.1.1
e98272c197bd0dc45fe11299fcf90196f595ba6a
code
1692
using Biplots using CairoMakie using ReferenceTests using Test @testset "Biplots.jl" begin # data matrix (22 paintings x 6 colors) data = [ 0.125 0.243 0.153 0.031 0.181 0.266 0.143 0.224 0.111 0.051 0.159 0.313 0.147 0.231 0.058 0.129 0.133 0.303 0.164 0.209 0.120 0.047 0.178 0.282 0.197 0.151 0.132 0.033 0.188 0.299 0.157 0.256 0.072 0.116 0.153 0.246 0.153 0.232 0.101 0.062 0.170 0.282 0.115 0.249 0.176 0.025 0.176 0.259 0.178 0.167 0.048 0.143 0.118 0.347 0.164 0.183 0.158 0.027 0.186 0.281 0.175 0.211 0.070 0.104 0.157 0.283 0.168 0.192 0.120 0.044 0.171 0.305 0.155 0.251 0.091 0.085 0.161 0.257 0.126 0.273 0.045 0.156 0.131 0.269 0.199 0.170 0.080 0.076 0.158 0.318 0.163 0.196 0.107 0.054 0.144 0.335 0.136 0.185 0.162 0.020 0.193 0.304 0.184 0.152 0.110 0.039 0.165 0.350 0.169 0.207 0.111 0.057 0.156 0.300 0.146 0.240 0.141 0.038 0.184 0.250 0.200 0.172 0.059 0.120 0.136 0.313 0.135 0.225 0.217 0.019 0.187 0.217 ] # variable names names = [:Black,:White,:Blue,:Red,:Yellow,:Other] # choose any Tables.jl table table = (; zip(names, eachcol(data))...) fig, ax = biplot(table, kind = :form, dotcolor = table.Red) ax.aspect = DataAspect() @test_reference "data/form.png" fig fig, ax = biplot(table, kind = :cov, dotcolor = table.Red) ax.aspect = DataAspect() @test_reference "data/cov.png" fig fig, ax = biplot(table, kind = :rform, dotcolor = table.Red) ax.aspect = DataAspect() @test_reference "data/rform.png" fig fig, ax = biplot(table, kind = :rcov, dotcolor = table.Red) ax.aspect = DataAspect() @test_reference "data/rcov.png" fig end
Biplots
https://github.com/MakieOrg/Biplots.jl.git
[ "MIT" ]
1.1.1
e98272c197bd0dc45fe11299fcf90196f595ba6a
docs
1640
# Biplots.jl [![Build Status](https://github.com/juliohm/Biplots.jl/workflows/CI/badge.svg)](https://github.com/juliohm/Biplots.jl/actions) [Biplot](https://en.wikipedia.org/wiki/Biplot) recipes in 2D and 3D for Makie.jl. ## Installation Get the latest stable release with Julia's package manager: ```julia ] add Biplots ``` ## Usage ```julia using Biplots using GLMakie # data matrix (22 paintings x 6 colors) data = [ 0.125 0.243 0.153 0.031 0.181 0.266 0.143 0.224 0.111 0.051 0.159 0.313 0.147 0.231 0.058 0.129 0.133 0.303 0.164 0.209 0.120 0.047 0.178 0.282 0.197 0.151 0.132 0.033 0.188 0.299 0.157 0.256 0.072 0.116 0.153 0.246 0.153 0.232 0.101 0.062 0.170 0.282 0.115 0.249 0.176 0.025 0.176 0.259 0.178 0.167 0.048 0.143 0.118 0.347 0.164 0.183 0.158 0.027 0.186 0.281 0.175 0.211 0.070 0.104 0.157 0.283 0.168 0.192 0.120 0.044 0.171 0.305 0.155 0.251 0.091 0.085 0.161 0.257 0.126 0.273 0.045 0.156 0.131 0.269 0.199 0.170 0.080 0.076 0.158 0.318 0.163 0.196 0.107 0.054 0.144 0.335 0.136 0.185 0.162 0.020 0.193 0.304 0.184 0.152 0.110 0.039 0.165 0.350 0.169 0.207 0.111 0.057 0.156 0.300 0.146 0.240 0.141 0.038 0.184 0.250 0.200 0.172 0.059 0.120 0.136 0.313 0.135 0.225 0.217 0.019 0.187 0.217 ] # variable names names = [:Black,:White,:Blue,:Red,:Yellow,:Other] # choose any Tables.jl table table = (; zip(names, eachcol(data))...) # 2D relative variation biplot with colored dots fig, ax = biplot(table, kind = :rform, dotcolor = table.Red) ax.aspect = DataAspect() ``` ![biplot2D](docs/biplot2D.png) Please check the docstring `?biplot` for available attributes.
Biplots
https://github.com/MakieOrg/Biplots.jl.git
[ "MIT" ]
0.1.1
63abcf2fbbf20e52204a4e7529514a6bd10e5b76
code
411
using Documenter, OceanColorData makedocs(; modules=[OceanColorData], format=Documenter.HTML(), pages=[ "Home" => "index.md", ], repo="https://github.com/gaelforget/OceanColorData.jl/blob/{commit}{path}#L{line}", sitename="OceanColorData.jl", authors="gaelforget <gforget@mit.edu>", assets=String[], ) deploydocs(; repo="github.com/gaelforget/OceanColorData.jl", )
OceanColorData
https://github.com/gaelforget/OceanColorData.jl.git
[ "MIT" ]
0.1.1
63abcf2fbbf20e52204a4e7529514a6bd10e5b76
code
6126
using Distributions, NetCDF """ FuzzyClassification(M,Sinv,Rrs) Apply fuzzy membership classifier (`M` + `Sinv`) to a vector of remotely sensed reflectcances (`Rrs`) and returns a membership vector (values between 0 and 1). """ function FuzzyClassification(M,Sinv,Rrs) f=Array{Any,1}(undef,length(M)) for ii=1:length(M) X=vec(Rrs)-M[ii] Z=transpose(X)*Sinv[ii]*X f[ii]=ccdf(Chisq(6),Z) end return f end """ Jackson2017() `Fuzzy logic` classifiers defined in [Moore et al 2009](https://doi.org/10.1016/j.rse.2009.07.016) and [Jackson et al 2017](http://dx.doi.org/10.1016/j.rse.2017.03.036) can be used to assign optical class memberships from an `Rrs` vector. This function provides vector `M` and inverse matrix `Sinv` for the Jackson et al 2017 classifier. Credits: T. Jackson kindly provided the `J17.nc` classifier file """ function Jackson2017() fil=joinpath(dirname(pathof(OceanColorData)),"../examples/J17.nc") tmpM = ncread(fil, "cluster_means") tmpSinv = ncread(fil, "inverse_covariance") M=Array{Any,1}(undef,14) Sinv=Array{Any,1}(undef,14) for ii=1:length(M) M[ii]=vec(tmpM[ii,:]) Sinv[ii]=tmpSinv[1:6,1:6,ii] end return M,Sinv end """ Moore2009() `Fuzzy logic` classifiers defined in [Moore et al 2009](https://doi.org/10.1016/j.rse.2009.07.016) and [Jackson et al 2017](http://dx.doi.org/10.1016/j.rse.2017.03.036) can be used to assign optical class memberships from an `Rrs` vector. This function provides vector `M` and inverse matrix `Sinv` for the Moore et al 2009 classifier. """ function Moore2009() #Moore et al 2009 mean vectors: M=Array{Any,1}(undef,8) M[1]=vec([0.0234 0.0192 0.0129 0.0075 0.0031 0.0002]) M[2]=vec([0.0162 0.0141 0.0112 0.0073 0.0034 0.0002]) M[3]=vec([0.0107 0.0098 0.0092 0.0070 0.0039 0.0003]) M[4]=vec([0.0065 0.0064 0.0070 0.0064 0.0048 0.0006]) M[5]=vec([0.0033 0.0034 0.0042 0.0042 0.0043 0.0009]) M[6]=vec([0.0064 0.0074 0.0105 0.0116 0.0140 0.0041]) M[7]=vec([0.0121 0.0140 0.0192 0.0204 0.0231 0.0084]) M[8]=vec([0.0184 0.0230 0.0333 0.0359 0.0409 0.0137]) #Moore et al 2009 covariance matrices: S=Array{Any,1}(undef,8) S[1]=[0.00000959 0.00000556 0.00000138 -0.00000034 -0.00000024 -0.00000003; 0.00000556 0.00000493 0.00000193 0.00000060 0.00000023 0.00000001; 0.00000138 0.00000193 0.00000282 0.00000223 0.00000119 0.00000007; -0.00000034 0.00000060 0.00000223 0.00000232 0.00000119 0.00000007; -0.00000024 0.00000023 0.00000119 0.00000119 0.00000071 0.00000005; -0.00000003 0.00000001 0.00000007 0.00000007 0.00000005 0.00000001] S[2]=[0.00000346 0.00000186 -0.00000011 -0.00000060 -0.00000062 -0.00000005; 0.00000186 0.00000228 0.00000086 0.00000033 -0.00000007 0.00000003; -0.00000011 0.00000086 0.00000231 0.00000221 0.00000145 0.00000023; -0.00000060 0.00000033 0.00000221 0.00000266 0.00000191 0.00000034; -0.00000062 -0.00000007 0.00000145 0.00000191 0.00000175 0.00000041; -0.00000005 0.00000003 0.00000023 0.00000034 0.00000041 0.00000021] S[3]=[0.00000241 0.00000144 0.00000035 -0.00000031 -0.00000063 -0.00000006; 0.00000144 0.00000138 0.00000076 0.00000015 -0.00000021 -0.00000001; 0.00000035 0.00000076 0.00000161 0.00000156 0.00000121 0.00000016; -0.00000031 0.00000015 0.00000156 0.00000227 0.00000209 0.00000031; -0.00000063 -0.00000021 0.00000121 0.00000209 0.00000225 0.00000037; -0.00000006 -0.00000001 0.00000016 0.00000031 0.00000037 0.00000013] S[4]=[0.00000166 0.00000091 0.00000034 -0.00000009 -0.00000080 -0.00000025; 0.00000091 0.00000097 0.00000071 0.00000025 -0.00000041 -0.00000015; 0.00000034 0.00000071 0.00000118 0.00000103 0.00000072 0.00000003; -0.00000009 0.00000025 0.00000103 0.00000137 0.00000162 0.00000025; -0.00000080 -0.00000041 0.00000072 0.00000162 0.00000290 0.00000065; -0.00000025 -0.00000015 0.00000003 0.00000025 0.00000065 0.00000050] S[5]=[0.00000178 0.00000132 0.00000104 0.00000081 0.00000018 -0.00000014; 0.00000132 0.00000127 0.00000121 0.00000099 0.00000034 -0.00000010; 0.00000104 0.00000121 0.00000150 0.00000142 0.00000110 0.00000013; 0.00000081 0.00000099 0.00000142 0.00000158 0.00000177 0.00000042; 0.00000018 0.00000034 0.00000110 0.00000177 0.00000351 0.00000131; -0.00000014 -0.00000010 0.00000013 0.00000042 0.00000131 0.00000081] S[6]=[0.00000715 0.00000586 0.00000409 0.00000292 0.00000005 -0.00000075; 0.00000586 0.00000589 0.00000520 0.00000398 0.00000027 -0.00000114; 0.00000409 0.00000520 0.00000634 0.00000541 0.00000188 -0.00000097; 0.00000292 0.00000398 0.00000541 0.00000528 0.00000392 0.00000070; 0.00000005 0.00000027 0.00000188 0.00000392 0.00000995 0.00000657; -0.00000075 -0.00000114 -0.00000097 0.00000070 0.00000657 0.00000819] S[7]=[0.00002625 0.00001981 0.00001058 0.00000544 -0.00000654 -0.00001122; 0.00001981 0.00001745 0.00001314 0.00000822 -0.00000431 -0.00001228; 0.00001058 0.00001314 0.00001629 0.00001226 0.00000035 -0.00001311; 0.00000544 0.00000822 0.00001226 0.00001170 0.00000742 -0.00000500; -0.00000654 -0.00000431 0.00000035 0.00000742 0.00002241 0.00001782; -0.00001122 -0.00001228 -0.00001311 -0.00000500 0.00001782 0.00003987] S[8]=[0.00001186 0.00001134 0.00001139 0.00000919 0.00000395 -0.00000186; 0.00001134 0.00001484 0.00002034 0.00001907 0.00001531 0.00000087; 0.00001139 0.00002034 0.00003467 0.00003546 0.00003555 0.00000708; 0.00000919 0.00001907 0.00003546 0.00003907 0.00004604 0.00001733; 0.00000395 0.00001531 0.00003555 0.00004604 0.00007306 0.00004953; -0.00000186 0.00000087 0.00000708 0.00001733 0.00004953 0.00006542]; Sinv=inv.(S) return M,Sinv end
OceanColorData
https://github.com/gaelforget/OceanColorData.jl.git
[ "MIT" ]
0.1.1
63abcf2fbbf20e52204a4e7529514a6bd10e5b76
code
2380
""" RemotelySensedReflectance(rirr_in,wvbd_in,wvbd_out) Compute remotely sensed reflectance at wvbd_out from irradiance reflectance at wvbd_in. ``` wvbd_out=Float64.([412, 443, 490, 510, 555, 670]) wvbd_in=Float64.([400,425,450,475,500,525,550,575,600,625,650,675,700]) rirr_in=1e-3*[23.7641,26.5037,27.9743,30.4914,28.1356, 21.9385,18.6545,13.5100,5.6338,3.9272,2.9621,2.1865,1.8015] rrs_out=RemotelySensedReflectance(rirr_in,wvbd_in,wvbd_out) using Plots plot(vec(rrs_out),linewidth=4,lab="recomputed RRS") rrs_ref=1e-3*[4.4099, 4.8533, 5.1247, 4.5137, 3.0864, 0.4064] plot!(rrs_ref,linewidth=4,ls=:dash,lab="reference result") ``` """ function RemotelySensedReflectance(rirr_in,wvbd_in,wvbd_out) rrs_out=similar(wvbd_out) nin=length(wvbd_in) nout=length(wvbd_out) jj=Array{Int64,1}(undef,nin) ww=Array{Float64,1}(undef,nin) for ii=1:6 tmp=wvbd_out[ii].-wvbd_in kk=maximum(findall(tmp.>=0)) jj[ii]=kk ww[ii]=tmp[kk]/(wvbd_in[kk+1]-wvbd_in[kk]) end tmp=rirr_in/3 rrs_tmp=(0.52*tmp)./(1.0 .-1.7*tmp); rrs_out=Array{Float64,1}(undef,nout) for vv=1:6 tmp0=rrs_tmp[jj[vv]] tmp1=rrs_tmp[jj[vv]+1] rrs_out[vv]=tmp0.*(1-ww[vv])+tmp1.*ww[vv] end return rrs_out end """ RrsToChla(Rrs; Eqn="OC4") Satellite `Chl_a` estimates typicaly derive from remotely sensed reflectances using the blue/green reflectance ratio method and a polynomial formulation. ``` wvbd_out=Float64.([412, 443, 490, 510, 555, 670]) wvbd_in=Float64.([400,425,450,475,500,525,550,575,600,625,650,675,700]) rirr_in=1e-3*[23.7641,26.5037,27.9743,30.4914,28.1356, 21.9385,18.6545,13.5100,5.6338,3.9272,2.9621,2.1865,1.8015] rrs_out=RemotelySensedReflectance(rirr_in,wvbd_in,wvbd_out) chla_out=RrsToChla(rrs_out) ``` """ function RrsToChla(Rrs;Eqn="OC4") RRSB=max.(Rrs[2],Rrs[3]) #blue RRSG=Rrs[5] #green X = log10.(RRSB./RRSG) #ratio of blue to green if Eqn=="OC4" C=[0.3272, -2.9940, +2.7218, -1.2259, -0.5683] #OC4 algorithms (SeaWifs, CCI) elseif Eqn=="OC3M-547" C=[0.2424, -2.7423, 1.8017, 0.0015, -1.2280] #OC3M-547 algorithm (MODIS) else error("this case has not been implemented yet...") end a0=C[1]; a1=C[2]; a2=C[3]; a3=C[4]; a4=C[5]; chld=exp10.(a0.+a1*X+a2*X.^2+a3*X.^3+a4*X.^4); #apply polynomial recipe end
OceanColorData
https://github.com/gaelforget/OceanColorData.jl.git
[ "MIT" ]
0.1.1
63abcf2fbbf20e52204a4e7529514a6bd10e5b76
code
185
module OceanColorData include("Conversions.jl") include("Classifiers.jl") export RemotelySensedReflectance, RrsToChla export FuzzyClassification, Moore2009, Jackson2017 end # module
OceanColorData
https://github.com/gaelforget/OceanColorData.jl.git
[ "MIT" ]
0.1.1
63abcf2fbbf20e52204a4e7529514a6bd10e5b76
code
1020
using OceanColorData using Test @testset "OceanColorData.jl" begin wvbd_out=[412, 443, 490, 510, 555, 670] wvbd_in=[400,425,450,475,500,525,550,575,600,625,650,675,700] rirr_in=1e-3*[23.7641,26.5037,27.9743,30.4914,28.1356, 21.9385,18.6545,13.5100,5.6338,3.9272,2.9621,2.1865,1.8015] rrs_ref=1e-3*[4.4099, 4.8533, 5.1247, 4.5137, 3.0864, 0.4064] chla_ref=0.6101219875535429 fcm_ref=[5.683734365402806e-26, 4.958850399758996e-64, 2.0058235898296587e-43, 2.399985306394786e-23, 1.0914931954631329e-15, 3.610712128260008e-8, 0.06660122938880934, 0.4566726319832639, 0.001153891939362191, 5.901424234631198e-11, 1.8433658038301877e-10, 0.4133547888920851, 0.027225883646784382, 0.005595266829573927] rrs_out=RemotelySensedReflectance(rirr_in,wvbd_in,wvbd_out) chla_out=RrsToChla(rrs_out; Eqn="OC4") (M,Sinv)=Jackson2017() fcm_out=FuzzyClassification(M,Sinv,rrs_out) @test isapprox(rrs_out,rrs_ref,atol=1e-5) @test isapprox(chla_out,chla_ref,atol=1e-5) @test isapprox(fcm_out,fcm_ref,atol=1e-5) end
OceanColorData
https://github.com/gaelforget/OceanColorData.jl.git
[ "MIT" ]
0.1.1
63abcf2fbbf20e52204a4e7529514a6bd10e5b76
docs
1007
# OceanColorData.jl [![Stable](https://img.shields.io/badge/docs-stable-blue.svg)](https://gaelforget.github.io/OceanColorData.jl/stable) [![Dev](https://img.shields.io/badge/docs-dev-blue.svg)](https://gaelforget.github.io/OceanColorData.jl/dev) [![Build Status](https://travis-ci.org/gaelforget/OceanColorData.jl.svg?branch=master)](https://travis-ci.org/gaelforget/OceanColorData.jl) [![Codecov](https://codecov.io/gh/gaelforget/OceanColorData.jl/branch/master/graph/badge.svg)](https://codecov.io/gh/gaelforget/OceanColorData.jl) [![Coveralls](https://coveralls.io/repos/github/gaelforget/OceanColorData.jl/badge.svg?branch=master)](https://coveralls.io/github/gaelforget/OceanColorData.jl?branch=master) [![DOI](https://zenodo.org/badge/248762827.svg)](https://zenodo.org/badge/latestdoi/248762827) Processing and analysis of [ocean color data](https://en.wikipedia.org/wiki/Ocean_color#Ocean_color_radiometry). _This package is in early developement stage when breaking changes can be expected._
OceanColorData
https://github.com/gaelforget/OceanColorData.jl.git
[ "MIT" ]
0.1.1
63abcf2fbbf20e52204a4e7529514a6bd10e5b76
docs
150
# OceanColorData.jl This package is at a very early stage of development. Stay tuned ... ```@index ``` ```@autodocs Modules = [OceanColorData] ```
OceanColorData
https://github.com/gaelforget/OceanColorData.jl.git
[ "MIT" ]
2.4.0
313ea256ced33aa6039987c9fef57e59aa229589
code
209
append!(empty!(LOAD_PATH), Base.DEFAULT_LOAD_PATH) using Pkg exampledir = joinpath(@__DIR__, "..", "examples") Pkg.activate(exampledir) Pkg.instantiate() include(joinpath(exampledir, "generate_notebooks.jl"))
RigidBodyDynamics
https://github.com/JuliaRobotics/RigidBodyDynamics.jl.git